text
stringlengths
54
60.6k
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011-2012 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society * Written (W) 2012 Victor Sadkov * Copyright (C) 2011 Moscow State University */ #include <shogun/base/init.h> #include <shogun/mathematics/Statistics.h> #include <shogun/mathematics/Math.h> using namespace shogun; void test_confidence_intervals() { int32_t data_size=100; SGVector<float64_t> data(data_size); CMath::random_vector(data.vector, data.vlen, 0.0, 1.0); float64_t low, up, mean; float64_t error_prob=0.1; mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up); SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n", mean, low, up, 100*(1-error_prob)); SG_SPRINT("variance: %f\n", CStatistics::variance(data)); SG_SPRINT("deviation: %f\n", CStatistics::std_deviation(data)); } void test_inverse_incomplete_gamma() { /* some tests for high precision MATLAB comparison */ float64_t difference=CStatistics::inverse_incomplete_gamma(1, 1-0.95)*2; difference-=5.991464547107981; difference=CMath::abs(difference); ASSERT(difference<=10E-15); difference=CStatistics::inverse_incomplete_gamma(0, 1-0.95)*3; ASSERT(difference==0); difference=CStatistics::inverse_incomplete_gamma(2, 1-0.95)*0.1; difference-=0.474386451839058; difference=CMath::abs(difference); ASSERT(difference<=10E-15) } int main(int argc, char **argv) { init_shogun_with_defaults(); test_confidence_intervals(); test_inverse_incomplete_gamma(); exit_shogun(); return 0; } <commit_msg>fixed a non-terminating test case<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011-2012 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society * Written (W) 2012 Victor Sadkov * Copyright (C) 2011 Moscow State University */ #include <shogun/base/init.h> #include <shogun/mathematics/Statistics.h> #include <shogun/mathematics/Math.h> using namespace shogun; void test_confidence_intervals() { int32_t data_size=100; SGVector<float64_t> data(data_size); CMath::random_vector(data.vector, data.vlen, 0.0, 1.0); float64_t low, up, mean; float64_t error_prob=0.1; mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up); SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n", mean, low, up, 100*(1-error_prob)); SG_SPRINT("variance: %f\n", CStatistics::variance(data)); SG_SPRINT("deviation: %f\n", CStatistics::std_deviation(data)); } void test_inverse_incomplete_gamma() { /* some tests for high precision MATLAB comparison */ float64_t difference=CStatistics::inverse_incomplete_gamma(1, 1-0.95)*2; difference-=5.991464547107981; difference=CMath::abs(difference); ASSERT(difference<=10E-15); difference=CStatistics::inverse_incomplete_gamma(0.1, 1-0.95)*3; difference-=1.741305315969402; difference=CMath::abs(difference); ASSERT(difference<=10E-15) difference=CStatistics::inverse_incomplete_gamma(2, 1-0.95)*0.1; difference-=0.474386451839058; difference=CMath::abs(difference); ASSERT(difference<=10E-15) } int main(int argc, char **argv) { init_shogun_with_defaults(); test_confidence_intervals(); test_inverse_incomplete_gamma(); exit_shogun(); return 0; } <|endoftext|>
<commit_before>#include "clm.h" void JelinekMercerFeature::set_interpolation(float lambda) { this->_bigram_contribution = 1.0 - lambda; this->_unigram_contribution = lambda; } float JelinekMercerFeature::interpolation() const { return this->_unigram_contribution; } void JelinekMercerFeature::set_slop(int slop) { assert(slop >= 0); _slop = slop; } void JelinekMercerFeature::set_censor_slop(bool censor_slop) { _censor_slop = censor_slop; } bool JelinekMercerFeature::censor_slop() const { return _censor_slop; } int JelinekMercerFeature::slop() const { return _slop; } void JelinekMercerFeature::set_cutoff(float cutoff) { _cutoff = cutoff; } float JelinekMercerFeature::cutoff() const { return _cutoff; } void JelinekMercerFeature::set_score(bool score) { _score = score; } bool JelinekMercerFeature::score() const { return _score; } void JelinekMercerFeature::set_log_length(bool log_length) { _log_length = log_length; } bool JelinekMercerFeature::log_length() const { return _log_length; } void JelinekMercerFeature::set_min_span(int span) { _min_span = span; } int JelinekMercerFeature::min_span() const { return _min_span; } void JelinekMercerFeature::set_min_start_rank(int rank) { _min_start_rank = rank; } int JelinekMercerFeature::min_start_rank() const { return _min_start_rank; } void JelinekMercerFeature::set_smooth(float smooth) { assert(smooth > 0.0); _smooth = smooth; _smooth_norm = smooth * (float)_vocab; } float JelinekMercerFeature::smooth() const { return _smooth; } void JelinekMercerFeature::add_stop(int word) { _stopwords.insert(word); } void JelinekMercerFeature::read_vocab(const std::string filename) { std::ifstream infile; infile.open(filename.c_str()); int type; int count; int contexts; int next; std::string word; infile >> _corpora; infile >> _vocab; _types.resize(_vocab); _corpus_names.resize(_corpora); for (int ii=0; ii < _vocab; ++ii) { infile >> word; _types[ii] = word; if (ii % 25000 == 0) std::cout << "Read vocab " << word << " (" << ii << "/" << _vocab << ")" << std::endl; } this->_unigram.resize(_corpora); this->_bigram.resize(_corpora); this->_normalizer.resize(_corpora); this->_compare.resize(_corpora); /* * Size the counts appropriately */ for (int cc=0; cc < _corpora; ++cc) { infile >> _corpus_names[cc]; infile >> _compare[cc]; _normalizer[cc] = 0; } std::cout << "Done reading " << _vocab << " vocab from " << _corpora << " corpora" << std::endl; } /* * Read in a protocol buffers contents and add to counts */ void JelinekMercerFeature::read_counts(const std::string filename) { std::cout << "reading corpus from " << filename << " ("; std::ifstream infile; infile.open(filename.c_str()); int corpus_id; std::string corpus_name; int num_contexts; infile >> corpus_name; infile >> corpus_id; infile >> num_contexts; std::cout << corpus_name << "," << corpus_id << ")" << std::endl; assert(_corpora > 0); assert(_normalizer[corpus_id] == 0.0); for (int vv=0; vv < num_contexts; ++vv) { // Set unigram counts int total; int first; int num_bigrams; std::string word; infile >> word; infile >> first; infile >> total; infile >> num_bigrams; _normalizer[corpus_id] += (float)total; _unigram[corpus_id][first] = total; assert(word == _types[first]); for (int bb=0; bb < num_bigrams; ++bb) { int second; int count; infile >> second; infile >> count; _bigram[corpus_id][bigram(first, second)] = count; } } infile.close(); } int JelinekMercerFeature::bigram_count(int corpus, int first, int second) { bigram key = bigram(first, second); if (_bigram[corpus].find(key) == _bigram[corpus].end()) return 0; else return _bigram[corpus][key]; } int JelinekMercerFeature::unigram_count(int corpus, int word) { if (_unigram[corpus].find(word) == _unigram[corpus].end()) return 0; else return _unigram[corpus][word]; } int JelinekMercerFeature::sum(int *first, int nitems) { int i, sum = 0; for (i = 0; i < nitems; i++) { sum += first[i]; } return sum; } const std::string JelinekMercerFeature::feature(const std::string name, int corpus, int *sent, int length) { assert(length > 0); assert(corpus < _corpora); int baseline = _compare[corpus]; // Create vectors to hold probabilities and masks _slop_mask.resize(length); std::fill(_slop_mask.begin(), _slop_mask.end(), false); _span_mask.resize(length); _span_start.resize(length); _d_bigram.resize(length); _b_bigram.resize(length); _d_unigram.resize(length); _b_unigram.resize(length); // Step 1: find the spans // Consider the first word part of a span unless it's very frequent // This will also contribute to the overall likelihood computation later _span_mask[0] = true; // Extend from the first position. Also compute the total likelihood while // we're at it. for (int ii=1; ii < length; ++ii) { if (this->bigram_count(corpus, sent[ii - 1], sent[ii]) > 0) { // The current word is only true if the previous word was or it isn't // too frequent. _span_mask[ii] = _span_mask[ii - 1] || (sent[ii] >= _min_start_rank && _stopwords.find(sent[ii]) == _stopwords.end()); } else { _span_mask[ii] = false; } } if (kDEBUG) { for (int ii=0; ii < length; ++ii) { if (_span_mask[ii]) std::cout << "\t" << "+" << _types[sent[ii]]; else std::cout << "\t" << "-" << _types[sent[ii]]; } std::cout << "\t<- tokens/mask" << std::endl; } // Filter spans that end with high-frequency words for (int ii=length; ii >= 0; --ii) { if (_span_mask[ii] && // It is in a span (ii==length || !_span_mask[ii+1]) && // at the end sent[ii] < _min_start_rank) {// and is high frequency _span_mask[ii] = false; // Then remove it from span } } // Add back in slop if (_slop > 0) { int position = 2; while (position < length - 1) { // Could this position expand a run if we had slop? if (_span_mask[position - 1] && !_span_mask[position]) { int slop_left = _slop; for (int ii=position; ii < std::min(position + _slop, length - 1); ++ii) { // If this is a LM hit, then // mark all positions before it as a slop position if (!_span_mask[ii]) { _slop_mask[ii] = true; --slop_left; } if (slop_left == 0) break; position = ii; } ++position; } else { // There's no run to expand, so just move onto the next position. ++position; } } } // For each element in the span, figure out where its span begins and compute // probabilities. _b_unigram[0] = this->score(baseline, -1, sent[0]); _d_unigram[0] = this->score(corpus, -1, sent[0]); float complete_prob = _d_unigram[0] - _b_unigram[0]; int start = -1; for (int ii=0; ii < length; ++ii) { // Do we end a span? if (!(_span_mask[ii] || _slop_mask[ii])) { start = -1; } else { // Do we start a new one? if (start < 0) start = ii; // If we're in a span, we'll want unigram probabilities _d_unigram[ii] = this->score(corpus, -1, sent[ii]); _b_unigram[ii] = this->score(baseline, -1, sent[ii]); } _span_start[ii] = start; // save the probabilities for later span calculations _d_bigram[ii] = this->score(corpus, sent[ii - 1], sent[ii]); _b_bigram[ii] = this->score(baseline, sent[ii - 1], sent[ii]); complete_prob += _d_bigram[ii] - _b_bigram[ii]; } if (kDEBUG) { std::cout << "\tX"; for (int ii=1; ii < length; ++ii) std::cout << "\t" << this->bigram_count(corpus, sent[ii-1], sent[ii]); std::cout << std::endl; for (int ii=0; ii < length; ++ii) { if (_span_mask[ii]) std::cout << "\t" << "+"; else std::cout << "\t" << "-"; } std::cout << "\t<- revision" << std::endl; for (int ii=0; ii < length; ++ii) { if (_slop_mask[ii]) std::cout << "\t" << "+"; else std::cout << "\t" << "-"; } std::cout << "\t<- slop" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << _span_start[ii]; std::cout << "\t<- start" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_bigram[ii]; std::cout << "\t<- domain bigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_bigram[ii]; std::cout << "\t<- base bigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_count(corpus, sent[ii]); std::cout << "\t<- domain unigram count" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_norm(corpus); std::cout << "\t<- domain unigram norm" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_unigram[ii]; std::cout << "\t<- domain unigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_unigram[ii]; std::cout << "\t<- base unigram" << std::endl; } // Now we can output the feature and compute the probability of spans std::ostringstream buffer; buffer << std::fixed; buffer << std::setprecision(2); int longest_span = 0; float max_prob = 0; for (int ii=1; ii < length; ++ii) { if (_span_start[ii] >= 0) { if (ii - _span_start[ii] >= longest_span) longest_span = ii - _span_start[ii] + 1; // Skip if it's too short if (ii - _span_start[ii] < _min_span - 1) continue; for (int start = _span_start[ii]; start <= ii - _min_span; ++start) { float span_probability; if (_stopwords.find(sent[start]) != _stopwords.end()) continue; span_probability = _d_unigram[start] - _b_unigram[start]; // First compute the span probabilities for (int jj = start + 1; jj <= ii; ++jj) { span_probability += _d_bigram[jj] - _b_bigram[jj]; } if (span_probability > _cutoff) { if (span_probability > max_prob) max_prob = span_probability; buffer << _corpus_names[corpus]; for (int jj = start; jj <= ii; ++jj) { buffer << "_"; if (_censor_slop && _slop_mask[jj]) buffer << "SLOP"; else buffer << sent[jj]; } if (_score) { buffer << ":"; buffer << span_probability; } buffer << " "; } } } } // Output the probability if (_score) { buffer << name; buffer << "_PROB:"; buffer << complete_prob / ((float)length); buffer << " "; buffer << name; buffer << "_MAX:"; buffer << max_prob; buffer << " "; } buffer << name; buffer << "_LEN:"; buffer << longest_span; if (_log_length) { buffer << " " << name; buffer << "_LGLEN:"; buffer << log(1 + longest_span); } return buffer.str(); } float JelinekMercerFeature::unigram_norm(int corpus) { return (float)this->_normalizer[corpus] + _smooth_norm; } float JelinekMercerFeature::score(int corpus, int first, int second) { // Store the unigram probability in the score float unigram_num = (float)this->unigram_count(corpus, second) + _smooth; float unigram_den = this->unigram_norm(corpus); float score = unigram_num / unigram_den; if (kDEBUG) { std::cout << _corpus_names[corpus] << " LL for " << first; //if (first >= 0) std::cout << "(" << _types[first] << ")"; std::cout << " " << second << "(" << _types[second] << ")" << std::endl; std::cout << "UNI:" << unigram_num << "/" << unigram_den << "=" << score << std::endl; } if (first >= 0) { // first == -1 means we just want unigram probability int bigram_den = this->unigram_count(corpus, first); int bigram_num = this->bigram_count(corpus, first, second); if (bigram_den == 0 || bigram_num == 0) { score *= _unigram_contribution; } else { score = this->_bigram_contribution * (float)bigram_num / (float)bigram_den + _unigram_contribution * score; } } if (kDEBUG) { std::cout << "Final:" << log(score) << std::endl; } return log(score); } <commit_msg>shorten lines<commit_after>#include "clm.h" void JelinekMercerFeature::set_interpolation(float lambda) { this->_bigram_contribution = 1.0 - lambda; this->_unigram_contribution = lambda; } float JelinekMercerFeature::interpolation() const { return this->_unigram_contribution; } void JelinekMercerFeature::set_slop(int slop) { assert(slop >= 0); _slop = slop; } void JelinekMercerFeature::set_censor_slop(bool censor_slop) { _censor_slop = censor_slop; } bool JelinekMercerFeature::censor_slop() const { return _censor_slop; } int JelinekMercerFeature::slop() const { return _slop; } void JelinekMercerFeature::set_cutoff(float cutoff) { _cutoff = cutoff; } float JelinekMercerFeature::cutoff() const { return _cutoff; } void JelinekMercerFeature::set_score(bool score) { _score = score; } bool JelinekMercerFeature::score() const { return _score; } void JelinekMercerFeature::set_log_length(bool log_length) { _log_length = log_length; } bool JelinekMercerFeature::log_length() const { return _log_length; } void JelinekMercerFeature::set_min_span(int span) { _min_span = span; } int JelinekMercerFeature::min_span() const { return _min_span; } void JelinekMercerFeature::set_min_start_rank(int rank) { _min_start_rank = rank; } int JelinekMercerFeature::min_start_rank() const { return _min_start_rank; } void JelinekMercerFeature::set_smooth(float smooth) { assert(smooth > 0.0); _smooth = smooth; _smooth_norm = smooth * (float)_vocab; } float JelinekMercerFeature::smooth() const { return _smooth; } void JelinekMercerFeature::add_stop(int word) { _stopwords.insert(word); } void JelinekMercerFeature::read_vocab(const std::string filename) { std::ifstream infile; infile.open(filename.c_str()); int type; int count; int contexts; int next; std::string word; infile >> _corpora; infile >> _vocab; _types.resize(_vocab); _corpus_names.resize(_corpora); for (int ii=0; ii < _vocab; ++ii) { infile >> word; _types[ii] = word; if (ii % 25000 == 0) std::cout << "Read vocab " << word << " (" << ii << "/" << _vocab << ")" << std::endl; } this->_unigram.resize(_corpora); this->_bigram.resize(_corpora); this->_normalizer.resize(_corpora); this->_compare.resize(_corpora); /* * Size the counts appropriately */ for (int cc=0; cc < _corpora; ++cc) { infile >> _corpus_names[cc]; infile >> _compare[cc]; _normalizer[cc] = 0; } std::cout << "Done reading " << _vocab << " vocab from " << _corpora << " corpora" << std::endl; } /* * Read in a protocol buffers contents and add to counts */ void JelinekMercerFeature::read_counts(const std::string filename) { std::cout << "reading corpus from " << filename << " ("; std::ifstream infile; infile.open(filename.c_str()); int corpus_id; std::string corpus_name; int num_contexts; infile >> corpus_name; infile >> corpus_id; infile >> num_contexts; std::cout << corpus_name << "," << corpus_id << ")" << std::endl; assert(_corpora > 0); assert(_normalizer[corpus_id] == 0.0); for (int vv=0; vv < num_contexts; ++vv) { // Set unigram counts int total; int first; int num_bigrams; std::string word; infile >> word; infile >> first; infile >> total; infile >> num_bigrams; _normalizer[corpus_id] += (float)total; _unigram[corpus_id][first] = total; assert(word == _types[first]); for (int bb=0; bb < num_bigrams; ++bb) { int second; int count; infile >> second; infile >> count; _bigram[corpus_id][bigram(first, second)] = count; } } infile.close(); } int JelinekMercerFeature::bigram_count(int corpus, int first, int second) { bigram key = bigram(first, second); if (_bigram[corpus].find(key) == _bigram[corpus].end()) return 0; else return _bigram[corpus][key]; } int JelinekMercerFeature::unigram_count(int corpus, int word) { if (_unigram[corpus].find(word) == _unigram[corpus].end()) return 0; else return _unigram[corpus][word]; } int JelinekMercerFeature::sum(int *first, int nitems) { int i, sum = 0; for (i = 0; i < nitems; i++) { sum += first[i]; } return sum; } const std::string JelinekMercerFeature::feature(const std::string name, int corpus, int *sent, int length) { assert(length > 0); assert(corpus < _corpora); int baseline = _compare[corpus]; // Create vectors to hold probabilities and masks _slop_mask.resize(length); std::fill(_slop_mask.begin(), _slop_mask.end(), false); _span_mask.resize(length); _span_start.resize(length); _d_bigram.resize(length); _b_bigram.resize(length); _d_unigram.resize(length); _b_unigram.resize(length); // Step 1: find the spans // Consider the first word part of a span unless it's very frequent // This will also contribute to the overall likelihood computation later _span_mask[0] = true; // Extend from the first position. Also compute the total likelihood while // we're at it. for (int ii=1; ii < length; ++ii) { if (this->bigram_count(corpus, sent[ii - 1], sent[ii]) > 0) { // The current word is only true if the previous word was or it isn't // too frequent. _span_mask[ii] = _span_mask[ii - 1] || (sent[ii] >= _min_start_rank && _stopwords.find(sent[ii]) == _stopwords.end()); } else { _span_mask[ii] = false; } } if (kDEBUG) { for (int ii=0; ii < length; ++ii) { if (_span_mask[ii]) std::cout << "\t" << "+" << _types[sent[ii]]; else std::cout << "\t" << "-" << _types[sent[ii]]; } std::cout << "\t<- tokens/mask" << std::endl; } // Filter spans that end with high-frequency words for (int ii=length; ii >= 0; --ii) { if (_span_mask[ii] && // It is in a span (ii==length || !_span_mask[ii+1]) && // at the end sent[ii] < _min_start_rank) {// and is high frequency _span_mask[ii] = false; // Then remove it from span } } // Add back in slop if (_slop > 0) { int position = 2; while (position < length - 1) { // Could this position expand a run if we had slop? if (_span_mask[position - 1] && !_span_mask[position]) { int slop_left = _slop; for (int ii=position; ii < std::min(position + _slop, length - 1); ++ii) { // If this is a LM hit, then // mark all positions before it as a slop position if (!_span_mask[ii]) { _slop_mask[ii] = true; --slop_left; } if (slop_left == 0) break; position = ii; } ++position; } else { // There's no run to expand, so just move onto the next position. ++position; } } } // For each element in the span, figure out where its span begins and compute // probabilities. _b_unigram[0] = this->score(baseline, -1, sent[0]); _d_unigram[0] = this->score(corpus, -1, sent[0]); float complete_prob = _d_unigram[0] - _b_unigram[0]; int start = -1; for (int ii=0; ii < length; ++ii) { // Do we end a span? if (!(_span_mask[ii] || _slop_mask[ii])) { start = -1; } else { // Do we start a new one? if (start < 0) start = ii; // If we're in a span, we'll want unigram probabilities _d_unigram[ii] = this->score(corpus, -1, sent[ii]); _b_unigram[ii] = this->score(baseline, -1, sent[ii]); } _span_start[ii] = start; // save the probabilities for later span calculations _d_bigram[ii] = this->score(corpus, sent[ii - 1], sent[ii]); _b_bigram[ii] = this->score(baseline, sent[ii - 1], sent[ii]); complete_prob += _d_bigram[ii] - _b_bigram[ii]; } if (kDEBUG) { std::cout << "\tX"; for (int ii=1; ii < length; ++ii) std::cout << "\t" << this->bigram_count(corpus, sent[ii-1], sent[ii]); std::cout << std::endl; for (int ii=0; ii < length; ++ii) { if (_span_mask[ii]) std::cout << "\t" << "+"; else std::cout << "\t" << "-"; } std::cout << "\t<- revision" << std::endl; for (int ii=0; ii < length; ++ii) { if (_slop_mask[ii]) std::cout << "\t" << "+"; else std::cout << "\t" << "-"; } std::cout << "\t<- slop" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << _span_start[ii]; std::cout << "\t<- start" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_bigram[ii]; std::cout << "\t<- domain bigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_bigram[ii]; std::cout << "\t<- base bigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_count(corpus, sent[ii]); std::cout << "\t<- domain unigram count" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_norm(corpus); std::cout << "\t<- domain unigram norm" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_unigram[ii]; std::cout << "\t<- domain unigram" << std::endl; for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_unigram[ii]; std::cout << "\t<- base unigram" << std::endl; } // Now we can output the feature and compute the probability of spans std::ostringstream buffer; buffer << std::fixed; buffer << std::setprecision(2); int longest_span = 0; float max_prob = 0; for (int ii=1; ii < length; ++ii) { if (_span_start[ii] >= 0) { if (ii - _span_start[ii] >= longest_span) longest_span = ii - _span_start[ii] + 1; // Skip if it's too short if (ii - _span_start[ii] < _min_span - 1) continue; for (int start = _span_start[ii]; start <= ii - _min_span; ++start) { float span_probability; if (_stopwords.find(sent[start]) != _stopwords.end()) continue; span_probability = _d_unigram[start] - _b_unigram[start]; // First compute the span probabilities for (int jj = start + 1; jj <= ii; ++jj) { span_probability += _d_bigram[jj] - _b_bigram[jj]; } if (span_probability > _cutoff) { if (span_probability > max_prob) max_prob = span_probability; buffer << corpus; for (int jj = start; jj <= ii; ++jj) { buffer << "_"; if (_censor_slop && _slop_mask[jj]) buffer << "SLOP"; else buffer << sent[jj]; } if (_score) { buffer << ":"; buffer << span_probability; } buffer << " "; } } } } // Output the probability if (_score) { buffer << name; buffer << "_PROB:"; buffer << complete_prob / ((float)length); buffer << " "; buffer << name; buffer << "_MAX:"; buffer << max_prob; buffer << " "; } buffer << name; buffer << "_LEN:"; buffer << longest_span; if (_log_length) { buffer << " " << name; buffer << "_LGLEN:"; buffer << log(1 + longest_span); } return buffer.str(); } float JelinekMercerFeature::unigram_norm(int corpus) { return (float)this->_normalizer[corpus] + _smooth_norm; } float JelinekMercerFeature::score(int corpus, int first, int second) { // Store the unigram probability in the score float unigram_num = (float)this->unigram_count(corpus, second) + _smooth; float unigram_den = this->unigram_norm(corpus); float score = unigram_num / unigram_den; if (kDEBUG) { std::cout << _corpus_names[corpus] << " LL for " << first; //if (first >= 0) std::cout << "(" << _types[first] << ")"; std::cout << " " << second << "(" << _types[second] << ")" << std::endl; std::cout << "UNI:" << unigram_num << "/" << unigram_den << "=" << score << std::endl; } if (first >= 0) { // first == -1 means we just want unigram probability int bigram_den = this->unigram_count(corpus, first); int bigram_num = this->bigram_count(corpus, first, second); if (bigram_den == 0 || bigram_num == 0) { score *= _unigram_contribution; } else { score = this->_bigram_contribution * (float)bigram_num / (float)bigram_den + _unigram_contribution * score; } } if (kDEBUG) { std::cout << "Final:" << log(score) << std::endl; } return log(score); } <|endoftext|>
<commit_before>/* * Hamming Window Function Unit for Jamoma DSP * Copyright © 2010 by Trond Lossius * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "HammingWindow.h" #define thisTTClass HammingWindow #define thisTTClassName "hamming" #define thisTTClassTags "audio, processor, function, window" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } HammingWindow::~HammingWindow() { ; } // hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5)) TTErr HammingWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { y = 0.54 + 0.46*cos(kTTwoTPi*(x-0.5)); return kTTErrNone; } TTErr HammingWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); } <commit_msg>fixing typo <commit_after>/* * Hamming Window Function Unit for Jamoma DSP * Copyright © 2010 by Trond Lossius * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "HammingWindow.h" #define thisTTClass HammingWindow #define thisTTClassName "hamming" #define thisTTClassTags "audio, processor, function, window" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } HammingWindow::~HammingWindow() { ; } // hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5)) TTErr HammingWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { y = 0.54 + 0.46*cos(kTTTwoPi*(x-0.5)); return kTTErrNone; } TTErr HammingWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); } <|endoftext|>
<commit_before> #include "journal/player.hpp" #include <list> #include <string> #include <thread> #include <vector> #include "benchmark/benchmark.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "journal/method.hpp" #include "journal/profiles.hpp" #include "journal/recorder.hpp" #include "ksp_plugin/interface.hpp" #include "serialization/journal.pb.h" namespace principia { namespace journal { // The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks void BM_PlayForReal(benchmark::State& state) { // NOLINT(runtime/references) while (state.KeepRunning()) { Player player( R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160626-143407)"); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } } } BENCHMARK(BM_PlayForReal); class PlayerTest : public ::testing::Test { protected: PlayerTest() : test_info_(testing::UnitTest::GetInstance()->current_test_info()), test_case_name_(test_info_->test_case_name()), test_name_(test_info_->name()), plugin_(interface::principia__NewPlugin("0 s", "0 s", 0)) {} template<typename Profile> bool RunIfAppropriate(serialization::Method const& method_in, serialization::Method const& method_out_return, Player& player) { return player.RunIfAppropriate<Profile>(method_in, method_out_return); } ::testing::TestInfo const* const test_info_; std::string const test_case_name_; std::string const test_name_; std::unique_ptr<ksp_plugin::Plugin> plugin_; }; TEST_F(PlayerTest, PlayTiny) { // Do the recording in a separate thread to make sure that it activates using // a different static variable than the one in the plugin dynamic library. std::thread recorder([this]() { Recorder* const r(new Recorder(test_name_ + ".journal.hex")); Recorder::Activate(r); { Method<NewPlugin> m({"1 s", "2 s", 3}); m.Return(plugin_.get()); } { const ksp_plugin::Plugin* plugin = plugin_.get(); Method<DeletePlugin> m({&plugin}, {&plugin}); m.Return(); } Recorder::Deactivate(); }); recorder.join(); Player player(test_name_ + ".journal.hex"); // Replay the journal. int count = 0; while (player.Play()) { ++count; } EXPECT_EQ(2, count); } // This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it // explicitly. TEST_F(PlayerTest, Benchmarks) { if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) { benchmark::RunSpecifiedBenchmarks(); } } #if 0 // This test is only run if the --gtest_filter flag names it explicitly. TEST_F(PlayerTest, Debug) { if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) { // An example of how journaling may be used for debugging. You must set // |path| and fill the |method_in| and |method_out_return| protocol buffers. std::string path = R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20170312-191519)"; Player player(path); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } LOG(ERROR) << count << " journal entries in total"; LOG(ERROR) << "Last successful method in:\n" << player.last_method_in().DebugString(); LOG(ERROR) << "Last successful method out/return: \n" << player.last_method_out_return().DebugString(); #if 0 serialization::Method method_in; auto* extension = method_in.MutableExtension( serialization::ReportCollision::extension); auto* in = extension->mutable_in(); in->set_plugin(355375312); in->set_vessel1_guid("14b05bd3-9707-4d49-a6be-a7de481f3e0a"); in->set_vessel2_guid("3e6fcb7e-4761-48ed-829f-0adb035f457e"); serialization::Method method_out_return; method_out_return.MutableExtension( serialization::ReportCollision::extension); LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString(); CHECK(RunIfAppropriate<ReportCollision>(method_in, method_out_return, player)); #endif } } #endif } // namespace journal } // namespace principia <commit_msg>Path.<commit_after> #include "journal/player.hpp" #include <list> #include <string> #include <thread> #include <vector> #include "benchmark/benchmark.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "journal/method.hpp" #include "journal/profiles.hpp" #include "journal/recorder.hpp" #include "ksp_plugin/interface.hpp" #include "serialization/journal.pb.h" namespace principia { namespace journal { // The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks void BM_PlayForReal(benchmark::State& state) { // NOLINT(runtime/references) while (state.KeepRunning()) { Player player( R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160626-143407)"); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } } } BENCHMARK(BM_PlayForReal); class PlayerTest : public ::testing::Test { protected: PlayerTest() : test_info_(testing::UnitTest::GetInstance()->current_test_info()), test_case_name_(test_info_->test_case_name()), test_name_(test_info_->name()), plugin_(interface::principia__NewPlugin("0 s", "0 s", 0)) {} template<typename Profile> bool RunIfAppropriate(serialization::Method const& method_in, serialization::Method const& method_out_return, Player& player) { return player.RunIfAppropriate<Profile>(method_in, method_out_return); } ::testing::TestInfo const* const test_info_; std::string const test_case_name_; std::string const test_name_; std::unique_ptr<ksp_plugin::Plugin> plugin_; }; TEST_F(PlayerTest, PlayTiny) { // Do the recording in a separate thread to make sure that it activates using // a different static variable than the one in the plugin dynamic library. std::thread recorder([this]() { Recorder* const r(new Recorder(test_name_ + ".journal.hex")); Recorder::Activate(r); { Method<NewPlugin> m({"1 s", "2 s", 3}); m.Return(plugin_.get()); } { const ksp_plugin::Plugin* plugin = plugin_.get(); Method<DeletePlugin> m({&plugin}, {&plugin}); m.Return(); } Recorder::Deactivate(); }); recorder.join(); Player player(test_name_ + ".journal.hex"); // Replay the journal. int count = 0; while (player.Play()) { ++count; } EXPECT_EQ(2, count); } // This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it // explicitly. TEST_F(PlayerTest, Benchmarks) { if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) { benchmark::RunSpecifiedBenchmarks(); } } // This test is only run if the --gtest_filter flag names it explicitly. TEST_F(PlayerTest, Debug) { if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) { // An example of how journaling may be used for debugging. You must set // |path| and fill the |method_in| and |method_out_return| protocol buffers. std::string path = R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20170317-181650)"; Player player(path); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } LOG(ERROR) << count << " journal entries in total"; LOG(ERROR) << "Last successful method in:\n" << player.last_method_in().DebugString(); LOG(ERROR) << "Last successful method out/return: \n" << player.last_method_out_return().DebugString(); #if 0 serialization::Method method_in; auto* extension = method_in.MutableExtension( serialization::ReportCollision::extension); auto* in = extension->mutable_in(); in->set_plugin(355375312); in->set_vessel1_guid("14b05bd3-9707-4d49-a6be-a7de481f3e0a"); in->set_vessel2_guid("3e6fcb7e-4761-48ed-829f-0adb035f457e"); serialization::Method method_out_return; method_out_return.MutableExtension( serialization::ReportCollision::extension); LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString(); CHECK(RunIfAppropriate<ReportCollision>(method_in, method_out_return, player)); #endif } } } // namespace journal } // namespace principia <|endoftext|>
<commit_before>#ifndef WIN32 #include "native.h" #include "generic.h" #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <unistd.h> #include <sys/ioctl.h> #include <curses.h> #include <term.h> /* * Marks the given result as failed, using the current value of errno */ void mark_failed_with_errno(JNIEnv *env, const char* message, jobject result) { mark_failed_with_code(env, message, errno, result); } /* * File functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_chmod(JNIEnv *env, jclass target, jstring path, jint mode, jobject result) { const char* pathUtf8 = env->GetStringUTFChars(path, NULL); int retval = chmod(pathUtf8, mode); env->ReleaseStringUTFChars(path, pathUtf8); if (retval != 0) { mark_failed_with_errno(env, "could not chmod file", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_stat(JNIEnv *env, jclass target, jstring path, jobject dest, jobject result) { struct stat fileInfo; const char* pathUtf8 = env->GetStringUTFChars(path, NULL); int retval = stat(pathUtf8, &fileInfo); env->ReleaseStringUTFChars(path, pathUtf8); if (retval != 0) { mark_failed_with_errno(env, "could not stat file", result); return; } jclass destClass = env->GetObjectClass(dest); jfieldID modeField = env->GetFieldID(destClass, "mode", "I"); env->SetIntField(dest, modeField, 0777 & fileInfo.st_mode); } /* * Process functions */ JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) { return getpid(); } /* * Terminal functions */ JNIEXPORT jboolean JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_isatty(JNIEnv *env, jclass target, jint output) { switch (output) { case 0: case 1: return isatty(output+1) ? JNI_TRUE : JNI_FALSE; default: return JNI_FALSE; } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_getTerminalSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) { struct winsize screen_size; int retval = ioctl(output+1, TIOCGWINSZ, &screen_size); if (retval != 0) { mark_failed_with_errno(env, "could not fetch terminal size", result); return; } jclass dimensionClass = env->GetObjectClass(dimension); jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I"); env->SetIntField(dimension, widthField, screen_size.ws_col); jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I"); env->SetIntField(dimension, heightField, screen_size.ws_row); } /* * Terminfo functions */ int current_terminal = -1; #ifdef SOLARIS #define TERMINAL_CHAR_TYPE char #else #define TERMINAL_CHAR_TYPE int #endif int write_to_terminal(TERMINAL_CHAR_TYPE ch) { write(current_terminal, &ch, 1); } void write_capability(JNIEnv *env, const char* capability, jobject result) { char* cap = tgetstr((char*)capability, NULL); if (cap == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } if (tputs(cap, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } void write_param_capability(JNIEnv *env, const char* capability, int count, jobject result) { char* cap = tgetstr((char*)capability, NULL); if (cap == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } cap = tparm(cap, count, 0, 0, 0, 0, 0, 0, 0, 0); if (cap == NULL) { mark_failed_with_message(env, "could not format terminal capability string", result); return; } if (tputs(cap, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_initTerminal(JNIEnv *env, jclass target, jint output, jobject result) { if (!isatty(output+1)) { mark_failed_with_message(env, "not a terminal", result); return; } char* termType = getenv("TERM"); if (termType == NULL) { mark_failed_with_message(env, "$TERM not set", result); return; } int retval = tgetent(NULL, termType); if (retval != 1) { mark_failed_with_message(env, "could not get termcap entry", result); return; } current_terminal = output + 1; write_capability(env, "me", result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_bold(JNIEnv *env, jclass target, jobject result) { write_capability(env, "md", result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_reset(JNIEnv *env, jclass target, jobject result) { write_capability(env, "me", result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_foreground(JNIEnv *env, jclass target, jint color, jobject result) { write_param_capability(env, "AF", color, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_up(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, "up", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_down(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, "do", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_left(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, "le", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_right(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, "nd", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_startLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, "cr", result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_clearToEndOfLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, "ce", result); } #endif <commit_msg>Lookup all terminal capabilities on initialisation.<commit_after>#ifndef WIN32 #include "native.h" #include "generic.h" #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <unistd.h> #include <sys/ioctl.h> #include <curses.h> #include <term.h> /* * Marks the given result as failed, using the current value of errno */ void mark_failed_with_errno(JNIEnv *env, const char* message, jobject result) { mark_failed_with_code(env, message, errno, result); } /* * File functions */ JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_chmod(JNIEnv *env, jclass target, jstring path, jint mode, jobject result) { const char* pathUtf8 = env->GetStringUTFChars(path, NULL); int retval = chmod(pathUtf8, mode); env->ReleaseStringUTFChars(path, pathUtf8); if (retval != 0) { mark_failed_with_errno(env, "could not chmod file", result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_stat(JNIEnv *env, jclass target, jstring path, jobject dest, jobject result) { struct stat fileInfo; const char* pathUtf8 = env->GetStringUTFChars(path, NULL); int retval = stat(pathUtf8, &fileInfo); env->ReleaseStringUTFChars(path, pathUtf8); if (retval != 0) { mark_failed_with_errno(env, "could not stat file", result); return; } jclass destClass = env->GetObjectClass(dest); jfieldID modeField = env->GetFieldID(destClass, "mode", "I"); env->SetIntField(dest, modeField, 0777 & fileInfo.st_mode); } /* * Process functions */ JNIEXPORT jint JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) { return getpid(); } /* * Terminal functions */ JNIEXPORT jboolean JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_isatty(JNIEnv *env, jclass target, jint output) { switch (output) { case 0: case 1: return isatty(output+1) ? JNI_TRUE : JNI_FALSE; default: return JNI_FALSE; } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_getTerminalSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) { struct winsize screen_size; int retval = ioctl(output+1, TIOCGWINSZ, &screen_size); if (retval != 0) { mark_failed_with_errno(env, "could not fetch terminal size", result); return; } jclass dimensionClass = env->GetObjectClass(dimension); jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I"); env->SetIntField(dimension, widthField, screen_size.ws_col); jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I"); env->SetIntField(dimension, heightField, screen_size.ws_row); } /* * Terminfo functions */ #define NORMAL_TEXT 0 #define BRIGHT_TEXT 1 #define FOREGROUND_COLOR 2 #define CURSOR_UP 3 #define CURSOR_DOWN 4 #define CURSOR_LEFT 5 #define CURSOR_RIGHT 6 #define CURSOR_START_LINE 7 #define CLEAR_END_OF_LINE 8 #ifdef SOLARIS #define TERMINAL_CHAR_TYPE char #else #define TERMINAL_CHAR_TYPE int #endif int current_terminal = -1; const char* terminal_capabilities[9]; int write_to_terminal(TERMINAL_CHAR_TYPE ch) { write(current_terminal, &ch, 1); } void write_capability(JNIEnv *env, const char* capability, jobject result) { if (capability == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } if (tputs(capability, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } void write_param_capability(JNIEnv *env, const char* capability, int count, jobject result) { if (capability == NULL) { mark_failed_with_message(env, "unknown terminal capability", result); return; } capability = tparm((char*)capability, count, 0, 0, 0, 0, 0, 0, 0, 0); if (capability == NULL) { mark_failed_with_message(env, "could not format terminal capability string", result); return; } if (tputs(capability, 1, write_to_terminal) == ERR) { mark_failed_with_message(env, "could not write to terminal", result); return; } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_initTerminal(JNIEnv *env, jclass target, jint output, jobject result) { if (!isatty(output+1)) { mark_failed_with_message(env, "not a terminal", result); return; } if (current_terminal < 0) { char* termType = getenv("TERM"); if (termType == NULL) { mark_failed_with_message(env, "$TERM not set", result); return; } int retval = tgetent(NULL, termType); if (retval != 1) { mark_failed_with_message(env, "could not get termcap entry", result); return; } terminal_capabilities[NORMAL_TEXT] = tgetstr((char*)"me", NULL); terminal_capabilities[BRIGHT_TEXT] = tgetstr((char*)"md", NULL); terminal_capabilities[FOREGROUND_COLOR] = tgetstr((char*)"AF", NULL); terminal_capabilities[CURSOR_UP] = tgetstr((char*)"up", NULL); terminal_capabilities[CURSOR_DOWN] = tgetstr((char*)"do", NULL); terminal_capabilities[CURSOR_LEFT] = tgetstr((char*)"le", NULL); terminal_capabilities[CURSOR_RIGHT] = tgetstr((char*)"nd", NULL); terminal_capabilities[CURSOR_START_LINE] = tgetstr((char*)"cr", NULL); terminal_capabilities[CLEAR_END_OF_LINE] = tgetstr((char*)"ce", NULL); } current_terminal = output + 1; write_capability(env, terminal_capabilities[NORMAL_TEXT], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_bold(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[BRIGHT_TEXT], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_reset(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[NORMAL_TEXT], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_foreground(JNIEnv *env, jclass target, jint color, jobject result) { write_param_capability(env, terminal_capabilities[FOREGROUND_COLOR], color, result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_up(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_UP], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_down(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_DOWN], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_left(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_LEFT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_right(JNIEnv *env, jclass target, jint count, jobject result) { for (jint i = 0; i < count; i++) { write_capability(env, terminal_capabilities[CURSOR_RIGHT], result); } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_startLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[CURSOR_START_LINE], result); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_TerminfoFunctions_clearToEndOfLine(JNIEnv *env, jclass target, jobject result) { write_capability(env, terminal_capabilities[CLEAR_END_OF_LINE], result); } #endif <|endoftext|>
<commit_before>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { #define ALIGN 6 AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 24)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 24)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); cerr << "Done.\n"; } } // namespace cnn <commit_msg>CPU memory size allocation fixes<commit_after>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { #define ALIGN 6 AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); cerr << "Done.\n"; } } // namespace cnn <|endoftext|>
<commit_before>#include "MediaSessionServiceHandler.h" #include "log.h" using namespace ::com::kurento::kms::api; using ::com::kurento::log::Log; static Log l("MediaSessionHandler"); #define i(...) aux_info(l, __VA_ARGS__); namespace com { namespace kurento { namespace kms { MediaSessionServiceHandler::MediaSessionServiceHandler() { } MediaSessionServiceHandler::~MediaSessionServiceHandler() { } void MediaSessionServiceHandler::createNetworkConnection(NetworkConnection& _return, const MediaSession& mediaSessionId, const std::vector<NetworkConnectionConfig::type>& config) { i("CreateNetworkConnection"); } void MediaSessionServiceHandler::deleteNetworkConnection( const MediaSession& mediaSessionId, const NetworkConnection& networConnection) { i("deleteNetworkConnection"); } void MediaSessionServiceHandler::getNetworkConnections( std::vector<NetworkConnection>& _return, const MediaSession& mediaSessionId) { i("getNetworkConnections"); } void MediaSessionServiceHandler::createMixer(Mixer& _return, const MediaSession& mediaSessionId, const std::vector<MixerConfig::type>& config) { i("createMixer"); } void MediaSessionServiceHandler::deleteMixer(const MediaSession& mediaSessionId, const Mixer& mixer) { i("deleteMixer"); } void MediaSessionServiceHandler::getMixers(std::vector<Mixer>& _return, const MediaSession& mediaSessionId) { i("getMixers"); } void MediaSessionServiceHandler::ping(const MediaObject& mediaObject, const int32_t timeout) { i("ping"); } void MediaSessionServiceHandler::release(const MediaObject& mediaObject) { i("release"); } }}} // com::kurento::kms<commit_msg>Get a reference of session manager on service handler construction<commit_after>#include "MediaSessionServiceHandler.h" #include "log.h" using namespace ::com::kurento::kms::api; using ::com::kurento::log::Log; static Log l("MediaSessionHandler"); #define i(...) aux_info(l, __VA_ARGS__); namespace com { namespace kurento { namespace kms { MediaSessionServiceHandler::MediaSessionServiceHandler() { manager = MediaSessionManager::getInstance(); } MediaSessionServiceHandler::~MediaSessionServiceHandler() { MediaSessionManager::releaseInstance(manager); } void MediaSessionServiceHandler::createNetworkConnection(NetworkConnection& _return, const MediaSession& mediaSessionId, const std::vector<NetworkConnectionConfig::type>& config) { i("CreateNetworkConnection"); } void MediaSessionServiceHandler::deleteNetworkConnection( const MediaSession& mediaSessionId, const NetworkConnection& networConnection) { i("deleteNetworkConnection"); } void MediaSessionServiceHandler::getNetworkConnections( std::vector<NetworkConnection>& _return, const MediaSession& mediaSessionId) { i("getNetworkConnections"); } void MediaSessionServiceHandler::createMixer(Mixer& _return, const MediaSession& mediaSessionId, const std::vector<MixerConfig::type>& config) { i("createMixer"); } void MediaSessionServiceHandler::deleteMixer(const MediaSession& mediaSessionId, const Mixer& mixer) { i("deleteMixer"); } void MediaSessionServiceHandler::getMixers(std::vector<Mixer>& _return, const MediaSession& mediaSessionId) { i("getMixers"); } void MediaSessionServiceHandler::ping(const MediaObject& mediaObject, const int32_t timeout) { i("ping"); } void MediaSessionServiceHandler::release(const MediaObject& mediaObject) { i("release"); } }}} // com::kurento::kms<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: popupmenudispatcher.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:03:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ #define __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_SERVICES_FRAME_HXX_ #include <services/frame.hxx> #endif /* #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif */ #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif /* #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif */ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_ #include <com/sun/star/frame/XDispatchProvider.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_URL_HPP_ #include <com/sun/star/util/URL.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_ #include <com/sun/star/frame/DispatchDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAMELOADER_HPP_ #include <com/sun/star/frame/XFrameLoader.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_ #include <com/sun/star/frame/XLoadEventListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_ #include <com/sun/star/frame/XFrameActionListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_URI_XURLREFERENCEFACTORY_HPP_ #include <com/sun/star/uri/XUriReferenceFactory.hpp> #endif #ifndef _COM_SUN_STAR_URI_XURLREFERENCE_HPP_ #include <com/sun/star/uri/XUriReference.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** We must save informations about our listener and URL for listening. We implement this as a hashtable for strings. *//*-*************************************************************************************************************/ typedef ::cppu::OMultiTypeInterfaceContainerHelperVar< ::rtl::OUString , OUStringHashCode , std::equal_to< ::rtl::OUString > > IMPL_ListenerHashContainer; /*-************************************************************************************************************//** @short helper for desktop only(!) to create new tasks on demand for dispatches @descr Use this class as member only! Never use it as baseclass. XInterface will be ambigous and we hold a weakcss::uno::Reference to ouer OWNER - not to our SUPERCLASS! @implements XInterface XDispatch XLoadEventListener XFrameActionListener XEventListener @base ThreadHelpBase OWeakObject @devstatus ready to use *//*-*************************************************************************************************************/ class PopupMenuDispatcher : // interfaces public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::frame::XDispatchProvider , public css::frame::XDispatch , public css::frame::XFrameActionListener , public css::lang::XInitialization , // baseclasses // Order is neccessary for right initialization! public ThreadHelpBase , public cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: // constructor / destructor PopupMenuDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ); // XInterface, XTypeProvider, XServiceInfo FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO // XInitialization virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& lArguments ) throw( css::uno::Exception , css::uno::RuntimeException); // XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL , const ::rtl::OUString& sTarget , sal_Int32 nFlags ) throw( ::com::sun::star::uno::RuntimeException ); virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ); // XDispatch virtual void SAL_CALL dispatch( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& seqProperties ) throw( css::uno::RuntimeException ); virtual void SAL_CALL addStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xControl, const css::util::URL& aURL ) throw( css::uno::RuntimeException ); virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xControl, const css::util::URL& aURL ) throw( css::uno::RuntimeException ); // XFrameActionListener virtual void SAL_CALL frameAction( const css::frame::FrameActionEvent& aEvent ) throw ( css::uno::RuntimeException ); // XEventListener void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException ); // protected methods protected: virtual ~PopupMenuDispatcher(); void impl_RetrievePopupControllerQuery(); void impl_CreateUriRefFactory(); // private methods // variables private: css::uno::WeakReference< css::frame::XFrame > m_xWeakFrame ; /// css::uno::WeakReference to frame (Don't use a hard css::uno::Reference. Owner can't delete us then!) css::uno::Reference< css::container::XNameAccess > m_xPopupCtrlQuery ; /// reference to query for popup controller css::uno::Reference< css::uri::XUriReferenceFactory > m_xUriRefFactory ; /// reference to the uri reference factory css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// factory shared with our owner to create new services! IMPL_ListenerHashContainer m_aListenerContainer; /// hash table for listener at specified URLs sal_Bool m_bAlreadyDisposed ; /// Protection against multiple disposing calls. sal_Bool m_bActivateListener ; /// dispatcher is listener for frame activation }; // class PopupMenuDispatcher } // namespace framework #endif // #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.2.224); FILE MERGED 2008/04/01 15:18:16 thb 1.2.224.3: #i85898# Stripping all external header guards 2008/04/01 10:57:46 thb 1.2.224.2: #i85898# Stripping all external header guards 2008/03/28 15:34:36 rt 1.2.224.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: popupmenudispatcher.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ #define __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <services/frame.hxx> /* #include <macros/generic.hxx> */ #include <macros/xinterface.hxx> #include <macros/xtypeprovider.hxx> #include <macros/xserviceinfo.hxx> /* #include <macros/debug.hxx> */ #include <threadhelp/threadhelpbase.hxx> #include <general.h> #include <stdtypes.h> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/lang/XTypeProvider.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/util/URL.hpp> #include <com/sun/star/frame/DispatchDescriptor.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/frame/XStatusListener.hpp> #include <com/sun/star/frame/XFrameLoader.hpp> #include <com/sun/star/frame/XLoadEventListener.hpp> #include <com/sun/star/frame/XDesktop.hpp> #include <com/sun/star/frame/FeatureStateEvent.hpp> #include <com/sun/star/frame/XFrameActionListener.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/container/XNameAccess.hpp> #ifndef _COM_SUN_STAR_URI_XURLREFERENCEFACTORY_HPP_ #include <com/sun/star/uri/XUriReferenceFactory.hpp> #endif #ifndef _COM_SUN_STAR_URI_XURLREFERENCE_HPP_ #include <com/sun/star/uri/XUriReference.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <cppuhelper/weak.hxx> #include <cppuhelper/weakref.hxx> #include <cppuhelper/interfacecontainer.h> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** We must save informations about our listener and URL for listening. We implement this as a hashtable for strings. *//*-*************************************************************************************************************/ typedef ::cppu::OMultiTypeInterfaceContainerHelperVar< ::rtl::OUString , OUStringHashCode , std::equal_to< ::rtl::OUString > > IMPL_ListenerHashContainer; /*-************************************************************************************************************//** @short helper for desktop only(!) to create new tasks on demand for dispatches @descr Use this class as member only! Never use it as baseclass. XInterface will be ambigous and we hold a weakcss::uno::Reference to ouer OWNER - not to our SUPERCLASS! @implements XInterface XDispatch XLoadEventListener XFrameActionListener XEventListener @base ThreadHelpBase OWeakObject @devstatus ready to use *//*-*************************************************************************************************************/ class PopupMenuDispatcher : // interfaces public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::frame::XDispatchProvider , public css::frame::XDispatch , public css::frame::XFrameActionListener , public css::lang::XInitialization , // baseclasses // Order is neccessary for right initialization! public ThreadHelpBase , public cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: // constructor / destructor PopupMenuDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ); // XInterface, XTypeProvider, XServiceInfo FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO // XInitialization virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& lArguments ) throw( css::uno::Exception , css::uno::RuntimeException); // XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL , const ::rtl::OUString& sTarget , sal_Int32 nFlags ) throw( ::com::sun::star::uno::RuntimeException ); virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ); // XDispatch virtual void SAL_CALL dispatch( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& seqProperties ) throw( css::uno::RuntimeException ); virtual void SAL_CALL addStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xControl, const css::util::URL& aURL ) throw( css::uno::RuntimeException ); virtual void SAL_CALL removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xControl, const css::util::URL& aURL ) throw( css::uno::RuntimeException ); // XFrameActionListener virtual void SAL_CALL frameAction( const css::frame::FrameActionEvent& aEvent ) throw ( css::uno::RuntimeException ); // XEventListener void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException ); // protected methods protected: virtual ~PopupMenuDispatcher(); void impl_RetrievePopupControllerQuery(); void impl_CreateUriRefFactory(); // private methods // variables private: css::uno::WeakReference< css::frame::XFrame > m_xWeakFrame ; /// css::uno::WeakReference to frame (Don't use a hard css::uno::Reference. Owner can't delete us then!) css::uno::Reference< css::container::XNameAccess > m_xPopupCtrlQuery ; /// reference to query for popup controller css::uno::Reference< css::uri::XUriReferenceFactory > m_xUriRefFactory ; /// reference to the uri reference factory css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// factory shared with our owner to create new services! IMPL_ListenerHashContainer m_aListenerContainer; /// hash table for listener at specified URLs sal_Bool m_bAlreadyDisposed ; /// Protection against multiple disposing calls. sal_Bool m_bActivateListener ; /// dispatcher is listener for frame activation }; // class PopupMenuDispatcher } // namespace framework #endif // #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mailtodispatcher.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:20:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_SYSTEM_XSYSTEMSHELLEXECUTE_HPP_ #include <com/sun/star/system/XSystemShellExecute.hpp> #endif #ifndef _COM_SUN_STAR_SYSTEM_SYSTEMSHELLEXECUTEFLAGS_HPP_ #include <com/sun/star/system/SystemShellExecuteFlags.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_ #include <com/sun/star/frame/DispatchResultState.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ #define PROTOCOL_VALUE "mailto:" #define PROTOCOL_LENGTH 7 //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // XInterface, XTypeProvider, XServiceInfo DEFINE_XINTERFACE_5(MailToDispatcher , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ), DIRECT_INTERFACE(css::lang::XServiceInfo ), DIRECT_INTERFACE(css::frame::XDispatchProvider ), DIRECT_INTERFACE(css::frame::XNotifyingDispatch), DIRECT_INTERFACE(css::frame::XDispatch )) DEFINE_XTYPEPROVIDER_5(MailToDispatcher , css::lang::XTypeProvider , css::lang::XServiceInfo , css::frame::XDispatchProvider , css::frame::XNotifyingDispatch, css::frame::XDispatch ) DEFINE_XSERVICEINFO_MULTISERVICE(MailToDispatcher , ::cppu::OWeakObject , SERVICENAME_PROTOCOLHANDLER , IMPLEMENTATIONNAME_MAILTODISPATCHER) DEFINE_INIT_SERVICE(MailToDispatcher, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ } ) //_________________________________________________________________________________________________________________ /** @short standard ctor @descr These initialize a new instance of ths class with needed informations for work. @param xFactory reference to uno servicemanager for creation of new services @modified 30.04.2002 14:10, as96863 */ MailToDispatcher::MailToDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ) // Init baseclasses first : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject ( ) // Init member , m_xFactory ( xFactory ) { } //_________________________________________________________________________________________________________________ /** @short standard dtor @descr - @modified 30.04.2002 14:10, as96863 */ MailToDispatcher::~MailToDispatcher() { m_xFactory = NULL; } //_________________________________________________________________________________________________________________ /** @short decide if this dispatch implementation can be used for requested URL or not @descr A protocol handler is registerd for an URL pattern inside configuration and will be asked by the generic dispatch mechanism inside framework, if he can handle this special URL wich match his registration. He can agree by returning of a valid dispatch instance or disagree by returning <NULL/>. We don't create new dispatch instances here realy - we return THIS as result to handle it at the same implementation. @modified 02.05.2002 15:25, as96863 */ css::uno::Reference< css::frame::XDispatch > SAL_CALL MailToDispatcher::queryDispatch( const css::util::URL& aURL , const ::rtl::OUString& sTarget , sal_Int32 nFlags ) throw( css::uno::RuntimeException ) { css::uno::Reference< css::frame::XDispatch > xDispatcher; if (aURL.Complete.compareToAscii(PROTOCOL_VALUE,PROTOCOL_LENGTH)==0) xDispatcher = this; return xDispatcher; } //_________________________________________________________________________________________________________________ /** @short do the same like dispatch() but for multiple requests at the same time @descr - @modified 02.05.2002 15:27, as96863 */ css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL MailToDispatcher::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ) { sal_Int32 nCount = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatcher( nCount ); for( sal_Int32 i=0; i<nCount; ++i ) { lDispatcher[i] = this->queryDispatch( lDescriptor[i].FeatureURL, lDescriptor[i].FrameName, lDescriptor[i].SearchFlags); } return lDispatcher; } //_________________________________________________________________________________________________________________ /** @short dispatch URL with arguments @descr We use threadsafe internal method to do so. It returns a state value - but we ignore it. Because we doesn't support status listener notifications here. Status events are not guaranteed - and we call another service internaly which doesn't return any notifications too. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @modified 30.04.2002 14:15, as96863 */ void SAL_CALL MailToDispatcher::dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { // dispatch() is an [oneway] call ... and may our user release his reference to us immediatly. // So we should hold us self alive till this call ends. css::uno::Reference< css::frame::XNotifyingDispatch > xSelfHold(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); implts_dispatch(aURL,lArguments); // No notification for status listener! } //_________________________________________________________________________________________________________________ /** @short dispatch with guaranteed notifications about success @descr We use threadsafe internal method to do so. Return state of this function will be used for notification if an optional listener is given. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @param xListener reference to a valid listener for state events @modified 30.04.2002 14:49, as96863 */ void SAL_CALL MailToDispatcher::dispatchWithNotification( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments, const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw( css::uno::RuntimeException ) { // This class was designed to die by reference. And if user release his reference to us immediatly after calling this method // we can run into some problems. So we hold us self alive till this method ends. // Another reason: We can use this reference as source of sending event at the end too. css::uno::Reference< css::frame::XNotifyingDispatch > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); sal_Bool bState = implts_dispatch(aURL,lArguments); if (xListener.is()) { css::frame::DispatchResultEvent aEvent; if (bState) aEvent.State = css::frame::DispatchResultState::SUCCESS; else aEvent.State = css::frame::DispatchResultState::FAILURE; aEvent.Source = xThis; xListener->dispatchFinished( aEvent ); } } //_________________________________________________________________________________________________________________ /** @short threadsafe helper for dispatch calls @descr We support two interfaces for the same process - dispatch URLs. That the reason for this internal function. It implements the real dispatch operation and returns a state value which inform caller about success. He can notify listener then by using this return value. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @return <TRUE/> if dispatch could be started successfully Note: Our internal used shell executor doesn't return any state value - so we must belive that call was successfully. <FALSE/> if neccessary ressource couldn't be created or an exception was thrown. @modified 30.04.2002 14:49, as96863 */ sal_Bool MailToDispatcher::implts_dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { sal_Bool bSuccess = sal_False; css::uno::Reference< css::lang::XMultiServiceFactory > xFactory; /* SAFE */{ ReadGuard aReadLock( m_aLock ); xFactory = m_xFactory; /* SAFE */} css::uno::Reference< css::system::XSystemShellExecute > xSystemShellExecute( xFactory->createInstance(SERVICENAME_SYSTEMSHELLEXECUTE), css::uno::UNO_QUERY ); if (xSystemShellExecute.is()) { try { // start mail client // Because there is no notofocation about success - we use case of // no detected exception as SUCCESS - FAILED otherwhise. xSystemShellExecute->execute( aURL.Complete, ::rtl::OUString(), css::system::SystemShellExecuteFlags::DEFAULTS ); bSuccess = sal_True; } catch (css::lang::IllegalArgumentException&) { } catch (css::system::SystemShellExecuteException&) { } } return bSuccess; } //_________________________________________________________________________________________________________________ /** @short add/remove listener for state events @descr Because we use an external process to forward such mail URLs, and this process doesn't return any notifications about success or failed state - we doesn't support such status listener. We have no status to send. @param xListener reference to a valid listener for state events @param aURL URL about listener will be informed, if something occured @modified 30.04.2002 14:49, as96863 */ void SAL_CALL MailToDispatcher::addStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener , const css::util::URL& aURL ) throw( css::uno::RuntimeException ) { // not suported yet } //_________________________________________________________________________________________________________________ void SAL_CALL MailToDispatcher::removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& xListener , const css::util::URL& aURL ) throw( css::uno::RuntimeException ) { // not suported yet } } // namespace framework <commit_msg>INTEGRATION: CWS warnings01 (1.4.32); FILE MERGED 2005/11/16 13:10:35 pl 1.4.32.1: #i55991# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mailtodispatcher.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:16:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_SYSTEM_XSYSTEMSHELLEXECUTE_HPP_ #include <com/sun/star/system/XSystemShellExecute.hpp> #endif #ifndef _COM_SUN_STAR_SYSTEM_SYSTEMSHELLEXECUTEFLAGS_HPP_ #include <com/sun/star/system/SystemShellExecuteFlags.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_ #include <com/sun/star/frame/DispatchResultState.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ #define PROTOCOL_VALUE "mailto:" #define PROTOCOL_LENGTH 7 //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // XInterface, XTypeProvider, XServiceInfo DEFINE_XINTERFACE_5(MailToDispatcher , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ), DIRECT_INTERFACE(css::lang::XServiceInfo ), DIRECT_INTERFACE(css::frame::XDispatchProvider ), DIRECT_INTERFACE(css::frame::XNotifyingDispatch), DIRECT_INTERFACE(css::frame::XDispatch )) DEFINE_XTYPEPROVIDER_5(MailToDispatcher , css::lang::XTypeProvider , css::lang::XServiceInfo , css::frame::XDispatchProvider , css::frame::XNotifyingDispatch, css::frame::XDispatch ) DEFINE_XSERVICEINFO_MULTISERVICE(MailToDispatcher , ::cppu::OWeakObject , SERVICENAME_PROTOCOLHANDLER , IMPLEMENTATIONNAME_MAILTODISPATCHER) DEFINE_INIT_SERVICE(MailToDispatcher, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ } ) //_________________________________________________________________________________________________________________ /** @short standard ctor @descr These initialize a new instance of ths class with needed informations for work. @param xFactory reference to uno servicemanager for creation of new services @modified 30.04.2002 14:10, as96863 */ MailToDispatcher::MailToDispatcher( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ) // Init baseclasses first : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject ( ) // Init member , m_xFactory ( xFactory ) { } //_________________________________________________________________________________________________________________ /** @short standard dtor @descr - @modified 30.04.2002 14:10, as96863 */ MailToDispatcher::~MailToDispatcher() { m_xFactory = NULL; } //_________________________________________________________________________________________________________________ /** @short decide if this dispatch implementation can be used for requested URL or not @descr A protocol handler is registerd for an URL pattern inside configuration and will be asked by the generic dispatch mechanism inside framework, if he can handle this special URL wich match his registration. He can agree by returning of a valid dispatch instance or disagree by returning <NULL/>. We don't create new dispatch instances here realy - we return THIS as result to handle it at the same implementation. @modified 02.05.2002 15:25, as96863 */ css::uno::Reference< css::frame::XDispatch > SAL_CALL MailToDispatcher::queryDispatch( const css::util::URL& aURL , const ::rtl::OUString& /*sTarget*/ , sal_Int32 /*nFlags*/ ) throw( css::uno::RuntimeException ) { css::uno::Reference< css::frame::XDispatch > xDispatcher; if (aURL.Complete.compareToAscii(PROTOCOL_VALUE,PROTOCOL_LENGTH)==0) xDispatcher = this; return xDispatcher; } //_________________________________________________________________________________________________________________ /** @short do the same like dispatch() but for multiple requests at the same time @descr - @modified 02.05.2002 15:27, as96863 */ css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL MailToDispatcher::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ) { sal_Int32 nCount = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatcher( nCount ); for( sal_Int32 i=0; i<nCount; ++i ) { lDispatcher[i] = this->queryDispatch( lDescriptor[i].FeatureURL, lDescriptor[i].FrameName, lDescriptor[i].SearchFlags); } return lDispatcher; } //_________________________________________________________________________________________________________________ /** @short dispatch URL with arguments @descr We use threadsafe internal method to do so. It returns a state value - but we ignore it. Because we doesn't support status listener notifications here. Status events are not guaranteed - and we call another service internaly which doesn't return any notifications too. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @modified 30.04.2002 14:15, as96863 */ void SAL_CALL MailToDispatcher::dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { // dispatch() is an [oneway] call ... and may our user release his reference to us immediatly. // So we should hold us self alive till this call ends. css::uno::Reference< css::frame::XNotifyingDispatch > xSelfHold(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); implts_dispatch(aURL,lArguments); // No notification for status listener! } //_________________________________________________________________________________________________________________ /** @short dispatch with guaranteed notifications about success @descr We use threadsafe internal method to do so. Return state of this function will be used for notification if an optional listener is given. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @param xListener reference to a valid listener for state events @modified 30.04.2002 14:49, as96863 */ void SAL_CALL MailToDispatcher::dispatchWithNotification( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& lArguments, const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw( css::uno::RuntimeException ) { // This class was designed to die by reference. And if user release his reference to us immediatly after calling this method // we can run into some problems. So we hold us self alive till this method ends. // Another reason: We can use this reference as source of sending event at the end too. css::uno::Reference< css::frame::XNotifyingDispatch > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); sal_Bool bState = implts_dispatch(aURL,lArguments); if (xListener.is()) { css::frame::DispatchResultEvent aEvent; if (bState) aEvent.State = css::frame::DispatchResultState::SUCCESS; else aEvent.State = css::frame::DispatchResultState::FAILURE; aEvent.Source = xThis; xListener->dispatchFinished( aEvent ); } } //_________________________________________________________________________________________________________________ /** @short threadsafe helper for dispatch calls @descr We support two interfaces for the same process - dispatch URLs. That the reason for this internal function. It implements the real dispatch operation and returns a state value which inform caller about success. He can notify listener then by using this return value. @param aURL mail URL which should be executed @param lArguments list of optional arguments for this mail request @return <TRUE/> if dispatch could be started successfully Note: Our internal used shell executor doesn't return any state value - so we must belive that call was successfully. <FALSE/> if neccessary ressource couldn't be created or an exception was thrown. @modified 30.04.2002 14:49, as96863 */ sal_Bool MailToDispatcher::implts_dispatch( const css::util::URL& aURL , const css::uno::Sequence< css::beans::PropertyValue >& /*lArguments*/ ) throw( css::uno::RuntimeException ) { sal_Bool bSuccess = sal_False; css::uno::Reference< css::lang::XMultiServiceFactory > xFactory; /* SAFE */{ ReadGuard aReadLock( m_aLock ); xFactory = m_xFactory; /* SAFE */} css::uno::Reference< css::system::XSystemShellExecute > xSystemShellExecute( xFactory->createInstance(SERVICENAME_SYSTEMSHELLEXECUTE), css::uno::UNO_QUERY ); if (xSystemShellExecute.is()) { try { // start mail client // Because there is no notofocation about success - we use case of // no detected exception as SUCCESS - FAILED otherwhise. xSystemShellExecute->execute( aURL.Complete, ::rtl::OUString(), css::system::SystemShellExecuteFlags::DEFAULTS ); bSuccess = sal_True; } catch (css::lang::IllegalArgumentException&) { } catch (css::system::SystemShellExecuteException&) { } } return bSuccess; } //_________________________________________________________________________________________________________________ /** @short add/remove listener for state events @descr Because we use an external process to forward such mail URLs, and this process doesn't return any notifications about success or failed state - we doesn't support such status listener. We have no status to send. @param xListener reference to a valid listener for state events @param aURL URL about listener will be informed, if something occured @modified 30.04.2002 14:49, as96863 */ void SAL_CALL MailToDispatcher::addStatusListener( const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/ , const css::util::URL& /*aURL*/ ) throw( css::uno::RuntimeException ) { // not suported yet } //_________________________________________________________________________________________________________________ void SAL_CALL MailToDispatcher::removeStatusListener( const css::uno::Reference< css::frame::XStatusListener >& /*xListener*/ , const css::util::URL& /*aURL*/ ) throw( css::uno::RuntimeException ) { // not suported yet } } // namespace framework <|endoftext|>
<commit_before><commit_msg>Add DetPid in ConvertTRD<commit_after><|endoftext|>
<commit_before>/* * Rule.cpp * * Created on: 18 Feb 2014 * Author: s0565741 */ #include <limits> #include <cassert> #include "Rule.h" #include "Parameter.h" #include "LatticeArc.h" #include "ConsistentPhrases.h" #include "AlignedSentence.h" using namespace std; Rule::Rule(const LatticeArc &arc) :m_isValid(true) ,m_canExtend(true) { m_arcs.push_back(&arc); } Rule::Rule(const Rule &prevRule, const LatticeArc &arc) :m_arcs(prevRule.m_arcs) ,m_isValid(true) ,m_canExtend(true) { m_arcs.push_back(&arc); } Rule::~Rule() { // TODO Auto-generated destructor stub } bool Rule::IsValid(const Parameter &params) const { if (!m_isValid) { return false; } return true; } bool Rule::CanExtend(const Parameter &params) const { return true; } void Rule::Fillout(const ConsistentPhrases &consistentPhrases, const AlignedSentence &alignedSentence, const Parameter &params) { // if last word is a non-term, check to see if it overlaps with any other non-terms if (m_arcs.back()->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(m_arcs.back()); const ConsistentRange &lastTargetRange = sourceRange->GetOtherRange(); for (size_t i = 0; i < m_arcs.size() - 1; ++i) { const LatticeArc *arc = m_arcs[i]; if (arc->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(arc); const ConsistentRange &targetRange = sourceRange->GetOtherRange(); if (lastTargetRange.Overlap(targetRange)) { cerr << "NOT VALID1"; Debug(cerr); m_isValid = false; m_canExtend = false; return; } } } } // find out if it's a consistent phrase int sourceStart = m_arcs.front()->GetStart(); int sourceEnd = m_arcs.back()->GetEnd(); int targetStart = numeric_limits<int>::max(); int targetEnd = -1; for (size_t i = 0; i < m_arcs.size(); ++i) { const LatticeArc &arc = *m_arcs[i]; if (arc.GetStart() < targetStart) { targetStart = arc.GetStart(); } if (arc.GetEnd() > targetEnd) { targetEnd = arc.GetEnd(); } } m_consistentPhrase = consistentPhrases.Find(sourceStart, sourceEnd, targetStart, targetEnd); if (m_consistentPhrase == NULL) { cerr << "NOT VALID2"; Debug(cerr); m_isValid = false; return; } // everything looks ok, create target phrase // get a list of all target non-term vector<const ConsistentRange*> targetNonTerms; for (size_t i = 0; i < m_arcs.size(); ++i) { const LatticeArc *arc = m_arcs[i]; if (arc->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(arc); const ConsistentRange &targetRange = sourceRange->GetOtherRange(); targetNonTerms.push_back(&targetRange); } } if (targetNonTerms.size() > params.maxNonTerm) { cerr << "NOT VALID3"; Debug(cerr); m_isValid = false; return; } // targetNonTerms will be deleted element-by-element as it is used CreateTargetPhrase(alignedSentence.GetPhrase(Moses::Output), targetStart, targetEnd, targetNonTerms); //assert(targetNonTerms.size() == 0); } void Rule::CreateTargetPhrase(const Phrase &targetPhrase, int targetStart, int targetEnd, vector<const ConsistentRange*> &targetNonTerms) { for (int pos = targetStart; pos <= targetEnd; ++pos) { const ConsistentRange *range = Overlap(pos, targetNonTerms); if (range) { // part of non-term. m_targetArcs.push_back(range); pos = range->GetEnd(); } else { // just use the word const Word *word = targetPhrase[pos]; m_targetArcs.push_back(word); } } } const ConsistentRange *Rule::Overlap(int pos, vector<const ConsistentRange*> &targetNonTerms) { vector<const ConsistentRange*>::iterator iter; for (iter = targetNonTerms.begin(); iter != targetNonTerms.end(); ++iter) { const ConsistentRange *range = *iter; if (range->Overlap(pos)) { // is part of a non-term. Delete the range targetNonTerms.erase(iter); return range; } } return NULL; } Rule *Rule::Extend(const LatticeArc &arc) const { Rule *ret = new Rule(*this, arc); return ret; } void Rule::Output(std::ostream &out, const std::vector<const LatticeArc*> &arcs) const { for (size_t i = 0; i < arcs.size(); ++i) { const LatticeArc &arc = *arcs[i]; arc.Output(out); out << " "; } } void Rule::Output(std::ostream &out) const { Output(out, m_arcs); out << " ||| "; Output(out, m_arcs); } void Rule::Debug(std::ostream &out) const { Output(out, m_arcs); out << "||| "; Output(out, m_targetArcs); if (m_consistentPhrase) { cerr << "||| m_consistentPhrase="; m_consistentPhrase->Debug(out); } out << endl; } <commit_msg>debug<commit_after>/* * Rule.cpp * * Created on: 18 Feb 2014 * Author: s0565741 */ #include <limits> #include <cassert> #include "Rule.h" #include "Parameter.h" #include "LatticeArc.h" #include "ConsistentPhrases.h" #include "AlignedSentence.h" using namespace std; Rule::Rule(const LatticeArc &arc) :m_isValid(true) ,m_canExtend(true) { m_arcs.push_back(&arc); } Rule::Rule(const Rule &prevRule, const LatticeArc &arc) :m_arcs(prevRule.m_arcs) ,m_isValid(true) ,m_canExtend(true) { m_arcs.push_back(&arc); } Rule::~Rule() { // TODO Auto-generated destructor stub } bool Rule::IsValid(const Parameter &params) const { if (!m_isValid) { return false; } return true; } bool Rule::CanExtend(const Parameter &params) const { return true; } void Rule::Fillout(const ConsistentPhrases &consistentPhrases, const AlignedSentence &alignedSentence, const Parameter &params) { // if last word is a non-term, check to see if it overlaps with any other non-terms if (m_arcs.back()->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(m_arcs.back()); const ConsistentRange &lastTargetRange = sourceRange->GetOtherRange(); for (size_t i = 0; i < m_arcs.size() - 1; ++i) { const LatticeArc *arc = m_arcs[i]; if (arc->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(arc); const ConsistentRange &targetRange = sourceRange->GetOtherRange(); if (lastTargetRange.Overlap(targetRange)) { cerr << "NOT VALID1"; Debug(cerr); m_isValid = false; m_canExtend = false; return; } } } } // find out if it's a consistent phrase int sourceStart = m_arcs.front()->GetStart(); int sourceEnd = m_arcs.back()->GetEnd(); int targetStart = numeric_limits<int>::max(); int targetEnd = -1; for (size_t i = 0; i < m_arcs.size(); ++i) { const LatticeArc &arc = *m_arcs[i]; if (arc.GetLowestAlignment() < targetStart) { targetStart = arc.GetLowestAlignment(); } if (arc.GetHighestAlignment() > targetEnd) { targetEnd = arc.GetHighestAlignment(); } } m_consistentPhrase = consistentPhrases.Find(sourceStart, sourceEnd, targetStart, targetEnd); if (m_consistentPhrase == NULL) { cerr << "NOT VALID2"; Debug(cerr); m_isValid = false; return; } // everything looks ok, create target phrase // get a list of all target non-term vector<const ConsistentRange*> targetNonTerms; for (size_t i = 0; i < m_arcs.size(); ++i) { const LatticeArc *arc = m_arcs[i]; if (arc->IsNonTerm()) { const ConsistentRange *sourceRange = static_cast<const ConsistentRange *>(arc); const ConsistentRange &targetRange = sourceRange->GetOtherRange(); targetNonTerms.push_back(&targetRange); } } if (targetNonTerms.size() > params.maxNonTerm) { cerr << "NOT VALID3"; Debug(cerr); m_isValid = false; return; } // targetNonTerms will be deleted element-by-element as it is used CreateTargetPhrase(alignedSentence.GetPhrase(Moses::Output), targetStart, targetEnd, targetNonTerms); //assert(targetNonTerms.size() == 0); } void Rule::CreateTargetPhrase(const Phrase &targetPhrase, int targetStart, int targetEnd, vector<const ConsistentRange*> &targetNonTerms) { for (int pos = targetStart; pos <= targetEnd; ++pos) { const ConsistentRange *range = Overlap(pos, targetNonTerms); if (range) { // part of non-term. m_targetArcs.push_back(range); pos = range->GetEnd(); } else { // just use the word const Word *word = targetPhrase[pos]; m_targetArcs.push_back(word); } } } const ConsistentRange *Rule::Overlap(int pos, vector<const ConsistentRange*> &targetNonTerms) { vector<const ConsistentRange*>::iterator iter; for (iter = targetNonTerms.begin(); iter != targetNonTerms.end(); ++iter) { const ConsistentRange *range = *iter; if (range->Overlap(pos)) { // is part of a non-term. Delete the range targetNonTerms.erase(iter); return range; } } return NULL; } Rule *Rule::Extend(const LatticeArc &arc) const { Rule *ret = new Rule(*this, arc); return ret; } void Rule::Output(std::ostream &out, const std::vector<const LatticeArc*> &arcs) const { for (size_t i = 0; i < arcs.size(); ++i) { const LatticeArc &arc = *arcs[i]; arc.Output(out); out << " "; } } void Rule::Output(std::ostream &out) const { Output(out, m_arcs); out << "||| "; Output(out, m_arcs); } void Rule::Debug(std::ostream &out) const { Output(out, m_arcs); out << "||| "; Output(out, m_targetArcs); if (m_consistentPhrase) { cerr << "||| m_consistentPhrase="; m_consistentPhrase->Debug(out); } out << endl; } <|endoftext|>
<commit_before>// $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Matthias Richter <[email protected]> * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliHLTHOMERLibManager.cxx @author Matthias Richter @date @brief dynamic HLT HOMER reader/writer generation and destruction. */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #include <cerrno> #include <cassert> #include "AliHLTHOMERLibManager.h" #include "AliHLTHOMERReader.h" #include "AliHLTHOMERWriter.h" #include "TString.h" #include "TSystem.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTHOMERLibManager) AliHLTHOMERLibManager::AliHLTHOMERLibManager() : fLibraryStatus(0), fFctCreateReaderFromTCPPort(NULL), fFctCreateReaderFromTCPPorts(NULL), fFctCreateReaderFromBuffer(NULL), fFctDeleteReader(NULL), fFctCreateWriter(NULL), fFctDeleteWriter(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTHOMERLibManager::~AliHLTHOMERLibManager() { // see header file for class documentation } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(const char* hostname, unsigned short port ) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromTCPPort!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromTCPPort_t)fFctCreateReaderFromTCPPort)(hostname, port)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromTCPPort); } return pReader; } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(unsigned int tcpCnt, const char** hostnames, unsigned short* ports) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromTCPPorts!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromTCPPorts_t)fFctCreateReaderFromTCPPorts)(tcpCnt, hostnames, ports)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromTCPPorts); } return pReader; } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(const AliHLTUInt8_t* pBuffer, int size) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromBuffer!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromBuffer_t)fFctCreateReaderFromBuffer)(pBuffer, size)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromBuffer); } return pReader; } int AliHLTHOMERLibManager::DeleteReader(AliHLTHOMERReader* pReader) { // see header file for class documentation if (fLibraryStatus<0) return fLibraryStatus; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } if (fFctDeleteReader!=NULL) { ((AliHLTHOMERReaderDelete_t)fFctDeleteReader)(pReader); } return 0; } AliHLTHOMERWriter* AliHLTHOMERLibManager::OpenWriter() { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERWriter* pWriter=NULL; // if (fFctCreateWriter!=NULL && (pWriter=(((AliHLTHOMERWriterCreate_t)fFctCreateWriter)()))==NULL) { // HLTError("can not create instance of HOMER writer (function %p)", fFctCreateWriter); // } return pWriter; } int AliHLTHOMERLibManager::DeleteWriter(AliHLTHOMERWriter* pWriter) { // see header file for class documentation if (fLibraryStatus<0) return fLibraryStatus; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } if (fFctDeleteWriter!=NULL) { ((AliHLTHOMERWriterDelete_t)fFctDeleteWriter)(pWriter); } return 0; } int AliHLTHOMERLibManager::LoadHOMERLibrary() { // see header file for class documentation int iResult=-EBADF; const char* libraries[]={"libAliHLTHOMER.so", "libHOMER.so", NULL}; const char** library=&libraries[0]; do { TString libs = gSystem->GetLibraries(); if (libs.Contains(*library) || (gSystem->Load(*library)) >= 0) { iResult=1; break; } } while (*(++library)!=NULL); if (iResult>0 && *library!=NULL) { // print compile info typedef void (*CompileInfo)( char*& date, char*& time); CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(*library, "CompileInfo"); if (fctInfo) { char* date=""; char* time=""; (*fctInfo)(date, time); if (!date) date="unknown"; if (!time) time="unknown"; //HLTInfo("%s build on %s (%s)", *library, date, time); } else { //HLTInfo("no build info available for %s", *library); } fFctCreateReaderFromTCPPort=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_TCPPORT); fFctCreateReaderFromTCPPorts=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_TCPPORTS); fFctCreateReaderFromBuffer=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_BUFFER); fFctDeleteReader=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_DELETE); fFctCreateWriter=gSystem->DynFindSymbol(*library, ALIHLTHOMERWRITER_CREATE); fFctDeleteWriter=gSystem->DynFindSymbol(*library, ALIHLTHOMERWRITER_DELETE); if (fFctCreateReaderFromTCPPort==NULL || fFctCreateReaderFromTCPPorts==NULL || fFctCreateReaderFromBuffer==NULL || fFctDeleteReader==NULL || fFctCreateWriter==NULL || fFctDeleteWriter==NULL) { iResult=-ENOSYS; } else { } } if (iResult<0 || *library==NULL) { fFctCreateReaderFromTCPPort=NULL; fFctCreateReaderFromTCPPorts=NULL; fFctCreateReaderFromBuffer=NULL; fFctDeleteReader=NULL; fFctCreateWriter=NULL; fFctDeleteWriter=NULL; } return iResult; } <commit_msg>bugfix: call of creator function for HOMER writers<commit_after>// $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Matthias Richter <[email protected]> * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliHLTHOMERLibManager.cxx @author Matthias Richter @date @brief dynamic HLT HOMER reader/writer generation and destruction. */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #include <cerrno> #include <cassert> #include "AliHLTHOMERLibManager.h" #include "AliHLTHOMERReader.h" #include "AliHLTHOMERWriter.h" #include "TString.h" #include "TSystem.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTHOMERLibManager) AliHLTHOMERLibManager::AliHLTHOMERLibManager() : fLibraryStatus(0), fFctCreateReaderFromTCPPort(NULL), fFctCreateReaderFromTCPPorts(NULL), fFctCreateReaderFromBuffer(NULL), fFctDeleteReader(NULL), fFctCreateWriter(NULL), fFctDeleteWriter(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTHOMERLibManager::~AliHLTHOMERLibManager() { // see header file for class documentation } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(const char* hostname, unsigned short port ) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromTCPPort!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromTCPPort_t)fFctCreateReaderFromTCPPort)(hostname, port)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromTCPPort); } return pReader; } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(unsigned int tcpCnt, const char** hostnames, unsigned short* ports) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromTCPPorts!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromTCPPorts_t)fFctCreateReaderFromTCPPorts)(tcpCnt, hostnames, ports)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromTCPPorts); } return pReader; } AliHLTHOMERReader* AliHLTHOMERLibManager::OpenReader(const AliHLTUInt8_t* pBuffer, int size) { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERReader* pReader=NULL; if (fFctCreateReaderFromBuffer!=NULL && (pReader=(((AliHLTHOMERReaderCreateFromBuffer_t)fFctCreateReaderFromBuffer)(pBuffer, size)))==NULL) { //HLTError("can not create instance of HOMER reader (function %p)", fFctCreateReaderFromBuffer); } return pReader; } int AliHLTHOMERLibManager::DeleteReader(AliHLTHOMERReader* pReader) { // see header file for class documentation if (fLibraryStatus<0) return fLibraryStatus; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } if (fFctDeleteReader!=NULL) { ((AliHLTHOMERReaderDelete_t)fFctDeleteReader)(pReader); } return 0; } AliHLTHOMERWriter* AliHLTHOMERLibManager::OpenWriter() { // see header file for class documentation if (fLibraryStatus<0) return NULL; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } AliHLTHOMERWriter* pWriter=NULL; if (fFctCreateWriter!=NULL && (pWriter=(((AliHLTHOMERWriterCreate_t)fFctCreateWriter)()))==NULL) { // HLTError("can not create instance of HOMER writer (function %p)", fFctCreateWriter); } return pWriter; } int AliHLTHOMERLibManager::DeleteWriter(AliHLTHOMERWriter* pWriter) { // see header file for class documentation if (fLibraryStatus<0) return fLibraryStatus; if (fLibraryStatus==0) { fLibraryStatus=LoadHOMERLibrary(); } if (fFctDeleteWriter!=NULL) { ((AliHLTHOMERWriterDelete_t)fFctDeleteWriter)(pWriter); } return 0; } int AliHLTHOMERLibManager::LoadHOMERLibrary() { // see header file for class documentation int iResult=-EBADF; const char* libraries[]={"libAliHLTHOMER.so", "libHOMER.so", NULL}; const char** library=&libraries[0]; do { TString libs = gSystem->GetLibraries(); if (libs.Contains(*library) || (gSystem->Load(*library)) >= 0) { iResult=1; break; } } while (*(++library)!=NULL); if (iResult>0 && *library!=NULL) { // print compile info typedef void (*CompileInfo)( char*& date, char*& time); CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(*library, "CompileInfo"); if (fctInfo) { char* date=""; char* time=""; (*fctInfo)(date, time); if (!date) date="unknown"; if (!time) time="unknown"; //HLTInfo("%s build on %s (%s)", *library, date, time); } else { //HLTInfo("no build info available for %s", *library); } fFctCreateReaderFromTCPPort=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_TCPPORT); fFctCreateReaderFromTCPPorts=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_TCPPORTS); fFctCreateReaderFromBuffer=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_CREATE_FROM_BUFFER); fFctDeleteReader=gSystem->DynFindSymbol(*library, ALIHLTHOMERREADER_DELETE); fFctCreateWriter=gSystem->DynFindSymbol(*library, ALIHLTHOMERWRITER_CREATE); fFctDeleteWriter=gSystem->DynFindSymbol(*library, ALIHLTHOMERWRITER_DELETE); if (fFctCreateReaderFromTCPPort==NULL || fFctCreateReaderFromTCPPorts==NULL || fFctCreateReaderFromBuffer==NULL || fFctDeleteReader==NULL || fFctCreateWriter==NULL || fFctDeleteWriter==NULL) { iResult=-ENOSYS; } else { } } if (iResult<0 || *library==NULL) { fFctCreateReaderFromTCPPort=NULL; fFctCreateReaderFromTCPPorts=NULL; fFctCreateReaderFromBuffer=NULL; fFctDeleteReader=NULL; fFctCreateWriter=NULL; fFctDeleteWriter=NULL; } return iResult; } <|endoftext|>
<commit_before>#include "scantargetwidget.h" #include <QDebug> #include <QOpenGLContext> #include <QTimer> #include "../../ClockReceiver/TimeTypes.hpp" ScanTargetWidget::ScanTargetWidget(QWidget *parent) : QOpenGLWidget(parent) {} ScanTargetWidget::~ScanTargetWidget() {} void ScanTargetWidget::initializeGL() { glClearColor(0.5, 0.5, 1.0, 1.0); // Follow each swapped frame with an additional update. connect(this, &QOpenGLWidget::frameSwapped, this, &ScanTargetWidget::vsync); // qDebug() << "share context: " << bool(context()->shareGroup()); } void ScanTargetWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT); if(scanTarget) { vsync_predictor_.begin_redraw(); scanTarget->update(width(), height()); scanTarget->draw(width(), height()); vsync_predictor_.end_redraw(); // static int64_t start = 0; // static int frames = 0; // if(!start) start = Time::nanos_now(); // else { // ++frames; // const int64_t now = Time::nanos_now(); // qDebug() << double(frames) * 1e9 / double(now - start); // } } } void ScanTargetWidget::vsync() { vsync_predictor_.announce_vsync(); const auto time_now = Time::nanos_now(); const auto delay_time = ((vsync_predictor_.suggested_draw_time() - time_now) / 1'000'000) - 5; // TODO: the extra 5 is a random guess. if(delay_time > 0) { QTimer::singleShot(delay_time, this, SLOT(repaint())); } else { repaint(); } } void ScanTargetWidget::resizeGL(int w, int h) { glViewport(0,0,w,h); } Outputs::Display::OpenGL::ScanTarget *ScanTargetWidget::getScanTarget() { makeCurrent(); if(!scanTarget) { scanTarget = std::make_unique<Outputs::Display::OpenGL::ScanTarget>(defaultFramebufferObject()); } return scanTarget.get(); } <commit_msg>Retains the default window background colour until a machine is running.<commit_after>#include "scantargetwidget.h" #include <QDebug> #include <QOpenGLContext> #include <QTimer> #include "../../ClockReceiver/TimeTypes.hpp" ScanTargetWidget::ScanTargetWidget(QWidget *parent) : QOpenGLWidget(parent) {} ScanTargetWidget::~ScanTargetWidget() {} void ScanTargetWidget::initializeGL() { // Retain the default background colour. const QColor backgroundColour = palette().color(QWidget::backgroundRole()); glClearColor(backgroundColour.redF(), backgroundColour.greenF(), backgroundColour.blueF(), 1.0); // Follow each swapped frame with an additional update. connect(this, &QOpenGLWidget::frameSwapped, this, &ScanTargetWidget::vsync); } void ScanTargetWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT); if(scanTarget) { vsync_predictor_.begin_redraw(); scanTarget->update(width(), height()); scanTarget->draw(width(), height()); vsync_predictor_.end_redraw(); } } void ScanTargetWidget::vsync() { vsync_predictor_.announce_vsync(); const auto time_now = Time::nanos_now(); const auto delay_time = ((vsync_predictor_.suggested_draw_time() - time_now) / 1'000'000) - 5; // TODO: the extra 5 is a random guess. if(delay_time > 0) { QTimer::singleShot(delay_time, this, SLOT(repaint())); } else { repaint(); } } void ScanTargetWidget::resizeGL(int w, int h) { glViewport(0,0,w,h); } Outputs::Display::OpenGL::ScanTarget *ScanTargetWidget::getScanTarget() { makeCurrent(); if(!scanTarget) { scanTarget = std::make_unique<Outputs::Display::OpenGL::ScanTarget>(defaultFramebufferObject()); } return scanTarget.get(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <iostream> #include <gtest/gtest.h> #include <qi/clock.hpp> #include <qi/os.hpp> #include <boost/chrono/chrono_io.hpp> namespace chrono = boost::chrono; TEST(QiClock, initialization) { qi::Duration d0; EXPECT_EQ(0, d0.count()); qi::Duration d1 = qi::Duration::zero(); EXPECT_EQ(0, d1.count()); qi::Duration d2 = qi::Duration(); EXPECT_EQ(0, d2.count()); qi::Duration d3(0); EXPECT_EQ(0, d3.count()); qi::Clock::time_point t0; EXPECT_EQ(0, t0.time_since_epoch().count()); qi::Clock::time_point t1(qi::Duration::zero()); EXPECT_EQ(0, t1.time_since_epoch().count()); qi::Clock::time_point t2 = qi::Clock::time_point(); EXPECT_EQ(0, t2.time_since_epoch().count()); } //TEST(QiClock, clock_sleep) //{ // typedef chrono::duration<int64_t, boost::pico> picoseconds; // qi::sleepFor(chrono::milliseconds(1)); // qi::sleepFor(chrono::milliseconds(1) + picoseconds(1)); // qi::sleepFor(picoseconds(1)); // qi::sleepUntil(qi::SteadyClock::now() + chrono::seconds(1)); // qi::sleepUntil(qi::SteadyClock::now()); // qi::sleepUntil(qi::SteadyClock::now() - chrono::seconds(1)); // qi::sleepUntil(qi::SystemClock::now() + chrono::seconds(1)); // qi::sleepUntil(qi::SystemClock::now()); // qi::sleepUntil(qi::SystemClock::now() - chrono::seconds(1)); //} TEST(QiClock, clock_sleep_our) { qi::sleepFor(qi::MilliSeconds(1)); qi::sleepUntil(qi::SteadyClock::now() + qi::Seconds(1)); qi::sleepUntil(qi::SteadyClock::now()); qi::sleepUntil(qi::SteadyClock::now() - qi::Seconds(1)); qi::sleepUntil(qi::Clock::now() + qi::Seconds(1)); qi::sleepUntil(qi::Clock::now()); qi::sleepUntil(qi::Clock::now() - qi::Seconds(1)); qi::sleepUntil(qi::SystemClock::now() + qi::Seconds(1)); qi::sleepUntil(qi::SystemClock::now()); qi::sleepUntil(qi::SystemClock::now() - qi::Seconds(1)); } template<class Clock> void clock_output_() { typename Clock::duration d(1); typename Clock::time_point t = Clock::now(); std::cout << "name: " << boost::chrono::clock_string<Clock, char>::name() << ",\t" << "tick: " << d << ",\t" << "now: " << t << "\n"; // same, using wide chars std::wcout << "name: " << boost::chrono::clock_string<Clock, wchar_t>::name() << ",\t" << "tick: " << d << ",\t" << "now: " << t << "\n"; } TEST(QiClock, clock_output) { clock_output_<qi::SteadyClock>(); clock_output_<qi::Clock>(); clock_output_<qi::SystemClock>(); } typedef chrono::duration<uint32_t, boost::milli > uint32ms; TEST(QiClock, tofromUint32ms) { // a test to show how we can convert from 32-bits guess-what-my-epoch-is // time stamps to qi::SteadyClock::time_point qi::Clock::duration period = qi::Clock::duration(uint32ms::max()) + qi::Clock::duration(uint32ms(1)); qi::Clock::duration eps = chrono::milliseconds(4); // check sum-ms "noise" is removed qi::Clock::duration noise = chrono::nanoseconds(654321); qi::Clock::time_point t(period/4); uint32_t input_ms = chrono::duration_cast<uint32ms>(t.time_since_epoch()).count(); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t+noise, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t-noise, qi::Clock::Expect_SoonerOrLater)); // check we get the expected values for (int i = 0; i<8; ++i) { t = qi::Clock::time_point((i*period)/4); input_ms = chrono::duration_cast<uint32ms>(t.time_since_epoch()).count(); EXPECT_EQ(input_ms, qi::Clock::toUint32ms(t)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period/2, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period/2 + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period/2 + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period/2, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period/2 - eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + period - eps, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period + eps, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period - eps, qi::Clock::Expect_Later)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period + eps, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_Later)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_Later)); } } TEST(QiClock, toIso8601String) { qi::SystemClockTimePoint t0(qi::Duration(0)); EXPECT_EQ("1970-01-01T000000.000Z", qi::toISO8601String(t0)); // we do not round, we ceil: EXPECT_EQ("1970-01-01T000000.000Z", qi::toISO8601String(t0 + qi::MicroSeconds(999))); EXPECT_EQ("1970-01-01T000001.042Z", qi::toISO8601String(t0 + qi::MilliSeconds(1042))); EXPECT_EQ("1970-02-01T010203.000Z", qi::toISO8601String(t0 + qi::Hours(24*31+1)+qi::Minutes(2)+qi::Seconds(3))); } TEST(QiClock, durationSince) { qi::SteadyClock::time_point tp = qi::SteadyClock::now(); const qi::Duration sleepDuration = qi::MilliSeconds(500); const qi::MilliSeconds sleepDurationMs = boost::chrono::duration_cast<qi::MilliSeconds>(sleepDuration); const qi::MicroSeconds sleepDurationUs = boost::chrono::duration_cast<qi::MicroSeconds>(sleepDuration); qi::sleepFor(sleepDuration); const qi::MilliSeconds durMs = qi::durationSince<qi::MilliSeconds>(tp); const qi::MicroSeconds durUs = qi::durationSince<qi::MicroSeconds>(tp); const qi::Duration tol = qi::MilliSeconds(1); // only needed on Windows EXPECT_GE(durMs + tol, sleepDurationMs); EXPECT_GE(durUs + tol, sleepDurationUs); } <commit_msg>chrono::duration is not zero-initialized #31991<commit_after>/* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <iostream> #include <gtest/gtest.h> #include <qi/clock.hpp> #include <qi/os.hpp> #include <boost/chrono/chrono_io.hpp> namespace chrono = boost::chrono; TEST(QiClock, initialization) { qi::Duration d0 = qi::Duration::zero(); EXPECT_EQ(0, d0.count()); qi::Duration d1(0); EXPECT_EQ(0, d1.count()); qi::Clock::time_point t0; EXPECT_EQ(0, t0.time_since_epoch().count()); qi::Clock::time_point t1(qi::Duration::zero()); EXPECT_EQ(0, t1.time_since_epoch().count()); qi::Clock::time_point t2 = qi::Clock::time_point(); EXPECT_EQ(0, t2.time_since_epoch().count()); } //TEST(QiClock, clock_sleep) //{ // typedef chrono::duration<int64_t, boost::pico> picoseconds; // qi::sleepFor(chrono::milliseconds(1)); // qi::sleepFor(chrono::milliseconds(1) + picoseconds(1)); // qi::sleepFor(picoseconds(1)); // qi::sleepUntil(qi::SteadyClock::now() + chrono::seconds(1)); // qi::sleepUntil(qi::SteadyClock::now()); // qi::sleepUntil(qi::SteadyClock::now() - chrono::seconds(1)); // qi::sleepUntil(qi::SystemClock::now() + chrono::seconds(1)); // qi::sleepUntil(qi::SystemClock::now()); // qi::sleepUntil(qi::SystemClock::now() - chrono::seconds(1)); //} TEST(QiClock, clock_sleep_our) { qi::sleepFor(qi::MilliSeconds(1)); qi::sleepUntil(qi::SteadyClock::now() + qi::Seconds(1)); qi::sleepUntil(qi::SteadyClock::now()); qi::sleepUntil(qi::SteadyClock::now() - qi::Seconds(1)); qi::sleepUntil(qi::Clock::now() + qi::Seconds(1)); qi::sleepUntil(qi::Clock::now()); qi::sleepUntil(qi::Clock::now() - qi::Seconds(1)); qi::sleepUntil(qi::SystemClock::now() + qi::Seconds(1)); qi::sleepUntil(qi::SystemClock::now()); qi::sleepUntil(qi::SystemClock::now() - qi::Seconds(1)); } template<class Clock> void clock_output_() { typename Clock::duration d(1); typename Clock::time_point t = Clock::now(); std::cout << "name: " << boost::chrono::clock_string<Clock, char>::name() << ",\t" << "tick: " << d << ",\t" << "now: " << t << "\n"; // same, using wide chars std::wcout << "name: " << boost::chrono::clock_string<Clock, wchar_t>::name() << ",\t" << "tick: " << d << ",\t" << "now: " << t << "\n"; } TEST(QiClock, clock_output) { clock_output_<qi::SteadyClock>(); clock_output_<qi::Clock>(); clock_output_<qi::SystemClock>(); } typedef chrono::duration<uint32_t, boost::milli > uint32ms; TEST(QiClock, tofromUint32ms) { // a test to show how we can convert from 32-bits guess-what-my-epoch-is // time stamps to qi::SteadyClock::time_point qi::Clock::duration period = qi::Clock::duration(uint32ms::max()) + qi::Clock::duration(uint32ms(1)); qi::Clock::duration eps = chrono::milliseconds(4); // check sum-ms "noise" is removed qi::Clock::duration noise = chrono::nanoseconds(654321); qi::Clock::time_point t(period/4); uint32_t input_ms = chrono::duration_cast<uint32ms>(t.time_since_epoch()).count(); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t+noise, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t-noise, qi::Clock::Expect_SoonerOrLater)); // check we get the expected values for (int i = 0; i<8; ++i) { t = qi::Clock::time_point((i*period)/4); input_ms = chrono::duration_cast<uint32ms>(t.time_since_epoch()).count(); EXPECT_EQ(input_ms, qi::Clock::toUint32ms(t)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period/2, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period/2 + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period/2 + eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period/2, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period/2 - eps, qi::Clock::Expect_SoonerOrLater)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_Sooner)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t + period - eps, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + period + eps, qi::Clock::Expect_Sooner)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period - eps, qi::Clock::Expect_Later)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t - period, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - period + eps, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t - eps, qi::Clock::Expect_Later)); EXPECT_TRUE(t == qi::Clock::fromUint32ms(input_ms, t, qi::Clock::Expect_Later)); EXPECT_FALSE(t == qi::Clock::fromUint32ms(input_ms, t + eps, qi::Clock::Expect_Later)); } } TEST(QiClock, toIso8601String) { qi::SystemClockTimePoint t0(qi::Duration(0)); EXPECT_EQ("1970-01-01T000000.000Z", qi::toISO8601String(t0)); // we do not round, we ceil: EXPECT_EQ("1970-01-01T000000.000Z", qi::toISO8601String(t0 + qi::MicroSeconds(999))); EXPECT_EQ("1970-01-01T000001.042Z", qi::toISO8601String(t0 + qi::MilliSeconds(1042))); EXPECT_EQ("1970-02-01T010203.000Z", qi::toISO8601String(t0 + qi::Hours(24*31+1)+qi::Minutes(2)+qi::Seconds(3))); } TEST(QiClock, durationSince) { qi::SteadyClock::time_point tp = qi::SteadyClock::now(); const qi::Duration sleepDuration = qi::MilliSeconds(500); const qi::MilliSeconds sleepDurationMs = boost::chrono::duration_cast<qi::MilliSeconds>(sleepDuration); const qi::MicroSeconds sleepDurationUs = boost::chrono::duration_cast<qi::MicroSeconds>(sleepDuration); qi::sleepFor(sleepDuration); const qi::MilliSeconds durMs = qi::durationSince<qi::MilliSeconds>(tp); const qi::MicroSeconds durUs = qi::durationSince<qi::MicroSeconds>(tp); const qi::Duration tol = qi::MilliSeconds(1); // only needed on Windows EXPECT_GE(durMs + tol, sleepDurationMs); EXPECT_GE(durUs + tol, sleepDurationUs); } <|endoftext|>
<commit_before>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2009-2014 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: [email protected] */ #include "OSDCipher.h" // 32 character key // "01234567890123456789012345678901" #define QGV_CIPHER_KEY "__THIS_IS_MY_EXTREMELY_LONG_KEY_" bool OsdCipher::_cipher(const QByteArray &byIn, QByteArray &byOut, bool bEncrypt) { return (true); }//OsdCipher::cipher <commit_msg>wp8: no encytion for you :P<commit_after>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2009-2014 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: [email protected] */ #include "OSDCipher.h" // 32 character key // "01234567890123456789012345678901" #define QGV_CIPHER_KEY "__THIS_IS_MY_EXTREMELY_LONG_KEY_" bool OsdCipher::_cipher(const QByteArray &byIn, QByteArray &byOut, bool bEncrypt) { // Do I reeealy need to encrypt anything when the app is entirely sandboxed? if (bEncrypt) { byOut = byIn.toBase64(); } else { byOut = QByteArray::fromBase64(byIn); } return (true); }//OsdCipher::cipher <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ /* * foregroundservice.cpp */ #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasnativeutils.h" #include "foregroundservice.h" ForegroundService::ForegroundService() {} ForegroundService::~ForegroundService() {} bool ForegroundService::executeService(TasCommandModel& model, TasResponse& response) { bool status = false; if(model.service() == serviceName()) { status = true; TasCommand* command = getCommandParameters(model, "BringToForeground"); if(command){ // Find app from client manager TasClientManager* clientManager = TasClientManager::instance(); TasClient* app = 0; app = clientManager->findByProcessId(command->parameter("pid")); if (app) { TasLogger::logger()->debug(" App found from client manager, PID: " + app->processId()); // Bring to foreground using native utils int error = TasNativeUtils::bringAppToForeground(*app); if (TAS_ERROR_NONE == error) { TasLogger::logger()->debug(" App brought to foreground"); } else { TasLogger::logger()->error(" Couldn't bring app to foreground, error: " + error); response.setErrorMessage(" Couldn't bring app to foreground, error: " + error); } } else { TasLogger::logger()->error(" App not found from client manager, PID: " + model.id()); response.setErrorMessage(" App not found from client manager, PID: " + model.id()); } } else { TasLogger::logger()->error(" Unknown command: " + model.name()); response.setErrorMessage(" Unknown command: " + model.name()); } } else if (model.service() == "changeOrientation" ){ TasCommand* command = getCommandParameters(model, "changeOrientation"); if(command){ TasNativeUtils::changeOrientation(command->parameter("direction")); } } return status; } <commit_msg>Change orientation for symbian<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ /* * foregroundservice.cpp */ #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasnativeutils.h" #include "foregroundservice.h" ForegroundService::ForegroundService() {} ForegroundService::~ForegroundService() {} bool ForegroundService::executeService(TasCommandModel& model, TasResponse& response) { bool status = false; if(model.service() == serviceName()) { status = true; TasCommand* command = getCommandParameters(model, "BringToForeground"); if(command){ // Find app from client manager TasClientManager* clientManager = TasClientManager::instance(); TasClient* app = 0; app = clientManager->findByProcessId(command->parameter("pid")); if (app) { TasLogger::logger()->debug(" App found from client manager, PID: " + app->processId()); // Bring to foreground using native utils int error = TasNativeUtils::bringAppToForeground(*app); if (TAS_ERROR_NONE == error) { TasLogger::logger()->debug(" App brought to foreground"); } else { TasLogger::logger()->error(" Couldn't bring app to foreground, error: " + error); response.setErrorMessage(" Couldn't bring app to foreground, error: " + error); } } else { TasLogger::logger()->error(" App not found from client manager, PID: " + model.id()); response.setErrorMessage(" App not found from client manager, PID: " + model.id()); } } else { TasLogger::logger()->error(" Unknown command: " + model.name()); response.setErrorMessage(" Unknown command: " + model.name()); } } else if (model.service() == "changeOrientation" ){ status = true; TasCommand* command = getCommandParameters(model, "ChangeOrientation"); if(command){ TasNativeUtils::changeOrientation(command->parameter("direction")); } } return status; } <|endoftext|>
<commit_before>#include <QtWidgets> #include <QtConcurrent> #include <random> std::default_random_engine reng; int ilog2(qint64 val) { Q_ASSERT(val >= 0); int ret = -1; while (val != 0) { val >>= 1; ret++; } return ret; } /// The value binned to contain at most \a binaryDigits significant digits. /// The less significant digits are reset to zero. qint64 binned(qint64 value, int binaryDigits) { Q_ASSERT(binaryDigits > 0); qint64 mask = -1; int clrBits = ilog2(value) - binaryDigits; if (clrBits > 0) mask <<= clrBits; return value & mask; } /// A safely destructible thread for perusal by QObjects. class Thread : public QThread { using QThread::run; public: explicit Thread(QObject * parent = 0) : QThread(parent) {} ~Thread() { quit(); wait(); } }; /// An application that monitors event loops in all threads. class MonitoringApp : public QApplication { Q_OBJECT Q_PROPERTY(int timeout READ timeout WRITE setTimeout MEMBER m_timeout) Q_PROPERTY(int updatePeriod READ updatePeriod WRITE setUpdatePeriod MEMBER m_updatePeriod) public: typedef QMap<qint64, uint> Histogram; typedef QApplication Base; private: struct ThreadData { /// A saturating, binned histogram of event handling durations for given thread. Histogram histogram; /// Number of milliseconds between the epoch and when the event handler on this thread /// was entered, or zero if no event handler is running. qint64 ping; /// Number of milliseconds between the epoch and when the last histogram update for /// this thread was broadcast qint64 update; /// Whether the thread's event loop is considered stuck at the moment bool stuck; ThreadData() : ping(0), update(0), stuck(false) {} }; typedef QMap<QThread*, ThreadData> Threads; QMutex m_mutex; Threads m_threads; int m_timeout; int m_updatePeriod; class StuckEventLoopNotifier : public QObject { MonitoringApp * m_app; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) Q_DECL_OVERRIDE { if (ev->timerId() != m_timer.timerId()) return; int timeout = m_app->m_timeout; auto now = QDateTime::currentMSecsSinceEpoch(); QList<QPair<QThread*, int>> toEmit; QMutexLocker lock(&m_app->m_mutex); for (auto it = m_app->m_threads.begin(); it != m_app->m_threads.end(); ++it) { if (it->ping == 0) continue; qint64 elapsed = now - it->ping; if (elapsed > timeout) { it->stuck = true; toEmit << qMakePair(it.key(), elapsed); } else { if (it->stuck) toEmit << qMakePair(it.key(), 0); it->stuck = false; } } lock.unlock(); for (auto & sig : toEmit) emit m_app->loopStateChanged(sig.first, sig.second); } public: explicit StuckEventLoopNotifier(MonitoringApp * app) : m_app(app) { m_timer.start(100, Qt::CoarseTimer, this); } }; StuckEventLoopNotifier m_notifier; Thread m_notifierThread; Q_SLOT void threadFinishedSlot() { auto const thread = qobject_cast<QThread*>(QObject::sender()); QMutexLocker lock(&m_mutex); typename Threads::iterator it = m_threads.find(thread); if (it == m_threads.end()) return; auto const histogram(it->histogram); bool stuck = it->stuck; m_threads.erase(it); lock.unlock(); emit newHistogram(thread, histogram); if (stuck) emit loopStateChanged(thread, 0); emit threadFinished(thread); } Q_SIGNAL void newThreadSignal(QThread*, const QString &); protected: bool notify(QObject * receiver, QEvent * event) Q_DECL_OVERRIDE { auto const curThread = QThread::currentThread(); QElapsedTimer timer; auto now = QDateTime::currentMSecsSinceEpoch(); QMutexLocker lock(&m_mutex); typename Threads::iterator it = m_threads.find(curThread); bool newThread = it == m_threads.end(); if (newThread) it = m_threads.insert(curThread, ThreadData()); it->ping = now; lock.unlock(); if (newThread) { connect(curThread, &QThread::finished, this, &MonitoringApp::threadFinishedSlot); emit newThreadSignal(curThread, curThread->objectName()); } timer.start(); auto result = Base::notify(receiver, event); // This is where the event loop can get "stuck". auto duration = binned(timer.elapsed(), 3); now += duration; lock.relock(); auto & thread = m_threads[curThread]; if (thread.histogram[duration] < std::numeric_limits<Histogram::mapped_type>::max()) ++thread.histogram[duration]; thread.ping = 0; qint64 sinceLastUpdate = now - thread.update; if (sinceLastUpdate >= m_updatePeriod) { auto const histogram = thread.histogram; thread.update = now; lock.unlock(); emit newHistogram(curThread, histogram); } return result; } public: explicit MonitoringApp(int & argc, char ** argv); /// The event loop for a given thread has gotten stuck, or unstuck. /** A zero elapsed time indicates that the loop is not stuck. The signal will be * emitted periodically with increasing values of `elapsed` for a given thread as long * as the loop is stuck. The thread might not exist when this notification is received. */ Q_SIGNAL void loopStateChanged(QThread *, int elapsed); /// The first event was received in a newly started thread's event loop. /** The thread might not exist when this notification is received. */ Q_SIGNAL void newThread(QThread *, const QString & threadName); /// The thread has a new histogram available. /** This signal is not sent more often than each updatePeriod(). * The thread might not exist when this notification is received. */ Q_SIGNAL void newHistogram(QThread *, const MonitoringApp::Histogram &); /// The thread has finished. /** The thread might not exist when this notification is received. A newHistogram * signal is always emitted prior to this signal's emission. */ Q_SIGNAL void threadFinished(QThread *); /// The maximum number of milliseconds an event handler can run before the event loop /// is considered stuck. int timeout() const { return m_timeout; } Q_SLOT void setTimeout(int timeout) { m_timeout = timeout; } int updatePeriod() const { return m_updatePeriod; } Q_SLOT void setUpdatePeriod(int updatePeriod) { m_updatePeriod = updatePeriod; } }; Q_DECLARE_METATYPE(QThread*) Q_DECLARE_METATYPE(MonitoringApp::Histogram) MonitoringApp::MonitoringApp(int & argc, char ** argv) : MonitoringApp::Base(argc, argv), m_timeout(1000), m_updatePeriod(250), m_notifier(this) { qRegisterMetaType<QThread*>(); qRegisterMetaType<MonitoringApp::Histogram>(); connect(this, &MonitoringApp::newThreadSignal, this, &MonitoringApp::newThread, Qt::QueuedConnection); m_notifier.moveToThread(&m_notifierThread); m_notifierThread.start(); } QImage renderHistogram(const MonitoringApp::Histogram & h) { const int blockX = 2, blockY = 2; QImage img(1 + h.size() * blockX, 32 * blockY, QImage::Format_ARGB32_Premultiplied); img.fill(Qt::white); QPainter p(&img); int x = 0; for (auto it = h.begin(); it != h.end(); ++it) { qreal key = it.key() > 0 ? log2(it.key()) : 0.0; QBrush b = QColor::fromHsv(qRound(240.0*(1.0 - key/32.0)), 255, 255); p.fillRect(QRectF(x, img.height(), blockX, -log2(it.value()) * blockY), b); x += blockX; } return img; } class MonitoringViewModel : public QStandardItemModel { Q_OBJECT QMap<QThread*, QPair<QStandardItem*, QStandardItem*>> m_threadItems; Q_SLOT void newThread(QThread * thread, const QString & threadName) { auto const caption = QString("0x%1 \"%2\"").arg(std::intptr_t(thread), 0, 16).arg(threadName); int row = rowCount() ? 1 : 0; insertRow(row); auto captionItem = new QStandardItem(caption); captionItem->setEditable(false); setItem(row, 0, captionItem); auto histogram = new QStandardItem; histogram->setEditable(false); setItem(row, 1, histogram); m_threadItems[thread] = qMakePair(captionItem, histogram); newHistogram(thread, MonitoringApp::Histogram()); } Q_SLOT void newHistogramImage(QThread * thread, const QImage & img) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->second->setSizeHint(img.size()); it->second->setData(img, Qt::DecorationRole); } Q_SIGNAL void newHistogramImageSignal(QThread * thread, const QImage & img); Q_SLOT void newHistogram(QThread * thread, const MonitoringApp::Histogram & histogram) { QtConcurrent::run([this, thread, histogram]{ emit newHistogramImageSignal(thread, renderHistogram(histogram)); }); } Q_SLOT void loopStateChanged(QThread * thread, int elapsed) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->first->setData(elapsed ? QColor(Qt::red) : QColor(Qt::transparent), Qt::BackgroundColorRole); } Q_SLOT void threadFinished(QThread * thread) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->first->setText(QString("Finished %1").arg(it->first->text())); m_threadItems.remove(thread); } public: MonitoringViewModel(QObject *parent = 0) : QStandardItemModel(parent) { connect(this, &MonitoringViewModel::newHistogramImageSignal, this, &MonitoringViewModel::newHistogramImage); auto app = qobject_cast<MonitoringApp*>(qApp); connect(app, &MonitoringApp::newThread, this, &MonitoringViewModel::newThread); connect(app, &MonitoringApp::newHistogram, this, &MonitoringViewModel::newHistogram); connect(app, &MonitoringApp::threadFinished, this, &MonitoringViewModel::threadFinished); connect(app, &MonitoringApp::loopStateChanged, this, &MonitoringViewModel::loopStateChanged); } }; class WorkerObject : public QObject { Q_OBJECT int m_trials; double m_probability; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) { if (ev->timerId() != m_timer.timerId()) return; QThread::msleep(std::binomial_distribution<>(m_trials, m_probability)(reng)); } public: WorkerObject(QObject * parent = 0) : QObject(parent), m_trials(2000), m_probability(0.2) {} Q_SLOT void start() { m_timer.start(0, this); } int trials() const { return m_trials; } Q_SLOT void setTrials(int trials) { m_trials = trials; } double probability() const { return m_probability; } Q_SLOT void setProbability(double p) { m_probability = p; } }; int main(int argc, char *argv[]) { MonitoringApp app(argc, argv); MonitoringViewModel model; WorkerObject workerObject; Thread workerThread; QWidget w; QGridLayout layout(&w); QTableView view; QLabel timeoutLabel; QSlider timeout(Qt::Horizontal); QGroupBox worker("Worker Thread"); worker.setCheckable(true); worker.setChecked(false); QGridLayout wLayout(&worker); QLabel rangeLabel, probabilityLabel; QSlider range(Qt::Horizontal), probability(Qt::Horizontal); timeoutLabel.setMinimumWidth(50); QObject::connect(&timeout, &QSlider::valueChanged, &timeoutLabel, (void(QLabel::*)(int))&QLabel::setNum); timeout.setMinimum(50); timeout.setMaximum(5000); timeout.setValue(app.timeout()); view.setModel(&model); view.verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); layout.addWidget(&view, 0, 0, 1, 3); layout.addWidget(new QLabel("Timeout"), 1, 0); layout.addWidget(&timeoutLabel, 1, 1); layout.addWidget(&timeout, 1, 2); layout.addWidget(&worker, 2, 0, 1, 3); QObject::connect(&range, &QAbstractSlider::valueChanged, [&](int p){ rangeLabel.setText(QString("Range %1 ms").arg(p)); workerObject.setTrials(p); }); QObject::connect(&probability, &QAbstractSlider::valueChanged, [&](int p){ double prob = p / (double)probability.maximum(); probabilityLabel.setText(QString("Probability %1").arg(prob, 0, 'g', 2)); workerObject.setProbability(prob); }); range.setMaximum(10000); range.setValue(workerObject.trials()); probability.setValue(workerObject.probability() * probability.maximum()); wLayout.addWidget(new QLabel("Sleep Time Binomial Distribution"), 0, 0, 1, 2); wLayout.addWidget(&rangeLabel, 1, 0); wLayout.addWidget(&range, 2, 0); wLayout.addWidget(&probabilityLabel, 1, 1); wLayout.addWidget(&probability, 2, 1); QObject::connect(&worker, &QGroupBox::toggled, [&](bool run) { if (run) { workerThread.start(); QMetaObject::invokeMethod(&workerObject, "start"); } else workerThread.quit(); }); QObject::connect(&timeout, &QAbstractSlider::valueChanged, &app, &MonitoringApp::setTimeout); workerObject.moveToThread(&workerThread); w.show(); return app.exec(); } #include "main.moc" <commit_msg>Fix orphaned timer errors.<commit_after>#include <QtWidgets> #include <QtConcurrent> #include <random> std::default_random_engine reng; int ilog2(qint64 val) { Q_ASSERT(val >= 0); int ret = -1; while (val != 0) { val >>= 1; ret++; } return ret; } /// The value binned to contain at most \a binaryDigits significant digits. /// The less significant digits are reset to zero. qint64 binned(qint64 value, int binaryDigits) { Q_ASSERT(binaryDigits > 0); qint64 mask = -1; int clrBits = ilog2(value) - binaryDigits; if (clrBits > 0) mask <<= clrBits; return value & mask; } /// A safely destructible thread for perusal by QObjects. class Thread final : public QThread { Q_OBJECT void run() override { connect(QAbstractEventDispatcher::instance(this), &QAbstractEventDispatcher::aboutToBlock, this, &Thread::aboutToBlock); QThread::run(); } QAtomicInt inDestructor; public: using QThread::QThread; /// Take an object and prevent timer resource leaks when the object is about /// to become threadless. void takeObject(QObject *obj) { // Work around to prevent // QBasicTimer::stop: Failed. Possibly trying to stop from a different thread static constexpr char kRegistered[] = "__ThreadRegistered"; static constexpr char kMoved[] = "__Moved"; if (!obj->property(kRegistered).isValid()) { QObject::connect(this, &Thread::finished, obj, [this, obj]{ if (!inDestructor.load() || obj->thread() != this) return; // The object is about to become threadless Q_ASSERT(obj->thread() == QThread::currentThread()); obj->setProperty(kMoved, true); obj->moveToThread(this->thread()); }, Qt::DirectConnection); QObject::connect(this, &QObject::destroyed, obj, [obj]{ if (!obj->thread()) { obj->moveToThread(QThread::currentThread()); obj->setProperty(kRegistered, {}); } else if (obj->thread() == QThread::currentThread() && obj->property(kMoved).isValid()) { obj->setProperty(kMoved, {}); QCoreApplication::sendPostedEvents(obj, QEvent::MetaCall); } else if (obj->thread()->eventDispatcher()) QTimer::singleShot(0, obj, [obj]{ obj->setProperty(kRegistered, {}); }); }, Qt::DirectConnection); obj->setProperty(kRegistered, true); } obj->moveToThread(this); } ~Thread() override { inDestructor.store(1); requestInterruption(); quit(); wait(); } Q_SIGNAL void aboutToBlock(); }; /// An application that monitors event loops in all threads. class MonitoringApp : public QApplication { Q_OBJECT Q_PROPERTY(int timeout READ timeout WRITE setTimeout MEMBER m_timeout) Q_PROPERTY(int updatePeriod READ updatePeriod WRITE setUpdatePeriod MEMBER m_updatePeriod) public: typedef QMap<qint64, uint> Histogram; typedef QApplication Base; private: struct ThreadData { /// A saturating, binned histogram of event handling durations for given thread. Histogram histogram; /// Number of milliseconds between the epoch and when the event handler on this thread /// was entered, or zero if no event handler is running. qint64 ping; /// Number of milliseconds between the epoch and when the last histogram update for /// this thread was broadcast qint64 update; /// Whether the thread's event loop is considered stuck at the moment bool stuck; ThreadData() : ping(0), update(0), stuck(false) {} }; typedef QMap<QThread*, ThreadData> Threads; QMutex m_mutex; Threads m_threads; int m_timeout; int m_updatePeriod; class StuckEventLoopNotifier : public QObject { MonitoringApp * m_app; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) Q_DECL_OVERRIDE { if (ev->timerId() != m_timer.timerId()) return; int timeout = m_app->m_timeout; auto now = QDateTime::currentMSecsSinceEpoch(); QList<QPair<QThread*, int>> toEmit; QMutexLocker lock(&m_app->m_mutex); for (auto it = m_app->m_threads.begin(); it != m_app->m_threads.end(); ++it) { if (it->ping == 0) continue; qint64 elapsed = now - it->ping; if (elapsed > timeout) { it->stuck = true; toEmit << qMakePair(it.key(), elapsed); } else { if (it->stuck) toEmit << qMakePair(it.key(), 0); it->stuck = false; } } lock.unlock(); for (auto & sig : toEmit) emit m_app->loopStateChanged(sig.first, sig.second); } public: explicit StuckEventLoopNotifier(MonitoringApp * app) : m_app(app) { m_timer.start(100, Qt::CoarseTimer, this); } }; StuckEventLoopNotifier m_notifier; Thread m_notifierThread; Q_SLOT void threadFinishedSlot() { auto const thread = qobject_cast<QThread*>(QObject::sender()); QMutexLocker lock(&m_mutex); typename Threads::iterator it = m_threads.find(thread); if (it == m_threads.end()) return; auto const histogram(it->histogram); bool stuck = it->stuck; m_threads.erase(it); lock.unlock(); emit newHistogram(thread, histogram); if (stuck) emit loopStateChanged(thread, 0); emit threadFinished(thread); } Q_SIGNAL void newThreadSignal(QThread*, const QString &); protected: bool notify(QObject * receiver, QEvent * event) Q_DECL_OVERRIDE { auto const curThread = QThread::currentThread(); QElapsedTimer timer; auto now = QDateTime::currentMSecsSinceEpoch(); QMutexLocker lock(&m_mutex); typename Threads::iterator it = m_threads.find(curThread); bool newThread = it == m_threads.end(); if (newThread) it = m_threads.insert(curThread, ThreadData()); it->ping = now; lock.unlock(); if (newThread) { connect(curThread, &QThread::finished, this, &MonitoringApp::threadFinishedSlot); emit newThreadSignal(curThread, curThread->objectName()); } timer.start(); auto result = Base::notify(receiver, event); // This is where the event loop can get "stuck". auto duration = binned(timer.elapsed(), 3); now += duration; lock.relock(); auto & thread = m_threads[curThread]; if (thread.histogram[duration] < std::numeric_limits<Histogram::mapped_type>::max()) ++thread.histogram[duration]; thread.ping = 0; qint64 sinceLastUpdate = now - thread.update; if (sinceLastUpdate >= m_updatePeriod) { auto const histogram = thread.histogram; thread.update = now; lock.unlock(); emit newHistogram(curThread, histogram); } return result; } public: explicit MonitoringApp(int & argc, char ** argv); /// The event loop for a given thread has gotten stuck, or unstuck. /** A zero elapsed time indicates that the loop is not stuck. The signal will be * emitted periodically with increasing values of `elapsed` for a given thread as long * as the loop is stuck. The thread might not exist when this notification is received. */ Q_SIGNAL void loopStateChanged(QThread *, int elapsed); /// The first event was received in a newly started thread's event loop. /** The thread might not exist when this notification is received. */ Q_SIGNAL void newThread(QThread *, const QString & threadName); /// The thread has a new histogram available. /** This signal is not sent more often than each updatePeriod(). * The thread might not exist when this notification is received. */ Q_SIGNAL void newHistogram(QThread *, const MonitoringApp::Histogram &); /// The thread has finished. /** The thread might not exist when this notification is received. A newHistogram * signal is always emitted prior to this signal's emission. */ Q_SIGNAL void threadFinished(QThread *); /// The maximum number of milliseconds an event handler can run before the event loop /// is considered stuck. int timeout() const { return m_timeout; } Q_SLOT void setTimeout(int timeout) { m_timeout = timeout; } int updatePeriod() const { return m_updatePeriod; } Q_SLOT void setUpdatePeriod(int updatePeriod) { m_updatePeriod = updatePeriod; } }; Q_DECLARE_METATYPE(QThread*) Q_DECLARE_METATYPE(MonitoringApp::Histogram) MonitoringApp::MonitoringApp(int & argc, char ** argv) : MonitoringApp::Base(argc, argv), m_timeout(1000), m_updatePeriod(250), m_notifier(this) { qRegisterMetaType<QThread*>(); qRegisterMetaType<MonitoringApp::Histogram>(); connect(this, &MonitoringApp::newThreadSignal, this, &MonitoringApp::newThread, Qt::QueuedConnection); m_notifier.moveToThread(&m_notifierThread); m_notifierThread.start(); } QImage renderHistogram(const MonitoringApp::Histogram & h) { const int blockX = 2, blockY = 2; QImage img(1 + h.size() * blockX, 32 * blockY, QImage::Format_ARGB32_Premultiplied); img.fill(Qt::white); QPainter p(&img); int x = 0; for (auto it = h.begin(); it != h.end(); ++it) { qreal key = it.key() > 0 ? log2(it.key()) : 0.0; QBrush b = QColor::fromHsv(qRound(240.0*(1.0 - key/32.0)), 255, 255); p.fillRect(QRectF(x, img.height(), blockX, -log2(it.value()) * blockY), b); x += blockX; } return img; } class MonitoringViewModel : public QStandardItemModel { Q_OBJECT QMap<QThread*, QPair<QStandardItem*, QStandardItem*>> m_threadItems; Q_SLOT void newThread(QThread * thread, const QString & threadName) { auto const caption = QString("0x%1 \"%2\"").arg(std::intptr_t(thread), 0, 16).arg(threadName); int row = rowCount() ? 1 : 0; insertRow(row); auto captionItem = new QStandardItem(caption); captionItem->setEditable(false); setItem(row, 0, captionItem); auto histogram = new QStandardItem; histogram->setEditable(false); setItem(row, 1, histogram); m_threadItems[thread] = qMakePair(captionItem, histogram); newHistogram(thread, MonitoringApp::Histogram()); } Q_SLOT void newHistogramImage(QThread * thread, const QImage & img) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->second->setSizeHint(img.size()); it->second->setData(img, Qt::DecorationRole); } Q_SIGNAL void newHistogramImageSignal(QThread * thread, const QImage & img); Q_SLOT void newHistogram(QThread * thread, const MonitoringApp::Histogram & histogram) { QtConcurrent::run([this, thread, histogram]{ emit newHistogramImageSignal(thread, renderHistogram(histogram)); }); } Q_SLOT void loopStateChanged(QThread * thread, int elapsed) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->first->setData(elapsed ? QColor(Qt::red) : QColor(Qt::transparent), Qt::BackgroundColorRole); } Q_SLOT void threadFinished(QThread * thread) { auto it = m_threadItems.find(thread); if (it == m_threadItems.end()) return; it->first->setText(QString("Finished %1").arg(it->first->text())); m_threadItems.remove(thread); } public: MonitoringViewModel(QObject *parent = 0) : QStandardItemModel(parent) { connect(this, &MonitoringViewModel::newHistogramImageSignal, this, &MonitoringViewModel::newHistogramImage); auto app = qobject_cast<MonitoringApp*>(qApp); connect(app, &MonitoringApp::newThread, this, &MonitoringViewModel::newThread); connect(app, &MonitoringApp::newHistogram, this, &MonitoringViewModel::newHistogram); connect(app, &MonitoringApp::threadFinished, this, &MonitoringViewModel::threadFinished); connect(app, &MonitoringApp::loopStateChanged, this, &MonitoringViewModel::loopStateChanged); } }; class WorkerObject : public QObject { Q_OBJECT int m_trials = 2000; double m_probability = 0.2; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) override { if (ev->timerId() != m_timer.timerId()) return; QThread::msleep(std::binomial_distribution<>(m_trials, m_probability)(reng)); } public: using QObject::QObject; Q_SIGNAL void stopped(); Q_SLOT void start() { m_timer.start(0, this); } Q_SLOT void stop() { m_timer.stop(); emit stopped(); } int trials() const { return m_trials; } Q_SLOT void setTrials(int trials) { m_trials = trials; } double probability() const { return m_probability; } Q_SLOT void setProbability(double p) { m_probability = p; } }; int main(int argc, char *argv[]) { MonitoringApp app(argc, argv); MonitoringViewModel model; WorkerObject workerObject; Thread workerThread; QWidget w; QGridLayout layout(&w); QTableView view; QLabel timeoutLabel; QSlider timeout(Qt::Horizontal); QGroupBox worker("Worker Thread"); worker.setCheckable(true); worker.setChecked(false); QGridLayout wLayout(&worker); QLabel rangeLabel, probabilityLabel; QSlider range(Qt::Horizontal), probability(Qt::Horizontal); timeoutLabel.setMinimumWidth(50); QObject::connect(&timeout, &QSlider::valueChanged, &timeoutLabel, (void(QLabel::*)(int))&QLabel::setNum); timeout.setMinimum(50); timeout.setMaximum(5000); timeout.setValue(app.timeout()); view.setModel(&model); view.verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); layout.addWidget(&view, 0, 0, 1, 3); layout.addWidget(new QLabel("Timeout"), 1, 0); layout.addWidget(&timeoutLabel, 1, 1); layout.addWidget(&timeout, 1, 2); layout.addWidget(&worker, 2, 0, 1, 3); QObject::connect(&range, &QAbstractSlider::valueChanged, [&](int p){ rangeLabel.setText(QString("Range %1 ms").arg(p)); workerObject.setTrials(p); }); QObject::connect(&probability, &QAbstractSlider::valueChanged, [&](int p){ double prob = p / (double)probability.maximum(); probabilityLabel.setText(QString("Probability %1").arg(prob, 0, 'g', 2)); workerObject.setProbability(prob); }); range.setMaximum(10000); range.setValue(workerObject.trials()); probability.setValue(workerObject.probability() * probability.maximum()); wLayout.addWidget(new QLabel("Sleep Time Binomial Distribution"), 0, 0, 1, 2); wLayout.addWidget(&rangeLabel, 1, 0); wLayout.addWidget(&range, 2, 0); wLayout.addWidget(&probabilityLabel, 1, 1); wLayout.addWidget(&probability, 2, 1); QObject::connect(&workerObject, &WorkerObject::stopped, &workerThread, &Thread::quit); QObject::connect(&worker, &QGroupBox::toggled, [&](bool run) { if (run) { workerThread.start(); QMetaObject::invokeMethod(&workerObject, "start"); } else QMetaObject::invokeMethod(&workerObject, "stop"); }); QObject::connect(&timeout, &QAbstractSlider::valueChanged, &app, &MonitoringApp::setTimeout); workerThread.takeObject(&workerObject); w.show(); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>#ifndef MIMOSA_REF_COUNTABLE_HH # define MIMOSA_REF_COUNTABLE_HH # include <cassert> # include "ref-counted-ptr.hh" namespace mimosa { class RefCountableBase { public: inline RefCountableBase() : ref_count_(0) { } inline RefCountableBase(const RefCountableBase & /*other*/) : ref_count_(0) { } virtual ~RefCountableBase() {} inline RefCountableBase & operator=(const RefCountableBase & /*other*/) { return *this; } inline int addRef() const { auto ret = __sync_add_and_fetch(&ref_count_, 1); assert(ret >= 1); return ret; } inline int releaseRef() const { auto ret = __sync_add_and_fetch(&ref_count_, -1); assert(ret >= 0); return ret; } mutable int ref_count_; }; inline void addRef(const RefCountableBase * obj) { obj->addRef(); } inline void releaseRef(const RefCountableBase * obj) { if (obj->releaseRef() == 0) delete obj; } # define MIMOSA_DEF_PTR(T...) \ typedef RefCountedPtr<T > Ptr; \ typedef RefCountedPtr<const T > ConstPtr template <typename T > class RefCountable : public RefCountableBase { public: MIMOSA_DEF_PTR(T); }; } #endif /* !MIMOSA_REF_COUNTABLE_HH */ <commit_msg>Fixed MIMOSA_DEF_PTR by using ::mimosa::<commit_after>#ifndef MIMOSA_REF_COUNTABLE_HH # define MIMOSA_REF_COUNTABLE_HH # include <cassert> # include "ref-counted-ptr.hh" namespace mimosa { class RefCountableBase { public: inline RefCountableBase() : ref_count_(0) { } inline RefCountableBase(const RefCountableBase & /*other*/) : ref_count_(0) { } virtual ~RefCountableBase() {} inline RefCountableBase & operator=(const RefCountableBase & /*other*/) { return *this; } inline int addRef() const { auto ret = __sync_add_and_fetch(&ref_count_, 1); assert(ret >= 1); return ret; } inline int releaseRef() const { auto ret = __sync_add_and_fetch(&ref_count_, -1); assert(ret >= 0); return ret; } mutable int ref_count_; }; inline void addRef(const RefCountableBase * obj) { obj->addRef(); } inline void releaseRef(const RefCountableBase * obj) { if (obj->releaseRef() == 0) delete obj; } # define MIMOSA_DEF_PTR(T...) \ typedef ::mimosa::RefCountedPtr<T > Ptr; \ typedef ::mimosa::RefCountedPtr<const T > ConstPtr template <typename T > class RefCountable : public ::mimosa::RefCountableBase { public: MIMOSA_DEF_PTR(T); }; } #endif /* !MIMOSA_REF_COUNTABLE_HH */ <|endoftext|>
<commit_before>/****************************************************************************** * root_bind.cpp - bindings for Ogre::Root ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgreRenderWindow.h> #include <OgreWindowEventUtilities.h> #include <OgreConfigFile.h> #include "ogre_manager.h" template<> OgreManager* Ogre::Singleton<OgreManager>::ms_Singleton = 0; void load_ogre_plugin(const char* plugin); void default_engine_options(engine_options* options) { options->renderer_s = "OpenGL"; #ifdef PLATFORM_WIN options->plugin_folder_s = "."; #else options->plugin_folder_s = "/usr/local/lib/OGRE"; #endif options->window_title = "Renderwindow"; options->width = 800; options->height = 600; options->auto_window = 1; options->log_name = "Ogre.log"; } void init_engine(const engine_options options) { new OgreManager(); OgreManager::getSingletonPtr()->set_plugin_folder(options.plugin_folder_s); // suppress console logging Ogre::LogManager * log_man = new Ogre::LogManager(); Ogre::Log * vge_log = log_man->createLog(options.log_name, true, false); Ogre::Root * root = new Ogre::Root("", "", ""); // default const char * renderer = "OpenGL Rendering Subsystem"; const char * render_plugin = "RenderSystem_GL"; if (strstr(options.renderer_s,"Direct") || strstr(options.renderer_s,"D3D")) { renderer = "Direct3D9 Rendering Subsystem"; render_plugin = "RenderSystem_Direct3D9"; } else if (!strstr(options.renderer_s,"GL")) Ogre::LogManager::getSingleton().logMessage( "Can't parse renderer string, using default (OpenGL)"); load_ogre_plugin(render_plugin); Ogre::RenderSystem* rs = root->getRenderSystemByName( Ogre::String(renderer) ); rs->setConfigOption("Full Screen", "No"); rs->setConfigOption("VSync", "No"); //rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit"); rs->setConfigOption("Video Mode", Ogre::StringConverter::toString(options.width) + " x " + Ogre::StringConverter::toString(options.height) + " @ 32-bit"); root->setRenderSystem(rs); load_ogre_plugin("Plugin_OctreeSceneManager"); Ogre::SceneManager * scene_manager = root->createSceneManager(Ogre::ST_GENERIC, "scene-manager"); if (options.auto_window) { OgreManager::getSingletonPtr()->setActiveRenderWindow(root->initialise(true , options.window_title)); } else { root->initialise(false , options.window_title); } } void release_engine() { delete Ogre::Root::getSingletonPtr(); } // Ogre::Root::initialise(bool, std::string const&, std::string const&) RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title) { Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->initialise(auto_create_window, render_window_title); if(auto_create_window) OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } // Ogre::Root::isInitialised() const DLL int root_is_initialised() { if(Ogre::Root::getSingletonPtr()->isInitialised()) return 1; return 0; } // Ogre::Root::Root(std::string const&, std::string const&, std::string const&) RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName) { new OgreManager(); Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName)); return reinterpret_cast<RootHandle>(root); } void save_config() { Ogre::Root::getSingletonPtr()->saveConfig(); } // Ogre::Root::restoreConfig() int restore_config() { if(Ogre::Root::getSingletonPtr()->restoreConfig()) return 1; return 0; } // Ogre::Root::showConfigDialog() int show_config_dialog() { if(Ogre::Root::getSingletonPtr()->showConfigDialog()) return 1; return 0; } // Ogre::Root::loadPlugin(std::string const&) void load_ogre_plugin(const char* plugin) { #if defined( WIN32 ) || defined( _WINDOWS ) Ogre::String pluginString(plugin); #ifdef _DEBUG Ogre::Root::getSingleton().loadPlugin(pluginString + Ogre::String("_d")); #else Ogre::Root::getSingleton().loadPlugin(plugin); #endif #else Ogre::Root::getSingleton().loadPlugin( Ogre::String(OgreManager::getSingletonPtr()->get_plugin_folder()) + "/" + plugin ); #endif } // Ogre::Root::renderOneFrame() int render_one_frame() { if(Ogre::Root::getSingletonPtr()->renderOneFrame()) return 1; return 0; } // Ogre::Root::renderOneFrame(float) int render_one_frame_ex(float time_since_last_frame) { if(Ogre::Root::getSingletonPtr()->renderOneFrame(time_since_last_frame)) return 1; return 0; } void pump_messages() { Ogre::WindowEventUtilities::messagePump(); } static bool do_render = 1; void render_loop() { while (do_render) { // Pump window messages for nice behaviour Ogre::WindowEventUtilities::messagePump(); // Render a frame if(!Ogre::Root::getSingletonPtr()->renderOneFrame()) { do_render = 0; } if (OgreManager::getSingletonPtr()->getActiveRenderWindow()->isClosed()) { do_render = 0; } } } /* Ogre::Root::~Root() Ogre::Root::saveConfig() Ogre::Root::addRenderSystem(Ogre::RenderSystem*) Ogre::Root::getAvailableRenderers() Ogre::Root::getRenderSystemByName(std::string const&) Ogre::Root::setRenderSystem(Ogre::RenderSystem*) Ogre::Root::getRenderSystem() Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*) Ogre::Root::getRemoveRenderQueueStructuresOnClear() const Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool) Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*) Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*) Ogre::Root::getSceneManagerMetaData(std::string const&) const Ogre::Root::getSceneManagerMetaDataIterator() const Ogre::Root::createSceneManager(std::string const&, std::string const&) Ogre::Root::createSceneManager(unsigned short, std::string const&) Ogre::Root::destroySceneManager(Ogre::SceneManager*) Ogre::Root::getSceneManager(std::string const&) const Ogre::Root::hasSceneManager(std::string const&) const Ogre::Root::getSceneManagerIterator() Ogre::Root::getTextureManager() Ogre::Root::getMeshManager() Ogre::Root::getErrorDescription(long) Ogre::Root::addFrameListener(Ogre::FrameListener*) Ogre::Root::removeFrameListener(Ogre::FrameListener*) Ogre::Root::queueEndRendering() Ogre::Root::startRendering() Ogre::Root::shutdown() Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool) Ogre::Root::removeResourceLocation(std::string const&, std::string const&) Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&) Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&) Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*) Ogre::Root::getAutoCreatedWindow() Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*) Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&) Ogre::Root::detachRenderTarget(Ogre::RenderTarget*) Ogre::Root::detachRenderTarget(std::string const&) Ogre::Root::getRenderTarget(std::string const&) Ogre::Root::unloadPlugin(std::string const&) Ogre::Root::installPlugin(Ogre::Plugin*) Ogre::Root::uninstallPlugin(Ogre::Plugin*) Ogre::Root::getInstalledPlugins() const Ogre::Root::getTimer() Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&) Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&) Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&) Ogre::Root::_fireFrameStarted() Ogre::Root::_fireFrameRenderingQueued() Ogre::Root::_fireFrameEnded() Ogre::Root::getNextFrameNumber() const Ogre::Root::_getCurrentSceneManager() const Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*) Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*) Ogre::Root::_updateAllRenderTargets() Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&) Ogre::Root::createRenderQueueInvocationSequence(std::string const&) Ogre::Root::getRenderQueueInvocationSequence(std::string const&) Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&) Ogre::Root::destroyAllRenderQueueInvocationSequences() Ogre::Root::getSingleton() Ogre::Root::getSingletonPtr() Ogre::Root::clearEventTimes() Ogre::Root::setFrameSmoothingPeriod(float) Ogre::Root::getFrameSmoothingPeriod() const Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool) Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*) Ogre::Root::hasMovableObjectFactory(std::string const&) const Ogre::Root::getMovableObjectFactory(std::string const&) Ogre::Root::_allocateNextMovableObjectTypeFlag() Ogre::Root::getMovableObjectFactoryIterator() const Ogre::Root::getDisplayMonitorCount() const Ogre::Root::getWorkQueue() const Ogre::Root::setWorkQueue(Ogre::WorkQueue*) Ogre::Root::setBlendIndicesGpuRedundant(bool) Ogre::Root::isBlendIndicesGpuRedundant() const Ogre::Root::setBlendWeightsGpuRedundant(bool) Ogre::Root::isBlendWeightsGpuRedundant() const */ <commit_msg>make compile with 1.8 and above<commit_after>/****************************************************************************** * root_bind.cpp - bindings for Ogre::Root ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgreRenderWindow.h> #include <OgreWindowEventUtilities.h> #include <OgreConfigFile.h> #include "ogre_manager.h" template<> OgreManager* Ogre::Singleton<OgreManager>::msSingleton = 0; void load_ogre_plugin(const char* plugin); void default_engine_options(engine_options* options) { options->renderer_s = "OpenGL"; #ifdef PLATFORM_WIN options->plugin_folder_s = "."; #else options->plugin_folder_s = "/usr/local/lib/OGRE"; #endif options->window_title = "Renderwindow"; options->width = 800; options->height = 600; options->auto_window = 1; options->log_name = "Ogre.log"; } void init_engine(const engine_options options) { new OgreManager(); OgreManager::getSingletonPtr()->set_plugin_folder(options.plugin_folder_s); // suppress console logging Ogre::LogManager * log_man = new Ogre::LogManager(); Ogre::Log * vge_log = log_man->createLog(options.log_name, true, false); Ogre::Root * root = new Ogre::Root("", "", ""); // default const char * renderer = "OpenGL Rendering Subsystem"; const char * render_plugin = "RenderSystem_GL"; if (strstr(options.renderer_s,"Direct") || strstr(options.renderer_s,"D3D")) { renderer = "Direct3D9 Rendering Subsystem"; render_plugin = "RenderSystem_Direct3D9"; } else if (!strstr(options.renderer_s,"GL")) Ogre::LogManager::getSingleton().logMessage( "Can't parse renderer string, using default (OpenGL)"); load_ogre_plugin(render_plugin); Ogre::RenderSystem* rs = root->getRenderSystemByName( Ogre::String(renderer) ); rs->setConfigOption("Full Screen", "No"); rs->setConfigOption("VSync", "No"); //rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit"); rs->setConfigOption("Video Mode", Ogre::StringConverter::toString(options.width) + " x " + Ogre::StringConverter::toString(options.height) + " @ 32-bit"); root->setRenderSystem(rs); load_ogre_plugin("Plugin_OctreeSceneManager"); Ogre::SceneManager * scene_manager = root->createSceneManager(Ogre::ST_GENERIC, "scene-manager"); if (options.auto_window) { OgreManager::getSingletonPtr()->setActiveRenderWindow(root->initialise(true , options.window_title)); } else { root->initialise(false , options.window_title); } } void release_engine() { delete Ogre::Root::getSingletonPtr(); } // Ogre::Root::initialise(bool, std::string const&, std::string const&) RenderWindowHandle root_initialise(int auto_create_window, const char* render_window_title) { Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->initialise(auto_create_window, render_window_title); if(auto_create_window) OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } // Ogre::Root::isInitialised() const DLL int root_is_initialised() { if(Ogre::Root::getSingletonPtr()->isInitialised()) return 1; return 0; } // Ogre::Root::Root(std::string const&, std::string const&, std::string const&) RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName) { new OgreManager(); Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName)); return reinterpret_cast<RootHandle>(root); } void save_config() { Ogre::Root::getSingletonPtr()->saveConfig(); } // Ogre::Root::restoreConfig() int restore_config() { if(Ogre::Root::getSingletonPtr()->restoreConfig()) return 1; return 0; } // Ogre::Root::showConfigDialog() int show_config_dialog() { if(Ogre::Root::getSingletonPtr()->showConfigDialog()) return 1; return 0; } // Ogre::Root::loadPlugin(std::string const&) void load_ogre_plugin(const char* plugin) { #if defined( WIN32 ) || defined( _WINDOWS ) Ogre::String pluginString(plugin); #ifdef _DEBUG Ogre::Root::getSingleton().loadPlugin(pluginString + Ogre::String("_d")); #else Ogre::Root::getSingleton().loadPlugin(plugin); #endif #else Ogre::Root::getSingleton().loadPlugin( Ogre::String(OgreManager::getSingletonPtr()->get_plugin_folder()) + "/" + plugin ); #endif } // Ogre::Root::renderOneFrame() int render_one_frame() { if(Ogre::Root::getSingletonPtr()->renderOneFrame()) return 1; return 0; } // Ogre::Root::renderOneFrame(float) int render_one_frame_ex(float time_since_last_frame) { if(Ogre::Root::getSingletonPtr()->renderOneFrame(time_since_last_frame)) return 1; return 0; } void pump_messages() { Ogre::WindowEventUtilities::messagePump(); } static bool do_render = 1; void render_loop() { while (do_render) { // Pump window messages for nice behaviour Ogre::WindowEventUtilities::messagePump(); // Render a frame if(!Ogre::Root::getSingletonPtr()->renderOneFrame()) { do_render = 0; } if (OgreManager::getSingletonPtr()->getActiveRenderWindow()->isClosed()) { do_render = 0; } } } /* Ogre::Root::~Root() Ogre::Root::saveConfig() Ogre::Root::addRenderSystem(Ogre::RenderSystem*) Ogre::Root::getAvailableRenderers() Ogre::Root::getRenderSystemByName(std::string const&) Ogre::Root::setRenderSystem(Ogre::RenderSystem*) Ogre::Root::getRenderSystem() Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*) Ogre::Root::getRemoveRenderQueueStructuresOnClear() const Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool) Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*) Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*) Ogre::Root::getSceneManagerMetaData(std::string const&) const Ogre::Root::getSceneManagerMetaDataIterator() const Ogre::Root::createSceneManager(std::string const&, std::string const&) Ogre::Root::createSceneManager(unsigned short, std::string const&) Ogre::Root::destroySceneManager(Ogre::SceneManager*) Ogre::Root::getSceneManager(std::string const&) const Ogre::Root::hasSceneManager(std::string const&) const Ogre::Root::getSceneManagerIterator() Ogre::Root::getTextureManager() Ogre::Root::getMeshManager() Ogre::Root::getErrorDescription(long) Ogre::Root::addFrameListener(Ogre::FrameListener*) Ogre::Root::removeFrameListener(Ogre::FrameListener*) Ogre::Root::queueEndRendering() Ogre::Root::startRendering() Ogre::Root::shutdown() Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool) Ogre::Root::removeResourceLocation(std::string const&, std::string const&) Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&) Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&) Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*) Ogre::Root::getAutoCreatedWindow() Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*) Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&) Ogre::Root::detachRenderTarget(Ogre::RenderTarget*) Ogre::Root::detachRenderTarget(std::string const&) Ogre::Root::getRenderTarget(std::string const&) Ogre::Root::unloadPlugin(std::string const&) Ogre::Root::installPlugin(Ogre::Plugin*) Ogre::Root::uninstallPlugin(Ogre::Plugin*) Ogre::Root::getInstalledPlugins() const Ogre::Root::getTimer() Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&) Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&) Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&) Ogre::Root::_fireFrameStarted() Ogre::Root::_fireFrameRenderingQueued() Ogre::Root::_fireFrameEnded() Ogre::Root::getNextFrameNumber() const Ogre::Root::_getCurrentSceneManager() const Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*) Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*) Ogre::Root::_updateAllRenderTargets() Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&) Ogre::Root::createRenderQueueInvocationSequence(std::string const&) Ogre::Root::getRenderQueueInvocationSequence(std::string const&) Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&) Ogre::Root::destroyAllRenderQueueInvocationSequences() Ogre::Root::getSingleton() Ogre::Root::getSingletonPtr() Ogre::Root::clearEventTimes() Ogre::Root::setFrameSmoothingPeriod(float) Ogre::Root::getFrameSmoothingPeriod() const Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool) Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*) Ogre::Root::hasMovableObjectFactory(std::string const&) const Ogre::Root::getMovableObjectFactory(std::string const&) Ogre::Root::_allocateNextMovableObjectTypeFlag() Ogre::Root::getMovableObjectFactoryIterator() const Ogre::Root::getDisplayMonitorCount() const Ogre::Root::getWorkQueue() const Ogre::Root::setWorkQueue(Ogre::WorkQueue*) Ogre::Root::setBlendIndicesGpuRedundant(bool) Ogre::Root::isBlendIndicesGpuRedundant() const Ogre::Root::setBlendWeightsGpuRedundant(bool) Ogre::Root::isBlendWeightsGpuRedundant() const */ <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/cpp_examples/example7/example7.cpp,v $ // $Revision: 1.2 $ // $Name: $ // $Author: gauges $ // $Date: 2009/08/31 18:36:12 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. /** * This is an example on how to create user defined kinetic functions with the COPASI API */ #include <iostream> #include <vector> #include <string> #include <set> #define COPASI_MAIN #include "copasi/copasi.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/model/CModel.h" #include "copasi/model/CCompartment.h" #include "copasi/model/CMetab.h" #include "copasi/model/CReaction.h" #include "copasi/model/CChemEq.h" #include "copasi/model/CModelValue.h" #include "copasi/function/CFunctionDB.h" #include "copasi/function/CFunction.h" #include "copasi/function/CEvaluationTree.h" int main() { // initialize the backend library // since we are not interested in the arguments // that are passed to main, we pass 0 and NULL to // init CCopasiRootContainer::init(0, NULL); assert(CCopasiRootContainer::getRoot() != NULL); // create a new datamodel CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); assert(CCopasiRootContainer::getDatamodelList()->size() == 1); // get the model from the datamodel CModel* pModel = pDataModel->getModel(); assert(pModel != NULL); // set the units for the model // we want seconds as the time unit // microliter as the volume units // and nanomole as the substance units pModel->setTimeUnit(CModel::s); pModel->setVolumeUnit(CModel::microl); pModel->setQuantityUnit(CModel::nMol); // we have to keep a set of all the initial values that are changed during // the model building process // They are needed after the model has been built to make sure all initial // values are set to the correct initial value std::set<const CCopasiObject*> changedObjects; // create a compartment with the name cell and an initial volume of 5.0 // microliter CCompartment* pCompartment = pModel->createCompartment("cell", 5.0); const CCopasiObject* pObject = pCompartment->getObject(CCopasiObjectName("Reference=InitialVolume")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pCompartment != NULL); assert(pModel->getCompartments().size() == 1); // create a new metabolite with the name S and an inital // concentration of 10 nanomol // the metabolite belongs to the compartment we created and is is to be // fixed CMetab* pS = pModel->createMetabolite("S", pCompartment->getObjectName(), 10.0, CMetab::FIXED); pObject = pS->getObject(CCopasiObjectName("Reference=InitialConcentration")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pCompartment != NULL); assert(pS != NULL); assert(pModel->getMetabolites().size() == 1); // create a second metabolite called P with an initial // concentration of 0. This metabolite is to be changed by reactions CMetab* pP = pModel->createMetabolite("P", pCompartment->getObjectName(), 0.0, CMetab::REACTIONS); assert(pP != NULL); pObject = pP->getObject(CCopasiObjectName("Reference=InitialConcentration")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pModel->getMetabolites().size() == 2); // now we create a reaction CReaction* pReaction = pModel->createReaction("reaction"); assert(pReaction != NULL); assert(pModel->getReactions().size() == 1); // reaction converts S to P // we can set these on the chemical equation of the reaction CChemEq* pChemEq = &pReaction->getChemEq(); // glucose is a substrate with stoichiometry 1 pChemEq->addMetabolite(pS->getKey(), 1.0, CChemEq::SUBSTRATE); // glucose-6-phosphate is a product with stoichiometry 1 pChemEq->addMetabolite(pP->getKey(), 1.0, CChemEq::PRODUCT); assert(pChemEq->getSubstrates().size() == 1); assert(pChemEq->getProducts().size() == 1); // this reaction is to be irreversible pReaction->setReversible(false); assert(pReaction->isReversible() == false); CModelValue* pMV = pModel->createModelValue("K", 42.0); // set the status to FIXED pMV->setStatus(CModelValue::FIXED); assert(pMV != NULL); pObject = pMV->getObject(CCopasiObjectName("Reference=InitialValue")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pModel->getModelValues().size() == 1); // now we ned to set a kinetic law on the reaction // for this we create a user defined function CFunctionDB* pFunDB = CCopasiRootContainer::getFunctionList(); assert(pFunDB != NULL); CKinFunction* pFunction = new CKinFunction("My Rate Law"); pFunDB->add(pFunction, true); CFunction* pRateLaw = dynamic_cast<CFunction*>(pFunDB->findFunction("My Rate Law")); assert(pRateLaw != NULL); // now we create the formula for the function and set it on the function std::string formula = "(1-0.4/(EXPONENTIALE^(temp-37)))*0.00001448471257*1.4^(temp-37)*substrate"; bool result = pFunction->setInfix(formula); assert(result == true); // make the function irreversible pFunction->setReversible(TriFalse); // the formula string should have been parsed now // and COPASI should have determined that the formula string contained 2 parameters (temp and substrate) CFunctionParameters& variables = pFunction->getVariables(); // per default the usage of those parameters will be set to VARIABLE unsigned C_INT32 index = pFunction->getVariableIndex("temp"); assert(index != C_INVALID_INDEX); CFunctionParameter* pParam = variables[index]; assert(pParam->getUsage() == CFunctionParameter::VARIABLE); // This is correct for temp, but substrate should get the usage SUBSTRATE in order // for us to use the function with the reaction created above // So we need to set the usage for "substrate" manually index = pFunction->getVariableIndex("substrate"); assert(index != C_INVALID_INDEX); pParam = variables[index]; pParam->setUsage(CFunctionParameter::SUBSTRATE); // set the rate law for the reaction pReaction->setFunction(pRateLaw); assert(pReaction->getFunction() != NULL); // COPASI also needs to know what object it has to assocuiate with the individual function parameters // In our case we need to tell COPASI that substrate is to be replaced by the substrate of the reaction // and temp is to be replaced by the global parameter K pReaction->setParameterMapping("substrate", pS->getKey()); pReaction->setParameterMapping("temp", pMV->getKey()); // finally compile the model // compile needs to be done before updating all initial values for // the model with the refresh sequence pModel->compileIfNecessary(NULL); // now that we are done building the model, we have to make sure all // initial values are updated according to their dependencies std::vector<Refresh*> refreshes = pModel->buildInitialRefreshSequence(changedObjects); std::vector<Refresh*>::iterator it2 = refreshes.begin(), endit2 = refreshes.end(); while (it2 != endit2) { // call each refresh (**it2)(); ++it2; } // save the model to a COPASI file // we save to a file named example1.cps, we don't want a progress report // and we want to overwrite any existing file with the same name // Default tasks are automatically generated and will always appear in cps // file unless they are explicitley deleted before saving. pDataModel->saveModel("example7.cps", NULL, true); // export the model to an SBML file // we save to a file named example1.xml, we want to overwrite any // existing file with the same name and we want SBML L2V3 pDataModel->exportSBML("example7.xml", true, 2, 3); // destroy the root container once we are done CCopasiRootContainer::destroy(); } <commit_msg>Small fixes to the comments and to the code.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/cpp_examples/example7/example7.cpp,v $ // $Revision: 1.3 $ // $Name: $ // $Author: gauges $ // $Date: 2009/08/31 19:34:31 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. /** * This is an example on how to create user defined kinetic functions with the COPASI API */ #include <iostream> #include <vector> #include <string> #include <set> #define COPASI_MAIN #include "copasi/copasi.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/model/CModel.h" #include "copasi/model/CCompartment.h" #include "copasi/model/CMetab.h" #include "copasi/model/CReaction.h" #include "copasi/model/CChemEq.h" #include "copasi/model/CModelValue.h" #include "copasi/function/CFunctionDB.h" #include "copasi/function/CFunction.h" #include "copasi/function/CEvaluationTree.h" int main() { // initialize the backend library // since we are not interested in the arguments // that are passed to main, we pass 0 and NULL to // init CCopasiRootContainer::init(0, NULL); assert(CCopasiRootContainer::getRoot() != NULL); // create a new datamodel CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); assert(CCopasiRootContainer::getDatamodelList()->size() == 1); // get the model from the datamodel CModel* pModel = pDataModel->getModel(); assert(pModel != NULL); // set the units for the model // we want seconds as the time unit // microliter as the volume units // and nanomole as the substance units pModel->setTimeUnit(CModel::s); pModel->setVolumeUnit(CModel::microl); pModel->setQuantityUnit(CModel::nMol); // we have to keep a set of all the initial values that are changed during // the model building process // They are needed after the model has been built to make sure all initial // values are set to the correct initial value std::set<const CCopasiObject*> changedObjects; // create a compartment with the name cell and an initial volume of 5.0 // microliter CCompartment* pCompartment = pModel->createCompartment("cell", 5.0); const CCopasiObject* pObject = pCompartment->getObject(CCopasiObjectName("Reference=InitialVolume")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pCompartment != NULL); assert(pModel->getCompartments().size() == 1); // create a new metabolite with the name S and an inital // concentration of 10 nanomol // the metabolite belongs to the compartment we created and is is to be // fixed CMetab* pS = pModel->createMetabolite("S", pCompartment->getObjectName(), 10.0, CMetab::FIXED); pObject = pS->getObject(CCopasiObjectName("Reference=InitialConcentration")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pCompartment != NULL); assert(pS != NULL); assert(pModel->getMetabolites().size() == 1); // create a second metabolite called P with an initial // concentration of 0. This metabolite is to be changed by reactions CMetab* pP = pModel->createMetabolite("P", pCompartment->getObjectName(), 0.0, CMetab::REACTIONS); assert(pP != NULL); pObject = pP->getObject(CCopasiObjectName("Reference=InitialConcentration")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pModel->getMetabolites().size() == 2); // now we create a reaction CReaction* pReaction = pModel->createReaction("reaction"); assert(pReaction != NULL); assert(pModel->getReactions().size() == 1); // reaction converts S to P // we can set these on the chemical equation of the reaction CChemEq* pChemEq = &pReaction->getChemEq(); // S is a substrate with stoichiometry 1 pChemEq->addMetabolite(pS->getKey(), 1.0, CChemEq::SUBSTRATE); // P is a product with stoichiometry 1 pChemEq->addMetabolite(pP->getKey(), 1.0, CChemEq::PRODUCT); assert(pChemEq->getSubstrates().size() == 1); assert(pChemEq->getProducts().size() == 1); // this reaction is to be irreversible pReaction->setReversible(false); assert(pReaction->isReversible() == false); CModelValue* pMV = pModel->createModelValue("K", 42.0); // set the status to FIXED pMV->setStatus(CModelValue::FIXED); assert(pMV != NULL); pObject = pMV->getObject(CCopasiObjectName("Reference=InitialValue")); assert(pObject != NULL); changedObjects.insert(pObject); assert(pModel->getModelValues().size() == 1); // now we ned to set a kinetic law on the reaction // for this we create a user defined function CFunctionDB* pFunDB = CCopasiRootContainer::getFunctionList(); assert(pFunDB != NULL); CKinFunction* pFunction = new CKinFunction("My Rate Law"); pFunDB->add(pFunction, true); CFunction* pRateLaw = dynamic_cast<CFunction*>(pFunDB->findFunction("My Rate Law")); assert(pRateLaw != NULL); // now we create the formula for the function and set it on the function std::string formula = "(1-0.4/(EXPONENTIALE^(temp-37)))*0.00001448471257*1.4^(temp-37)*substrate"; bool result = pFunction->setInfix(formula); assert(result == true); // make the function irreversible pFunction->setReversible(TriFalse); // the formula string should have been parsed now // and COPASI should have determined that the formula string contained 2 parameters (temp and substrate) CFunctionParameters& variables = pFunction->getVariables(); // per default the usage of those parameters will be set to VARIABLE unsigned C_INT32 index = pFunction->getVariableIndex("temp"); assert(index != C_INVALID_INDEX); CFunctionParameter* pParam = variables[index]; assert(pParam->getUsage() == CFunctionParameter::VARIABLE); // This is correct for temp, but substrate should get the usage SUBSTRATE in order // for us to use the function with the reaction created above // So we need to set the usage for "substrate" manually index = pFunction->getVariableIndex("substrate"); assert(index != C_INVALID_INDEX); pParam = variables[index]; pParam->setUsage(CFunctionParameter::SUBSTRATE); // set the rate law for the reaction pReaction->setFunction(pFunction); assert(pReaction->getFunction() != NULL); // COPASI also needs to know what object it has to assocuiate with the individual function parameters // In our case we need to tell COPASI that substrate is to be replaced by the substrate of the reaction // and temp is to be replaced by the global parameter K pReaction->setParameterMapping("substrate", pS->getKey()); pReaction->setParameterMapping("temp", pMV->getKey()); // finally compile the model // compile needs to be done before updating all initial values for // the model with the refresh sequence pModel->compileIfNecessary(NULL); // now that we are done building the model, we have to make sure all // initial values are updated according to their dependencies std::vector<Refresh*> refreshes = pModel->buildInitialRefreshSequence(changedObjects); std::vector<Refresh*>::iterator it2 = refreshes.begin(), endit2 = refreshes.end(); while (it2 != endit2) { // call each refresh (**it2)(); ++it2; } // save the model to a COPASI file // we save to a file named example1.cps, we don't want a progress report // and we want to overwrite any existing file with the same name // Default tasks are automatically generated and will always appear in cps // file unless they are explicitley deleted before saving. pDataModel->saveModel("example7.cps", NULL, true); // export the model to an SBML file // we save to a file named example1.xml, we want to overwrite any // existing file with the same name and we want SBML L2V3 pDataModel->exportSBML("example7.xml", true, 2, 3); // destroy the root container once we are done CCopasiRootContainer::destroy(); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgrePlatform.h" #include "OgreStableHeaders.h" #include "OgrePrerequisites.h" #include "OgreMemoryTracker.h" #include "OgreString.h" namespace Ogre { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 # define Ogre_OutputCString(str) ::OutputDebugStringA(str) # define Ogre_OutputWString(str) ::OutputDebugStringW(str) #else # define Ogre_OutputCString(str) std::err << str # define Ogre_OutputWString(str) std::err << str #endif #if OGRE_MEMORY_TRACKER //-------------------------------------------------------------------------- MemoryTracker& MemoryTracker::get() { static MemoryTracker tracker; return tracker; } //-------------------------------------------------------------------------- void MemoryTracker::_recordAlloc(void* ptr, size_t sz, unsigned int pool, const char* file, size_t ln, const char* func) { OGRE_LOCK_AUTO_MUTEX assert(mAllocations.find(ptr) == mAllocations.end() && "Double allocation with same address - " "this probably means you have a mismatched allocation / deallocation style, " "check if you're are using OGRE_ALLOC_T / OGRE_FREE and OGRE_NEW_T / OGRE_DELETE_T consistently"); mAllocations[ptr] = Alloc(sz, pool, file, ln, func); if(pool >= mAllocationsByPool.size()) mAllocationsByPool.resize(pool+1, 0); mAllocationsByPool[pool] += sz; mTotalAllocations += sz; } //-------------------------------------------------------------------------- void MemoryTracker::_recordDealloc(void* ptr) { // deal cleanly with null pointers if (!ptr) return; OGRE_LOCK_AUTO_MUTEX AllocationMap::iterator i = mAllocations.find(ptr); assert(i != mAllocations.end() && "Unable to locate allocation unit - " "this probably means you have a mismatched allocation / deallocation style, " "check if you're are using OGRE_ALLOC_T / OGRE_FREE and OGRE_NEW_T / OGRE_DELETE_T consistently"); // update category stats mAllocationsByPool[i->second.pool] -= i->second.bytes; // global stats mTotalAllocations -= i->second.bytes; mAllocations.erase(i); } //-------------------------------------------------------------------------- size_t MemoryTracker::getTotalMemoryAllocated() const { return mTotalAllocations; } //-------------------------------------------------------------------------- size_t MemoryTracker::getMemoryAllocatedForPool(unsigned int pool) const { return mAllocationsByPool[pool]; } //-------------------------------------------------------------------------- void MemoryTracker::reportLeaks() { StringUtil::StrStreamType os; if (mAllocations.empty()) { os << "Ogre Memory: No memory leaks" << std::endl; } else { os << "Ogre Memory: Detected memory leaks !!! " << std::endl; os << "Ogre Memory: (" << mAllocations.size() << ") Allocation(s) with total " << mTotalAllocations << " bytes." << std::endl; os << "Ogre Memory: Dumping allocations -> " << std::endl; for (AllocationMap::const_iterator i = mAllocations.begin(); i != mAllocations.end(); ++i) { const Alloc& alloc = i->second; if (!alloc.filename.empty()) os << alloc.filename; else os << "(unknown source):"; os << "(" << alloc.line << ") : {" << alloc.bytes << " bytes}" << " function: " << alloc.function << std::endl; } os << std::endl; } if (mDumpToStdOut) std::cout << os.str(); std::cout << os.str(); std::ofstream of; of.open(mLeakFileName.c_str()); of << os.str(); of.close(); Ogre_OutputCString(os.str().c_str()); } #endif // OGRE_DEBUG_MODE } <commit_msg>Fix use of memory tracker on non-Windows platforms (std::cerr, not std::err)<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgrePlatform.h" #include "OgreStableHeaders.h" #include "OgrePrerequisites.h" #include "OgreMemoryTracker.h" #include "OgreString.h" namespace Ogre { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 # define Ogre_OutputCString(str) ::OutputDebugStringA(str) # define Ogre_OutputWString(str) ::OutputDebugStringW(str) #else # define Ogre_OutputCString(str) std::cerr << str # define Ogre_OutputWString(str) std::cerr << str #endif #if OGRE_MEMORY_TRACKER //-------------------------------------------------------------------------- MemoryTracker& MemoryTracker::get() { static MemoryTracker tracker; return tracker; } //-------------------------------------------------------------------------- void MemoryTracker::_recordAlloc(void* ptr, size_t sz, unsigned int pool, const char* file, size_t ln, const char* func) { OGRE_LOCK_AUTO_MUTEX assert(mAllocations.find(ptr) == mAllocations.end() && "Double allocation with same address - " "this probably means you have a mismatched allocation / deallocation style, " "check if you're are using OGRE_ALLOC_T / OGRE_FREE and OGRE_NEW_T / OGRE_DELETE_T consistently"); mAllocations[ptr] = Alloc(sz, pool, file, ln, func); if(pool >= mAllocationsByPool.size()) mAllocationsByPool.resize(pool+1, 0); mAllocationsByPool[pool] += sz; mTotalAllocations += sz; } //-------------------------------------------------------------------------- void MemoryTracker::_recordDealloc(void* ptr) { // deal cleanly with null pointers if (!ptr) return; OGRE_LOCK_AUTO_MUTEX AllocationMap::iterator i = mAllocations.find(ptr); assert(i != mAllocations.end() && "Unable to locate allocation unit - " "this probably means you have a mismatched allocation / deallocation style, " "check if you're are using OGRE_ALLOC_T / OGRE_FREE and OGRE_NEW_T / OGRE_DELETE_T consistently"); // update category stats mAllocationsByPool[i->second.pool] -= i->second.bytes; // global stats mTotalAllocations -= i->second.bytes; mAllocations.erase(i); } //-------------------------------------------------------------------------- size_t MemoryTracker::getTotalMemoryAllocated() const { return mTotalAllocations; } //-------------------------------------------------------------------------- size_t MemoryTracker::getMemoryAllocatedForPool(unsigned int pool) const { return mAllocationsByPool[pool]; } //-------------------------------------------------------------------------- void MemoryTracker::reportLeaks() { StringUtil::StrStreamType os; if (mAllocations.empty()) { os << "Ogre Memory: No memory leaks" << std::endl; } else { os << "Ogre Memory: Detected memory leaks !!! " << std::endl; os << "Ogre Memory: (" << mAllocations.size() << ") Allocation(s) with total " << mTotalAllocations << " bytes." << std::endl; os << "Ogre Memory: Dumping allocations -> " << std::endl; for (AllocationMap::const_iterator i = mAllocations.begin(); i != mAllocations.end(); ++i) { const Alloc& alloc = i->second; if (!alloc.filename.empty()) os << alloc.filename; else os << "(unknown source):"; os << "(" << alloc.line << ") : {" << alloc.bytes << " bytes}" << " function: " << alloc.function << std::endl; } os << std::endl; } if (mDumpToStdOut) std::cout << os.str(); std::cout << os.str(); std::ofstream of; of.open(mLeakFileName.c_str()); of << os.str(); of.close(); Ogre_OutputCString(os.str().c_str()); } #endif // OGRE_DEBUG_MODE } <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <string> #include <utils.hpp> #include <Observation.hpp> #ifndef BEAM_FORMER_HPP #define BEAM_FORMER_HPP namespace RadioAstronomy { // Sequential beam forming algorithm template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights); // OpenCL beam forming algorithm std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation); // Implementations template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights) { for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { T beamP0_r = 0; T beamP0_i = 0; T beamP1_r = 0; T beamP1_i = 0; for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) { T * samplePointer = &(samples.data()[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]); float * weightPointer = &(weights.data()[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]); beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]); beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]); beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]); beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]); } beamP0_r /= observation.getNrStations(); beamP0_i /= observation.getNrStations(); beamP1_r /= observation.getNrStations(); beamP1_i /= observation.getNrStations(); output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i; } } } } std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __global const float2 * restrict const weights) {\n" "const unsigned int channel = get_group_id(2);\n" "const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n" "<%DEF_SAMPLES%>" "<%DEF_SUMS%>" + dataType + "4 sample = (" + dataType + "4)(0);\n"; if ( local ) { *code += "__local float2 localWeights[" + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + "];\n" "__local float localSamples[" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 4) + "];\n"; } *code += "float2 weight = (float2)(0);\n" "\n" "for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n"; if ( local ) { *code += "unsigned int itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "unsigned int itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "while ( itemLocal < " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") {\n" "localWeights[itemLocal] = weights[itemGlobal];\n" "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "}\n" "itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "while ( itemLocal < " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") {\n" "sample = samples[itemGlobal];\n" "localSamples[itemLocal] = sample.x;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + itemLocal] = sample.y;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + itemLocal] = sample.z;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + itemLocal] = sample.w;\n" "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n"; } *code += "<%LOAD_COMPUTE%>" "}\n" "<%AVERAGE%>" "<%STORE%>" "}\n"; std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n"; std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n"; std::string loadComputeTemplate; if ( local ) { loadComputeTemplate += "sample.x = localSamples[get_local_id(0) + <%OFFSET%>];\n" "sample.y = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + get_local_id(0) + <%OFFSET%>];\n" "sample.z = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + get_local_id(0) + <%OFFSET%>];\n" "sample.w = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + get_local_id(0) + <%OFFSET%>];\n"; } else { loadComputeTemplate += "sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n"; } loadComputeTemplate += "<%SUMS%>"; std::string sumsTemplate; if ( local ) { sumsTemplate += "weight = localWeights[(get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ") + <%BNUM%>];\n"; } else { sumsTemplate += "weight = weights[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + beam + <%BNUM%>];\n"; } sumsTemplate += "beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n" "beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n" "beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n" "beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n"; std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n"; std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n"; // End kernel's template std::string * defSamples_s = new std::string(); std::string * defSums_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * average_s = new std::string(); std::string * store_s = new std::string(); for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) { std::string sample_s = isa::utils::toString(sample); std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock); std::string * sums_s = new std::string(); std::string * temp_s = 0; temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s); temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true); defSamples_s->append(*temp_s); delete temp_s; for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) { std::string beam_s = isa::utils::toString(beam); std::string * temp_s = 0; temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s); defSums_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s); sums_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s); average_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s); store_s->append(*temp_s); delete temp_s; } defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true); temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s); temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true); temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true); temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true); loadCompute_s->append(*temp_s); delete temp_s; average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true); store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true); } code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true); code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true); code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); return code; } } // RadioAstronomy #endif // BEAM_FORMER_HPP <commit_msg>Using constant instead of local memory for the weights.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <string> #include <utils.hpp> #include <Observation.hpp> #ifndef BEAM_FORMER_HPP #define BEAM_FORMER_HPP namespace RadioAstronomy { // Sequential beam forming algorithm template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights); // OpenCL beam forming algorithm std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation); // Implementations template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights) { for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { T beamP0_r = 0; T beamP0_i = 0; T beamP1_r = 0; T beamP1_i = 0; for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) { T * samplePointer = &(samples.data()[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]); float * weightPointer = &(weights.data()[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]); beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]); beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]); beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]); beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]); } beamP0_r /= observation.getNrStations(); beamP0_i /= observation.getNrStations(); beamP1_r /= observation.getNrStations(); beamP1_i /= observation.getNrStations(); output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r; output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i; } } } } std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __constant const float2 * restrict const weights) {\n" "const unsigned int channel = get_group_id(2);\n" "const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n" "<%DEF_SAMPLES%>" "<%DEF_SUMS%>" + dataType + "4 sample = (" + dataType + "4)(0);\n"; if ( local ) { *code += "__local float localSamples[" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 4) + "];\n"; } *code += "float2 weight = (float2)(0);\n" "\n" "for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n"; if ( local ) { *code += "itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n" "while ( itemLocal < " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") {\n" "sample = samples[itemGlobal];\n" "localSamples[itemLocal] = sample.x;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + itemLocal] = sample.y;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + itemLocal] = sample.z;\n" "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + itemLocal] = sample.w;\n" "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n"; } *code += "<%LOAD_COMPUTE%>" "}\n" "<%AVERAGE%>" "<%STORE%>" "}\n"; std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n"; std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n"; std::string loadComputeTemplate; if ( local ) { loadComputeTemplate += "sample.x = localSamples[get_local_id(0) + <%OFFSET%>];\n" "sample.y = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + get_local_id(0) + <%OFFSET%>];\n" "sample.z = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + get_local_id(0) + <%OFFSET%>];\n" "sample.w = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + get_local_id(0) + <%OFFSET%>];\n"; } else { loadComputeTemplate += "sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n"; } loadComputeTemplate += "<%SUMS%>"; std::string sumsTemplate = "weight = weights[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + beam + <%BNUM%>];\n" "beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n" "beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n" "beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n" "beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n"; std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n"; std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n"; // End kernel's template std::string * defSamples_s = new std::string(); std::string * defSums_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * average_s = new std::string(); std::string * store_s = new std::string(); for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) { std::string sample_s = isa::utils::toString(sample); std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock); std::string * sums_s = new std::string(); std::string * temp_s = 0; temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s); temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true); defSamples_s->append(*temp_s); delete temp_s; for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) { std::string beam_s = isa::utils::toString(beam); std::string * temp_s = 0; temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s); defSums_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s); sums_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s); average_s->append(*temp_s); delete temp_s; temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s); store_s->append(*temp_s); delete temp_s; } defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true); temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s); temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true); temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true); temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true); loadCompute_s->append(*temp_s); delete temp_s; average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true); store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true); } code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true); code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true); code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); return code; } } // RadioAstronomy #endif // BEAM_FORMER_HPP <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_BUILTINS_H #define K3_RUNTIME_BUILTINS_H #ifdef CACHEPROFILE #include <cpucounters.h> #endif #ifdef MEMPROFILE #include "gperftools/heap-profiler.h" #endif #ifdef JEMALLOC #include "jemalloc/jemalloc.h" #endif #include <ctime> #include <chrono> #include <climits> #include <fstream> #include <sstream> #include <string> #include <climits> #include <functional> #include "re2/re2.h" #include "BaseTypes.hpp" #include "BaseString.hpp" #include "Common.hpp" #include "dataspace/Dataspace.hpp" // Hashing: namespace boost { template<> struct hash<boost::asio::ip::address> { size_t operator()(boost::asio::ip::address const& v) const { if (v.is_v4()) { return v.to_v4().to_ulong(); } if (v.is_v6()) { auto const& range = v.to_v6().to_bytes(); return hash_range(range.begin(), range.end()); } if (v.is_unspecified()) { return 0x4751301174351161ul; } return hash_value(v.to_string()); } }; } // boost namespace K3 { template <class C1, class C, class F> void read_records(C1& paths, C& container, F read_record) { for (auto rec : paths) { std::ifstream in; in.open(rec.path); std::string tmp_buffer; while (!in.eof()) { container.insert(read_record(in, tmp_buffer)); in >> std::ws; } } return; } class __pcm_context { #ifdef CACHEPROFILE protected: PCM *instance; std::shared_ptr<SystemCounterState> initial_state; #endif public: __pcm_context(); ~__pcm_context(); unit_t cacheProfilerStart(unit_t); unit_t cacheProfilerStop(unit_t); }; class __tcmalloc_context { public: unit_t heapProfilerStart(const string_impl&); unit_t heapProfilerStop(unit_t); }; class __jemalloc_context { public: unit_t jemallocStart(unit_t); unit_t jemallocStop(unit_t); }; template <class C1, class C, class F> void read_records_with_resize(int size, C1& paths, C& container, F read_record) { if (size == 0) { return read_records(paths, container, read_record); } else { container.getContainer().resize(size); } int i = 0; for (auto rec : paths) { std::ifstream in; in.open(rec.path); std::string tmp_buffer; while (!in.eof()) { if (i >= container.size(unit_t {}) ) { throw std::runtime_error("Cannot read records, container size is too small"); } container.getContainer()[i++] = read_record(in, tmp_buffer); in >> std::ws; } } return; } // Standard context for common builtins that use a handle to the engine (via inheritance) class __standard_context : public __k3_context { public: __standard_context(Engine&); unit_t openBuiltin(string_impl ch_id, string_impl builtin_ch_id, string_impl fmt); unit_t openFile(string_impl ch_id, string_impl path, string_impl fmt, string_impl mode); unit_t openSocket(string_impl ch_id, Address a, string_impl fmt, string_impl mode); bool hasRead(string_impl ch_id); template<typename T> T doRead(string_impl ch_id); template<typename T> Collection<R_elem<T>> doReadBlock(string_impl ch_id, int block_size); bool hasWrite(string_impl ch_id); template<typename T> unit_t doWrite(string_impl ch_id, T& val); unit_t close(string_impl chan_id); int random(int n); double randomFraction(unit_t); template <class T> int hash(const T& x) { // We implement hash_value for all of our types. // for ordered containers, so we may as well delegate to that. return static_cast<int>(hash_value(x)); } template <class T> string_impl toJson(const T& in) { return K3::serialization::json::encode<T>(in); } template <class T> T range(int i) { T result; for (int j = 0; j < i; j++) { result.insert(j); } return result; } int truncate(double n) { return (int)n; } double real_of_int(int n) { return (double)n; } int get_max_int(unit_t) { return INT_MAX; } unit_t print(string_impl message); // TODO, implement, sharing code with prettify() template <class T> string_impl show(T t) { return string_impl("TODO: implement show()"); } template <class T> T error(unit_t) { throw std::runtime_error("Error. Terminating"); return T(); } template <class T> unit_t ignore(T t) { return unit_t(); } // TODO add a member to base_string, call that instead int strcomp(const string_impl& s1,const string_impl& s2) { const char* c1 = s1.c_str(); const char* c2 = s2.c_str(); if (c1 && c2) { return strcmp(c1,c2); } else if(c1) { return 1; } else if(c2) { return -1; } else { return 0; } } unit_t haltEngine(unit_t); unit_t drainEngine(unit_t); unit_t sleep(int n); template <template <class> class M, template <class> class C, template <typename...> class R> unit_t loadGraph(string_impl filepath, M<R<int, C<R_elem<int>>>>& c) { std::string tmp_buffer; std::ifstream in(filepath); int source; std::size_t position; while (!in.eof()) { C<R_elem<int>> edge_list; std::size_t start = 0; std::size_t end = start; std::getline(in, tmp_buffer); end = tmp_buffer.find(",", start); source = std::atoi(tmp_buffer.substr(start, end - start).c_str()); start = end + 1; while (end != std::string::npos) { end = tmp_buffer.find(",", start); edge_list.insert(R_elem<int>( std::atoi(tmp_buffer.substr(start, end - start).c_str()))); start = end + 1; } c.insert(R<int, C<R_elem<int>>>{source, std::move(edge_list)}); in >> std::ws; } return unit_t{}; } // TODO move to seperate context template <class C1> unit_t loadRKQ3(const C1& paths, K3::Map<R_key_value<string_impl, int>>& c) { for (auto r : paths) { // Buffers std::string tmp_buffer; R_key_value<string_impl, int> rec; // Infile std::ifstream in; in.open(r.path); // Parse by line while (!in.eof()) { std::getline(in, tmp_buffer, ','); rec.key = tmp_buffer; std::getline(in, tmp_buffer, ','); rec.value = std::atoi(tmp_buffer.c_str()); // ignore last value std::getline(in, tmp_buffer); c.insert(rec); } } return unit_t{}; } int lineCountFile(const string_impl& filepath) { std::cout << "LCF: " << filepath << std::endl; std::ifstream _in; _in.open(filepath); std::string tmp_buffer; std::getline(_in, tmp_buffer); std::cout << "LCF read: " << tmp_buffer << std::endl; return std::atoi(tmp_buffer.c_str()); } template <class C1, template <class> class C, template <typename ...> class R> unit_t loadQ1(const C1& paths, C<R<int, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<int, string_impl> record; // Get pageURL std::getline(in, tmp_buffer, ','); record.pageURL = tmp_buffer; // Get pageRank std::getline(in, tmp_buffer, ','); record.pageRank = std::atoi(tmp_buffer.c_str()); // Ignore avgDuration std::getline(in, tmp_buffer); //record.avgDuration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C1, template<typename S> class C, template <typename ...> class R> unit_t loadQ2(const C1& paths, C<R<double, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<double, string_impl> record; // Get sourceIP std::getline(in, tmp_buffer, ','); record.sourceIP = tmp_buffer; // Ignore until adRevenue std::getline(in, tmp_buffer, ','); //record.destURL = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.visitDate = tmp_buffer; // Get adRevenue std::getline(in, tmp_buffer, ','); record.adRevenue = std::atof(tmp_buffer.c_str()); // Ignore the rest std::getline(in, tmp_buffer, ','); //record.userAgent = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.countryCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.languageCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.searchWord = tmp_buffer; std::getline(in, tmp_buffer); //record.duration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C1, template<typename S> class C, template <typename ...> class R> unit_t loadUVQ3(const C1& paths, C<R<double, string_impl, string_impl, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<double, string_impl, string_impl, string_impl> record; std::getline(in, tmp_buffer, ','); record.sourceIP = tmp_buffer; std::getline(in, tmp_buffer, ','); record.destURL = tmp_buffer; std::getline(in, tmp_buffer, ','); record.visitDate = tmp_buffer; std::getline(in, tmp_buffer, ','); record.adRevenue = std::atof(tmp_buffer.c_str()); std::getline(in, tmp_buffer, ','); //record.userAgent = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.countryCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.languageCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.searchWord = tmp_buffer; std::getline(in, tmp_buffer); //record.duration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C, class F> unit_t logHelper(string_impl filepath, const C& c, F f, string_impl sep) { std::ofstream outfile; outfile.open(filepath); auto& container = c.getConstContainer(); for (auto& elem : container) { f(outfile, elem, sep); outfile << "\n"; } outfile.close(); return unit_t(); } Vector<R_elem<double>> zeroVector(int i); Vector<R_elem<double>> randomVector(int i); template <template <typename S> class C, class R> unit_t loadStrings(string_impl filepath, C<R>& c) { std::string line; std::ifstream infile(filepath); while (std::getline(infile, line)) { c.insert(R{line}); } return unit_t{}; } template <template<typename S> class C, class V> unit_t loadVector(string_impl filepath, C<R_elem<V>>& c) { std::string line; std::ifstream infile(filepath); char *saveptr; while (std::getline(infile, line)){ char * pch; pch = strtok_r(&line[0],",", &saveptr); V v; while (pch) { R_elem<double> rec; rec.elem = std::atof(pch); v.insert(rec); pch = strtok_r(NULL,",", &saveptr); } R_elem<V> rec2 {v}; c.insert(rec2); } return unit_t(); } template <template <typename S> class C, template <typename...> class R, class V> unit_t loadVectorLabel(int dims, string_impl filepath, C<R<double, V>>& c) { // Buffers std::string tmp_buffer; R<double, V> rec; // Infile std::ifstream in; in.open(filepath); char* saveptr; // Parse by line while (!in.eof()) { V v; R_elem<double> r; for (int j = 0; j < dims; j++) { std::getline(in, tmp_buffer, ','); r.elem = std::atof(tmp_buffer.c_str()); v.insert(r); } std::getline(in, tmp_buffer, ','); rec.class_label = std::atof(tmp_buffer.c_str()); rec.elem = v; c.insert(rec); in >> std::ws; } return unit_t{}; } }; // Utilities: // Time: class __time_context { public: __time_context(); int now_int(unit_t); }; // String operations: class __string_context { public: shared_ptr<RE2> pattern; __string_context(); string_impl itos(int i); string_impl rtos(double d); string_impl atos(Address a); F<Collection<R_elem<string_impl>>(const string_impl &)> regex_matcher(const string_impl&); Collection<R_elem<string_impl>> regex_matcher_q4(const string_impl&); template <class S> S slice_string(const S& s, int x, int y) { return s.substr(x, y); } // Split a string by substrings Seq<R_elem<string_impl>> splitString(string_impl, const string_impl&); string_impl takeUntil(const string_impl& s, const string_impl& splitter); int countChar(const string_impl& s, const string_impl& splitter); int tpch_date(const string_impl& s); string_impl tpch_date_to_string(const int& date); }; } // namespace K3 #endif /* K3_RUNTIME_BUILTINS_H */ <commit_msg>Fix graphLoader<commit_after>#ifndef K3_RUNTIME_BUILTINS_H #define K3_RUNTIME_BUILTINS_H #ifdef CACHEPROFILE #include <cpucounters.h> #endif #ifdef MEMPROFILE #include "gperftools/heap-profiler.h" #endif #ifdef JEMALLOC #include "jemalloc/jemalloc.h" #endif #include <ctime> #include <chrono> #include <climits> #include <fstream> #include <sstream> #include <string> #include <climits> #include <functional> #include "re2/re2.h" #include "BaseTypes.hpp" #include "BaseString.hpp" #include "Common.hpp" #include "dataspace/Dataspace.hpp" // Hashing: namespace boost { template<> struct hash<boost::asio::ip::address> { size_t operator()(boost::asio::ip::address const& v) const { if (v.is_v4()) { return v.to_v4().to_ulong(); } if (v.is_v6()) { auto const& range = v.to_v6().to_bytes(); return hash_range(range.begin(), range.end()); } if (v.is_unspecified()) { return 0x4751301174351161ul; } return hash_value(v.to_string()); } }; } // boost namespace K3 { template <class C1, class C, class F> void read_records(C1& paths, C& container, F read_record) { for (auto rec : paths) { std::ifstream in; in.open(rec.path); std::string tmp_buffer; while (!in.eof()) { container.insert(read_record(in, tmp_buffer)); in >> std::ws; } } return; } class __pcm_context { #ifdef CACHEPROFILE protected: PCM *instance; std::shared_ptr<SystemCounterState> initial_state; #endif public: __pcm_context(); ~__pcm_context(); unit_t cacheProfilerStart(unit_t); unit_t cacheProfilerStop(unit_t); }; class __tcmalloc_context { public: unit_t heapProfilerStart(const string_impl&); unit_t heapProfilerStop(unit_t); }; class __jemalloc_context { public: unit_t jemallocStart(unit_t); unit_t jemallocStop(unit_t); }; template <class C1, class C, class F> void read_records_with_resize(int size, C1& paths, C& container, F read_record) { if (size == 0) { return read_records(paths, container, read_record); } else { container.getContainer().resize(size); } int i = 0; for (auto rec : paths) { std::ifstream in; in.open(rec.path); std::string tmp_buffer; while (!in.eof()) { if (i >= container.size(unit_t {}) ) { throw std::runtime_error("Cannot read records, container size is too small"); } container.getContainer()[i++] = read_record(in, tmp_buffer); in >> std::ws; } } return; } // Standard context for common builtins that use a handle to the engine (via inheritance) class __standard_context : public __k3_context { public: __standard_context(Engine&); unit_t openBuiltin(string_impl ch_id, string_impl builtin_ch_id, string_impl fmt); unit_t openFile(string_impl ch_id, string_impl path, string_impl fmt, string_impl mode); unit_t openSocket(string_impl ch_id, Address a, string_impl fmt, string_impl mode); bool hasRead(string_impl ch_id); template<typename T> T doRead(string_impl ch_id); template<typename T> Collection<R_elem<T>> doReadBlock(string_impl ch_id, int block_size); bool hasWrite(string_impl ch_id); template<typename T> unit_t doWrite(string_impl ch_id, T& val); unit_t close(string_impl chan_id); int random(int n); double randomFraction(unit_t); template <class T> int hash(const T& x) { // We implement hash_value for all of our types. // for ordered containers, so we may as well delegate to that. return static_cast<int>(hash_value(x)); } template <class T> string_impl toJson(const T& in) { return K3::serialization::json::encode<T>(in); } template <class T> T range(int i) { T result; for (int j = 0; j < i; j++) { result.insert(j); } return result; } int truncate(double n) { return (int)n; } double real_of_int(int n) { return (double)n; } int get_max_int(unit_t) { return INT_MAX; } unit_t print(string_impl message); // TODO, implement, sharing code with prettify() template <class T> string_impl show(T t) { return string_impl("TODO: implement show()"); } template <class T> T error(unit_t) { throw std::runtime_error("Error. Terminating"); return T(); } template <class T> unit_t ignore(T t) { return unit_t(); } // TODO add a member to base_string, call that instead int strcomp(const string_impl& s1,const string_impl& s2) { const char* c1 = s1.c_str(); const char* c2 = s2.c_str(); if (c1 && c2) { return strcmp(c1,c2); } else if(c1) { return 1; } else if(c2) { return -1; } else { return 0; } } unit_t haltEngine(unit_t); unit_t drainEngine(unit_t); unit_t sleep(int n); template <template <class> class M, template <class> class C, template <typename...> class R, class C2> unit_t loadGraph(const C2& filepaths, M<R<int, C<R_elem<int>>>>& c) { for (const auto& filepath : filepaths) { std::string tmp_buffer; std::ifstream in(filepath.path); int source; std::size_t position; while (!in.eof()) { C<R_elem<int>> edge_list; std::size_t start = 0; std::size_t end = start; std::getline(in, tmp_buffer); end = tmp_buffer.find(",", start); source = std::atoi(tmp_buffer.substr(start, end - start).c_str()); start = end + 1; while (end != std::string::npos) { end = tmp_buffer.find(",", start); edge_list.insert(R_elem<int>( std::atoi(tmp_buffer.substr(start, end - start).c_str()))); start = end + 1; } c.insert(R<int, C<R_elem<int>>>{source, std::move(edge_list)}); in >> std::ws; } } return unit_t{}; } // TODO move to seperate context template <class C1> unit_t loadRKQ3(const C1& paths, K3::Map<R_key_value<string_impl, int>>& c) { for (auto r : paths) { // Buffers std::string tmp_buffer; R_key_value<string_impl, int> rec; // Infile std::ifstream in; in.open(r.path); // Parse by line while (!in.eof()) { std::getline(in, tmp_buffer, ','); rec.key = tmp_buffer; std::getline(in, tmp_buffer, ','); rec.value = std::atoi(tmp_buffer.c_str()); // ignore last value std::getline(in, tmp_buffer); c.insert(rec); } } return unit_t{}; } int lineCountFile(const string_impl& filepath) { std::cout << "LCF: " << filepath << std::endl; std::ifstream _in; _in.open(filepath); std::string tmp_buffer; std::getline(_in, tmp_buffer); std::cout << "LCF read: " << tmp_buffer << std::endl; return std::atoi(tmp_buffer.c_str()); } template <class C1, template <class> class C, template <typename ...> class R> unit_t loadQ1(const C1& paths, C<R<int, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<int, string_impl> record; // Get pageURL std::getline(in, tmp_buffer, ','); record.pageURL = tmp_buffer; // Get pageRank std::getline(in, tmp_buffer, ','); record.pageRank = std::atoi(tmp_buffer.c_str()); // Ignore avgDuration std::getline(in, tmp_buffer); //record.avgDuration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C1, template<typename S> class C, template <typename ...> class R> unit_t loadQ2(const C1& paths, C<R<double, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<double, string_impl> record; // Get sourceIP std::getline(in, tmp_buffer, ','); record.sourceIP = tmp_buffer; // Ignore until adRevenue std::getline(in, tmp_buffer, ','); //record.destURL = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.visitDate = tmp_buffer; // Get adRevenue std::getline(in, tmp_buffer, ','); record.adRevenue = std::atof(tmp_buffer.c_str()); // Ignore the rest std::getline(in, tmp_buffer, ','); //record.userAgent = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.countryCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.languageCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.searchWord = tmp_buffer; std::getline(in, tmp_buffer); //record.duration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C1, template<typename S> class C, template <typename ...> class R> unit_t loadUVQ3(const C1& paths, C<R<double, string_impl, string_impl, string_impl>>& c) { K3::read_records(paths, c, [] (std::istream& in, std::string& tmp_buffer) { R<double, string_impl, string_impl, string_impl> record; std::getline(in, tmp_buffer, ','); record.sourceIP = tmp_buffer; std::getline(in, tmp_buffer, ','); record.destURL = tmp_buffer; std::getline(in, tmp_buffer, ','); record.visitDate = tmp_buffer; std::getline(in, tmp_buffer, ','); record.adRevenue = std::atof(tmp_buffer.c_str()); std::getline(in, tmp_buffer, ','); //record.userAgent = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.countryCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.languageCode = tmp_buffer; std::getline(in, tmp_buffer, ','); //record.searchWord = tmp_buffer; std::getline(in, tmp_buffer); //record.duration = std::atoi(tmp_buffer.c_str()); return record; }); return unit_t {}; } template <class C, class F> unit_t logHelper(string_impl filepath, const C& c, F f, string_impl sep) { std::ofstream outfile; outfile.open(filepath); auto& container = c.getConstContainer(); for (auto& elem : container) { f(outfile, elem, sep); outfile << "\n"; } outfile.close(); return unit_t(); } Vector<R_elem<double>> zeroVector(int i); Vector<R_elem<double>> randomVector(int i); template <template <typename S> class C, class R> unit_t loadStrings(string_impl filepath, C<R>& c) { std::string line; std::ifstream infile(filepath); while (std::getline(infile, line)) { c.insert(R{line}); } return unit_t{}; } template <template<typename S> class C, class V> unit_t loadVector(string_impl filepath, C<R_elem<V>>& c) { std::string line; std::ifstream infile(filepath); char *saveptr; while (std::getline(infile, line)){ char * pch; pch = strtok_r(&line[0],",", &saveptr); V v; while (pch) { R_elem<double> rec; rec.elem = std::atof(pch); v.insert(rec); pch = strtok_r(NULL,",", &saveptr); } R_elem<V> rec2 {v}; c.insert(rec2); } return unit_t(); } template <template <typename S> class C, template <typename...> class R, class V> unit_t loadVectorLabel(int dims, string_impl filepath, C<R<double, V>>& c) { // Buffers std::string tmp_buffer; R<double, V> rec; // Infile std::ifstream in; in.open(filepath); char* saveptr; // Parse by line while (!in.eof()) { V v; R_elem<double> r; for (int j = 0; j < dims; j++) { std::getline(in, tmp_buffer, ','); r.elem = std::atof(tmp_buffer.c_str()); v.insert(r); } std::getline(in, tmp_buffer, ','); rec.class_label = std::atof(tmp_buffer.c_str()); rec.elem = v; c.insert(rec); in >> std::ws; } return unit_t{}; } }; // Utilities: // Time: class __time_context { public: __time_context(); int now_int(unit_t); }; // String operations: class __string_context { public: shared_ptr<RE2> pattern; __string_context(); string_impl itos(int i); string_impl rtos(double d); string_impl atos(Address a); F<Collection<R_elem<string_impl>>(const string_impl &)> regex_matcher(const string_impl&); Collection<R_elem<string_impl>> regex_matcher_q4(const string_impl&); template <class S> S slice_string(const S& s, int x, int y) { return s.substr(x, y); } // Split a string by substrings Seq<R_elem<string_impl>> splitString(string_impl, const string_impl&); string_impl takeUntil(const string_impl& s, const string_impl& splitter); int countChar(const string_impl& s, const string_impl& splitter); int tpch_date(const string_impl& s); string_impl tpch_date_to_string(const int& date); }; } // namespace K3 #endif /* K3_RUNTIME_BUILTINS_H */ <|endoftext|>
<commit_before>#include "catch.hpp" #include <toolbox/alloc/stack_allocator.hpp> #include <iostream> TEST_CASE("simple functionality", "[alloc][stack_allocator]") { toolbox::alloc::stack_allocator<int, 10> alloc; int *p1 = alloc.allocate(1); int *p2 = alloc.allocate(1); int *p3 = alloc.allocate(8); REQUIRE(p2 - p1 == 1); REQUIRE(p3 != nullptr); REQUIRE(alloc.allocate(1) == nullptr); REQUIRE(alloc.available() == 0); alloc.deallocate(p1, 1); REQUIRE(alloc.available() == 0); alloc.deallocate(p3, 8); REQUIRE(alloc.available() == 8); } TEST_CASE("test with vector", "[alloc][stack_allocator][vector]") { toolbox::alloc::stack_allocator<float, 5> alloc; std::vector<float, decltype(alloc)> vec(alloc); vec.push_back(1); vec.push_back(1); } <commit_msg>tests: check for exception in allocator tests<commit_after>#include "catch.hpp" #include <toolbox/alloc/stack_allocator.hpp> #include <iostream> TEST_CASE("simple functionality", "[alloc][stack_allocator]") { toolbox::alloc::stack_allocator<int, 10> alloc; int *p1 = alloc.allocate(1); int *p2 = alloc.allocate(1); int *p3 = alloc.allocate(8); REQUIRE(p2 - p1 == 1); REQUIRE(p3 != nullptr); REQUIRE_THROWS(alloc.allocate(1)); REQUIRE(alloc.available() == 0); alloc.deallocate(p1, 1); REQUIRE(alloc.available() == 0); alloc.deallocate(p3, 8); REQUIRE(alloc.available() == 8); } TEST_CASE("test with vector", "[alloc][stack_allocator][vector]") { toolbox::alloc::stack_allocator<float, 5> alloc; std::vector<float, decltype(alloc)> vec(alloc); vec.push_back(1); vec.push_back(1); } <|endoftext|>
<commit_before>#ifndef DIMENTIONS_HPP #define DIMENTIONS_HPP struct Dimentions { int W; int H; Dimentions(int w, int h) : W(w), H(h) {} }; #endif // DIMENTIONS_HPP <commit_msg>Add comparison operators for Dimention class.<commit_after>#ifndef DIMENTIONS_HPP #define DIMENTIONS_HPP struct Dimentions { int W; int H; Dimentions(int w, int h) : W(w), H(h) {} }; inline bool operator==(const Dimentions& lhs, const Dimentions& rhs) { return lhs.W == rhs.W && lhs.H == rhs.H; } inline bool operator!=(const Dimentions& lhs, const Dimentions& rhs) { return !(lhs == rhs); } #endif // DIMENTIONS_HPP <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCEventProcessModule.cpp // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCEventProcessModule // // ------------------------------------------------------------------------- #include "NFCEventProcessModule.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" #include "NFComm/NFPluginModule/NFIActorManager.h" NFCEventProcessModule::NFCEventProcessModule(NFIPluginManager* p) { pPluginManager = p; } NFCEventProcessModule::~NFCEventProcessModule() { mRemoveObjectListEx.ClearAll(); mRemoveEventListEx.ClearAll(); mxClassEventInfoEx.ClearAll(); mObjectEventInfoMapEx.ClearAll(); } bool NFCEventProcessModule::Init() { return true; } bool NFCEventProcessModule::Shut() { mxClassEventInfoEx.ClearAll(); mRemoveEventListEx.ClearAll(); mObjectEventInfoMapEx.ClearAll(); return true; } void NFCEventProcessModule::OnReload(const char* strModuleName, NFILogicModule* pModule) { } bool NFCEventProcessModule::AddEventCallBack(const NFIDENTID& objectID, const int nEventID, const EVENT_PROCESS_FUNCTOR_PTR& cb) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr != pObjectEventInfo) { pObjectEventInfo = NF_SHARE_PTR<NFCObjectEventInfo>(NF_NEW NFCObjectEventInfo()); mObjectEventInfoMapEx.AddElement(objectID, pObjectEventInfo); } assert(nullptr != pObjectEventInfo); NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr != pEventInfo) { pEventInfo = NF_SHARE_PTR<NFEventList>(NF_NEW NFEventList()); pObjectEventInfo->AddElement(nEventID, pEventInfo); } assert(nullptr != pEventInfo); pEventInfo->Add(cb); return true; } bool NFCEventProcessModule::Execute(const float fLasFrametime, const float fStartedTime) { NFIDENTID ident; NF_SHARE_PTR<NFList<int>> pList = mRemoveEventListEx.First(ident); while (nullptr != pList) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(ident); if (pObjectEventInfo) { int nEvent = 0; bool bRet = pList->First(nEvent); while (bRet) { pObjectEventInfo->RemoveElement(nEvent); bRet = pList->Next(nEvent); } } pList = NULL; pList = mRemoveEventListEx.Next(); } mRemoveEventListEx.ClearAll(); ////////////////////////////////////////////////////////////////////////// //删除事件对象 bool bRet = mRemoveObjectListEx.First(ident); while (bRet) { mObjectEventInfoMapEx.RemoveElement(ident); bRet = mRemoveObjectListEx.Next(ident); } mRemoveObjectListEx.ClearAll(); return true; } bool NFCEventProcessModule::RemoveEvent(const NFIDENTID& objectID) { return mRemoveObjectListEx.Add(objectID); } bool NFCEventProcessModule::RemoveEventCallBack(const NFIDENTID& objectID, const int nEventID/*, const EVENT_PROCESS_FUNCTOR_PTR& cb*/) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr != pObjectEventInfo) { NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr != pEventInfo) { NF_SHARE_PTR<NFList<int>> pList = mRemoveEventListEx.GetElement(objectID); if (nullptr != pList) { pList = NF_SHARE_PTR<NFList<int>>(NF_NEW NFList<int>()); mRemoveEventListEx.AddElement(objectID, pList); } pList->Add(nEventID); return true; } } return false; } bool NFCEventProcessModule::DoEvent(const NFIDENTID& objectID, const int nEventID, const NFIDataList& valueList) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr == pObjectEventInfo) { return false; } NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr == pEventInfo) { return false; } EVENT_PROCESS_FUNCTOR_PTR cb; bool bRet = pEventInfo->First(cb); while (bRet) { cb->operator()(objectID, nEventID, valueList); bRet = pEventInfo->Next(cb); } return true; } bool NFCEventProcessModule::DoEvent(const NFIDENTID& objectID, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& valueList) { NF_SHARE_PTR<NFCClassEventList> pEventList = mxClassEventInfoEx.GetElement(strClassName); if (nullptr != pEventList) { CLASS_EVENT_FUNCTOR_PTR cb; bool bRet = pEventList->First(cb); while (bRet) { cb->operator()(objectID, strClassName, eClassEvent, valueList); bRet = pEventList->Next(cb); } } return false; } bool NFCEventProcessModule::HasEventCallBack(const NFIDENTID& objectID, const int nEventID) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr != pObjectEventInfo) { NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr != pEventInfo) { return true; } } return false; } bool NFCEventProcessModule::AddClassCallBack(const std::string& strClassName, const CLASS_EVENT_FUNCTOR_PTR& cb) { NF_SHARE_PTR<NFCClassEventList> pEventList = mxClassEventInfoEx.GetElement(strClassName); if (nullptr == pEventList) { pEventList = NF_SHARE_PTR<NFCClassEventList>(NF_NEW NFCClassEventList()); mxClassEventInfoEx.AddElement(strClassName, pEventList); } assert(NULL != pEventList); pEventList->Add(cb); return true; }<commit_msg>fixed dump for event system<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCEventProcessModule.cpp // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCEventProcessModule // // ------------------------------------------------------------------------- #include "NFCEventProcessModule.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" #include "NFComm/NFPluginModule/NFIActorManager.h" NFCEventProcessModule::NFCEventProcessModule(NFIPluginManager* p) { pPluginManager = p; } NFCEventProcessModule::~NFCEventProcessModule() { mRemoveObjectListEx.ClearAll(); mRemoveEventListEx.ClearAll(); mxClassEventInfoEx.ClearAll(); mObjectEventInfoMapEx.ClearAll(); } bool NFCEventProcessModule::Init() { return true; } bool NFCEventProcessModule::Shut() { mxClassEventInfoEx.ClearAll(); mRemoveEventListEx.ClearAll(); mObjectEventInfoMapEx.ClearAll(); return true; } void NFCEventProcessModule::OnReload(const char* strModuleName, NFILogicModule* pModule) { } bool NFCEventProcessModule::AddEventCallBack(const NFIDENTID& objectID, const int nEventID, const EVENT_PROCESS_FUNCTOR_PTR& cb) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr == pObjectEventInfo) { pObjectEventInfo = NF_SHARE_PTR<NFCObjectEventInfo>(NF_NEW NFCObjectEventInfo()); mObjectEventInfoMapEx.AddElement(objectID, pObjectEventInfo); } assert(nullptr != pObjectEventInfo); NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr == pEventInfo) { pEventInfo = NF_SHARE_PTR<NFEventList>(NF_NEW NFEventList()); pObjectEventInfo->AddElement(nEventID, pEventInfo); } assert(nullptr != pEventInfo); pEventInfo->Add(cb); return true; } bool NFCEventProcessModule::Execute(const float fLasFrametime, const float fStartedTime) { NFIDENTID ident; NF_SHARE_PTR<NFList<int>> pList = mRemoveEventListEx.First(ident); while (nullptr != pList) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(ident); if (pObjectEventInfo) { int nEvent = 0; bool bRet = pList->First(nEvent); while (bRet) { pObjectEventInfo->RemoveElement(nEvent); bRet = pList->Next(nEvent); } } pList = NULL; pList = mRemoveEventListEx.Next(); } mRemoveEventListEx.ClearAll(); ////////////////////////////////////////////////////////////////////////// //删除事件对象 bool bRet = mRemoveObjectListEx.First(ident); while (bRet) { mObjectEventInfoMapEx.RemoveElement(ident); bRet = mRemoveObjectListEx.Next(ident); } mRemoveObjectListEx.ClearAll(); return true; } bool NFCEventProcessModule::RemoveEvent(const NFIDENTID& objectID) { return mRemoveObjectListEx.Add(objectID); } bool NFCEventProcessModule::RemoveEventCallBack(const NFIDENTID& objectID, const int nEventID/*, const EVENT_PROCESS_FUNCTOR_PTR& cb*/) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr != pObjectEventInfo) { NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr != pEventInfo) { NF_SHARE_PTR<NFList<int>> pList = mRemoveEventListEx.GetElement(objectID); if (nullptr != pList) { pList = NF_SHARE_PTR<NFList<int>>(NF_NEW NFList<int>()); mRemoveEventListEx.AddElement(objectID, pList); } pList->Add(nEventID); return true; } } return false; } bool NFCEventProcessModule::DoEvent(const NFIDENTID& objectID, const int nEventID, const NFIDataList& valueList) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr == pObjectEventInfo) { return false; } NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr == pEventInfo) { return false; } EVENT_PROCESS_FUNCTOR_PTR cb; bool bRet = pEventInfo->First(cb); while (bRet) { cb->operator()(objectID, nEventID, valueList); bRet = pEventInfo->Next(cb); } return true; } bool NFCEventProcessModule::DoEvent(const NFIDENTID& objectID, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& valueList) { NF_SHARE_PTR<NFCClassEventList> pEventList = mxClassEventInfoEx.GetElement(strClassName); if (nullptr != pEventList) { CLASS_EVENT_FUNCTOR_PTR cb; bool bRet = pEventList->First(cb); while (bRet) { cb->operator()(objectID, strClassName, eClassEvent, valueList); bRet = pEventList->Next(cb); } } return false; } bool NFCEventProcessModule::HasEventCallBack(const NFIDENTID& objectID, const int nEventID) { NF_SHARE_PTR<NFCObjectEventInfo> pObjectEventInfo = mObjectEventInfoMapEx.GetElement(objectID); if (nullptr != pObjectEventInfo) { NF_SHARE_PTR<NFEventList> pEventInfo = pObjectEventInfo->GetElement(nEventID); if (nullptr != pEventInfo) { return true; } } return false; } bool NFCEventProcessModule::AddClassCallBack(const std::string& strClassName, const CLASS_EVENT_FUNCTOR_PTR& cb) { NF_SHARE_PTR<NFCClassEventList> pEventList = mxClassEventInfoEx.GetElement(strClassName); if (nullptr == pEventList) { pEventList = NF_SHARE_PTR<NFCClassEventList>(NF_NEW NFCClassEventList()); mxClassEventInfoEx.AddElement(strClassName, pEventList); } assert(NULL != pEventList); pEventList->Add(cb); return true; }<|endoftext|>
<commit_before>#include "ROOT/RDataFrame.hxx" #include "ROOT/RTrivialDS.hxx" #include "TMemFile.h" #include "TTree.h" #include "gtest/gtest.h" using namespace ROOT; using namespace ROOT::RDF; TEST(RDataFrameInterface, CreateFromCStrings) { RDataFrame tdf("t", "file"); } TEST(RDataFrameInterface, CreateFromStrings) { std::string t("t"), f("file"); RDataFrame tdf(t, f); } TEST(RDataFrameInterface, CreateFromContainer) { std::string t("t"); std::vector<std::string> f({"f1", "f2"}); RDataFrame tdf(t, f); } TEST(RDataFrameInterface, CreateFromInitList) { RDataFrame tdf("t", {"f1", "f2"}); } TEST(RDataFrameInterface, CreateFromNullTDirectory) { int ret = 1; try { RDataFrame tdf("t", nullptr); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } TEST(RDataFrameInterface, CreateFromNonExistingTree) { int ret = 1; try { RDataFrame tdf("theTreeWhichDoesNotExist", gDirectory); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } TEST(RDataFrameInterface, CreateFromTree) { TMemFile f("dataframe_interfaceAndUtils_0.root", "RECREATE"); TTree t("t", "t"); RDataFrame tdf(t); auto c = tdf.Count(); EXPECT_EQ(0U, *c); } TEST(RDataFrameInterface, CreateAliases) { RDataFrame tdf(1); auto aliased_tdf = tdf.Define("c0", []() { return 0; }).Alias("c1", "c0").Alias("c2", "c0").Alias("c3", "c1"); auto c = aliased_tdf.Count(); EXPECT_EQ(1U, *c); int ret(1); try { aliased_tdf.Alias("c4", "c"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column."; ret = 1; try { aliased_tdf.Alias("c0", "c2"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when specifying an alias name which is the name of a column."; ret = 1; try { aliased_tdf.Alias("c2", "c1"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when re-using an alias for a different column."; } TEST(RDataFrameInterface, CheckAliasesPerChain) { RDataFrame tdf(1); auto d = tdf.Define("c0", []() { return 0; }); // Now branch the graph auto ok = []() { return true; }; auto f0 = d.Filter(ok); auto f1 = d.Filter(ok); auto f0a = f0.Alias("c1", "c0"); // must work auto f0aa = f0a.Alias("c2", "c1"); // must fail auto ret = 1; try { auto f1a = f1.Alias("c2", "c1"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column."; } TEST(RDataFrameInterface, GetColumnNamesFromScratch) { RDataFrame f(1); auto dummyGen = []() { return 1; }; auto names = f.Define("a", dummyGen).Define("b", dummyGen).Define("tdfDummy_", dummyGen).GetColumnNames(); EXPECT_STREQ("a", names[0].c_str()); EXPECT_STREQ("b", names[1].c_str()); EXPECT_EQ(2U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromTree) { TTree t("t", "t"); int a, b; t.Branch("a", &a); t.Branch("b", &b); RDataFrame tdf(t); auto names = tdf.GetColumnNames(); EXPECT_STREQ("a", names[0].c_str()); EXPECT_STREQ("a.a", names[1].c_str()); EXPECT_STREQ("b", names[2].c_str()); EXPECT_STREQ("b.b", names[3].c_str()); EXPECT_EQ(4U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromOrdering) { TTree t("t", "t"); int a, b; t.Branch("zzz", &a); t.Branch("aaa", &b); RDataFrame tdf(t); auto names = tdf.GetColumnNames(); EXPECT_STREQ("zzz", names[0].c_str()); EXPECT_STREQ("zzz.zzz", names[1].c_str()); EXPECT_STREQ("aaa", names[2].c_str()); EXPECT_STREQ("aaa.aaa", names[3].c_str()); EXPECT_EQ(4U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromSource) { std::unique_ptr<RDataSource> tds(new RTrivialDS(1)); RDataFrame tdf(std::move(tds)); auto names = tdf.Define("b", []() { return 1; }).GetColumnNames(); EXPECT_STREQ("b", names[0].c_str()); EXPECT_STREQ("col0", names[1].c_str()); EXPECT_EQ(2U, names.size()); } TEST(RDataFrameInterface, DefaultColumns) { RDataFrame tdf(8); ULong64_t i(0ULL); auto checkSlotAndEntries = [&i](unsigned int slot, ULong64_t entry) { EXPECT_EQ(entry, i); EXPECT_EQ(slot, 0U); i++; }; tdf.Foreach(checkSlotAndEntries, {"tdfslot_", "tdfentry_"}); } TEST(RDataFrameInterface, JitDefaultColumns) { RDataFrame tdf(8); auto f = tdf.Filter("tdfslot_ + tdfentry_ == 3"); auto maxEntry = f.Max("tdfentry_"); auto minEntry = f.Min("tdfentry_"); EXPECT_EQ(*maxEntry, *minEntry); } <commit_msg>[DF] Add test for validation of custom column names<commit_after>#include "ROOT/RDataFrame.hxx" #include "ROOT/RTrivialDS.hxx" #include "TMemFile.h" #include "TTree.h" #include "gtest/gtest.h" using namespace ROOT; using namespace ROOT::RDF; TEST(RDataFrameInterface, CreateFromCStrings) { RDataFrame tdf("t", "file"); } TEST(RDataFrameInterface, CreateFromStrings) { std::string t("t"), f("file"); RDataFrame tdf(t, f); } TEST(RDataFrameInterface, CreateFromContainer) { std::string t("t"); std::vector<std::string> f({"f1", "f2"}); RDataFrame tdf(t, f); } TEST(RDataFrameInterface, CreateFromInitList) { RDataFrame tdf("t", {"f1", "f2"}); } TEST(RDataFrameInterface, CreateFromNullTDirectory) { int ret = 1; try { RDataFrame tdf("t", nullptr); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } TEST(RDataFrameInterface, CreateFromNonExistingTree) { int ret = 1; try { RDataFrame tdf("theTreeWhichDoesNotExist", gDirectory); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } TEST(RDataFrameInterface, CreateFromTree) { TMemFile f("dataframe_interfaceAndUtils_0.root", "RECREATE"); TTree t("t", "t"); RDataFrame tdf(t); auto c = tdf.Count(); EXPECT_EQ(0U, *c); } TEST(RDataFrameInterface, CreateAliases) { RDataFrame tdf(1); auto aliased_tdf = tdf.Define("c0", []() { return 0; }).Alias("c1", "c0").Alias("c2", "c0").Alias("c3", "c1"); auto c = aliased_tdf.Count(); EXPECT_EQ(1U, *c); int ret(1); try { aliased_tdf.Alias("c4", "c"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column."; ret = 1; try { aliased_tdf.Alias("c0", "c2"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when specifying an alias name which is the name of a column."; ret = 1; try { aliased_tdf.Alias("c2", "c1"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when re-using an alias for a different column."; } TEST(RDataFrameInterface, CheckAliasesPerChain) { RDataFrame tdf(1); auto d = tdf.Define("c0", []() { return 0; }); // Now branch the graph auto ok = []() { return true; }; auto f0 = d.Filter(ok); auto f1 = d.Filter(ok); auto f0a = f0.Alias("c1", "c0"); // must work auto f0aa = f0a.Alias("c2", "c1"); // must fail auto ret = 1; try { auto f1a = f1.Alias("c2", "c1"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "No exception thrown when trying to alias a non-existing column."; } TEST(RDataFrameInterface, GetColumnNamesFromScratch) { RDataFrame f(1); auto dummyGen = []() { return 1; }; auto names = f.Define("a", dummyGen).Define("b", dummyGen).Define("tdfDummy_", dummyGen).GetColumnNames(); EXPECT_STREQ("a", names[0].c_str()); EXPECT_STREQ("b", names[1].c_str()); EXPECT_EQ(2U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromTree) { TTree t("t", "t"); int a, b; t.Branch("a", &a); t.Branch("b", &b); RDataFrame tdf(t); auto names = tdf.GetColumnNames(); EXPECT_STREQ("a", names[0].c_str()); EXPECT_STREQ("a.a", names[1].c_str()); EXPECT_STREQ("b", names[2].c_str()); EXPECT_STREQ("b.b", names[3].c_str()); EXPECT_EQ(4U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromOrdering) { TTree t("t", "t"); int a, b; t.Branch("zzz", &a); t.Branch("aaa", &b); RDataFrame tdf(t); auto names = tdf.GetColumnNames(); EXPECT_STREQ("zzz", names[0].c_str()); EXPECT_STREQ("zzz.zzz", names[1].c_str()); EXPECT_STREQ("aaa", names[2].c_str()); EXPECT_STREQ("aaa.aaa", names[3].c_str()); EXPECT_EQ(4U, names.size()); } TEST(RDataFrameInterface, GetColumnNamesFromSource) { std::unique_ptr<RDataSource> tds(new RTrivialDS(1)); RDataFrame tdf(std::move(tds)); auto names = tdf.Define("b", []() { return 1; }).GetColumnNames(); EXPECT_STREQ("b", names[0].c_str()); EXPECT_STREQ("col0", names[1].c_str()); EXPECT_EQ(2U, names.size()); } TEST(RDataFrameInterface, DefaultColumns) { RDataFrame tdf(8); ULong64_t i(0ULL); auto checkSlotAndEntries = [&i](unsigned int slot, ULong64_t entry) { EXPECT_EQ(entry, i); EXPECT_EQ(slot, 0U); i++; }; tdf.Foreach(checkSlotAndEntries, {"tdfslot_", "tdfentry_"}); } TEST(RDataFrameInterface, JitDefaultColumns) { RDataFrame tdf(8); auto f = tdf.Filter("tdfslot_ + tdfentry_ == 3"); auto maxEntry = f.Max("tdfentry_"); auto minEntry = f.Min("tdfentry_"); EXPECT_EQ(*maxEntry, *minEntry); } TEST(RDataFrameInterface, InvalidDefine) { RDataFrame df(1); try { df.Define("1", [] { return true; }); } catch (const std::runtime_error &e) { EXPECT_STREQ("Cannot define column \"1\": not a valid C++ variable name.", e.what()); } try { df.Define("a-b", "true"); } catch (const std::runtime_error &e) { EXPECT_STREQ("Cannot define column \"a-b\": not a valid C++ variable name.", e.what()); } } <|endoftext|>
<commit_before>#include "command.h" Command::Command() { //nothing? } /*Command::Command(string n) { commandName = n; } Command::Command(string n, vector<string> a) { commandName = n; args.resize(a.size()); for(int i = 0; i < a.size(); i++) { args.at(i) = a.at(i); } } Command::Command(const Command &c) { commandName = c.getName(); }*/ Command::Command(vector <string> &v) { /*for(int i = 0; i < v.size(); i++) { cout << v.at(i) << " "; args.push_back(v.at(i)); }*/ args = v; } bool Command::exec() { if(args.at(0) == "exit") { exit(0); } /*char* evp[] = {const_cast<char*>( commandName.c_str() ), (char*) 0 }; execvp( const_cast<char*>( commandName.c_str() ) , evp);*/ cout << "Executing: " << args.at(0) << endl; // insert exec code here! vector<char*> temp; for(int i = 0; i <args.size(); i++) { temp.push_back(const_cast<char*>(args.at(i).c_str())); } temp.push_back(NULL); char** argArray = &temp[0]; pid_t pID = fork(); if(pID == 0) { //child cout << "Child Process here calling EXECVP" << endl; //execvp usage requires a const_cast<char*> of a cstr for arg1 //and a char* array with the const_cast<char*> cstr and following arguments //this will call execvp on our command execvp(argArray[0], argArray); } else if(pID < 0) { cout << "Fork failure" << endl; exit(1); } else { //parent //waitPID(); << Need help implemeting this to wait for child to finish cout << "Parent does nothing here" << endl; } //assuming it executed correctly data = true; return true; } void Command::rearg(vector <string> &v) { args.clear(); for(int i = 0; i < v.size(); i++) { args.push_back(v.at(i)); } } void Command::print() { //cout << "Command Name: " << commandName << endl; cout << "Vector of Arguments: " << endl; for (int i = 0; i < args.size(); i++) { cout << args.at(i) << " "; } cout << endl; } <commit_msg>fixed child process not terminating bug<commit_after>#include "command.h" #include <sys/wait.h> Command::Command() { //nothing? } /*Command::Command(string n) { commandName = n; } Command::Command(string n, vector<string> a) { commandName = n; args.resize(a.size()); for(int i = 0; i < a.size(); i++) { args.at(i) = a.at(i); } } Command::Command(const Command &c) { commandName = c.getName(); }*/ Command::Command(vector <string> &v) { /*for(int i = 0; i < v.size(); i++) { cout << v.at(i) << " "; args.push_back(v.at(i)); }*/ args = v; } bool Command::exec() { if(args.at(0) == "exit") { exit(0); } /*char* evp[] = {const_cast<char*>( commandName.c_str() ), (char*) 0 }; execvp( const_cast<char*>( commandName.c_str() ) , evp);*/ cout << "Executing: " << args.at(0) << endl; // insert exec code here! vector<char*> temp; for(int i = 0; i <args.size(); i++) { temp.push_back(const_cast<char*>(args.at(i).c_str())); } temp.push_back(NULL); char** argArray = &temp[0]; pid_t pID = fork(); if(pID == 0) { //child cout << "Child Process here calling EXECVP" << endl; //execvp usage requires a const_cast<char*> of a cstr for arg1 //and a char* array with the const_cast<char*> cstr and following arguments //this will call execvp on our command execvp(argArray[0], argArray); } else if(pID < 0) { cout << "Fork failure" << endl; exit(1); } else { //parent int status; wait(&status); if(status == -1) { cout << "There was an error with wait()!! "; exit(1); } cout << endl; cout << "Parent does nothing here" << endl; } //assuming it executed correctly data = true; return true; } void Command::rearg(vector <string> &v) { args.clear(); for(int i = 0; i < v.size(); i++) { args.push_back(v.at(i)); } } void Command::print() { //cout << "Command Name: " << commandName << endl; cout << "Vector of Arguments: " << endl; for (int i = 0; i < args.size(); i++) { cout << args.at(i) << " "; } cout << endl; } <|endoftext|>
<commit_before>#include "RConfigure.h" #include "ROOT/RRawFile.hxx" #include "ROOT/RMakeUnique.hxx" #include <algorithm> #include <cstdio> #include <cstring> #include <fstream> #include <memory> #include <stdexcept> #include <string> #include <utility> #include "gtest/gtest.h" using RRawFile = ROOT::Internal::RRawFile; namespace { /** * An RAII wrapper around an open temporary file on disk. It cleans up the guarded file when the wrapper object * goes out of scope. */ class FileRaii { private: std::string fPath; public: FileRaii(const std::string &path, const std::string &content) : fPath(path) { std::ofstream ostrm(path, std::ios::binary | std::ios::out | std::ios::trunc); ostrm << content; } FileRaii(const FileRaii&) = delete; FileRaii& operator=(const FileRaii&) = delete; ~FileRaii() { std::remove(fPath.c_str()); } }; /** * A minimal RRawFile implementation that serves data from a string. It keeps a counter of the number of read calls * to help veryfing the buffer logic in the base class. */ class RRawFileMock : public RRawFile { public: std::string fContent; unsigned fNumReadAt; RRawFileMock(const std::string &content, RRawFile::ROptions options) : RRawFile("", options), fContent(content), fNumReadAt(0) { } std::unique_ptr<RRawFile> Clone() const final { return std::make_unique<RRawFileMock>(fContent, fOptions); } void OpenImpl() final { } size_t ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset) final { fNumReadAt++; if (offset > fContent.length()) return 0; auto slice = fContent.substr(offset, nbytes); memcpy(buffer, slice.data(), slice.length()); return slice.length(); } std::uint64_t GetSizeImpl() final { return fContent.size(); } int GetFeatures() const final { return kFeatureHasSize; } }; } // anonymous namespace TEST(RRawFile, Empty) { FileRaii emptyGuard("testEmpty", ""); auto f = RRawFile::Create("testEmpty"); EXPECT_TRUE(f->GetFeatures() & RRawFile::kFeatureHasSize); EXPECT_EQ(0u, f->GetSize()); EXPECT_EQ(0u, f->Read(nullptr, 0)); EXPECT_EQ(0u, f->ReadAt(nullptr, 0, 1)); std::string line; EXPECT_FALSE(f->Readln(line)); } TEST(RRawFile, Basic) { FileRaii basicGuard("testBasic", "foo\nbar"); auto f = RRawFile::Create("testBasic"); EXPECT_EQ(7u, f->GetSize()); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("foo", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("bar", line.c_str()); EXPECT_FALSE(f->Readln(line)); auto clone = f->Clone(); /// file pointer is reset by clone EXPECT_TRUE(clone->Readln(line)); EXPECT_STREQ("foo", line.c_str()); auto f2 = RRawFile::Create("NoSuchFile"); EXPECT_THROW(f2->Readln(line), std::runtime_error); auto f3 = RRawFile::Create("FiLE://testBasic"); EXPECT_EQ(7u, f3->GetSize()); EXPECT_THROW(RRawFile::Create("://testBasic"), std::runtime_error); EXPECT_THROW(RRawFile::Create("Communicator://Kirk"), std::runtime_error); } TEST(RRawFile, Remote) { #ifdef R__HAS_DAVIX auto f = RRawFile::Create("http://root.cern.ch/files/davix.test"); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("Hello, World", line.c_str()); #else EXPECT_THROW(RRawFile::Create("http://root.cern.ch/files/davix.test"), std::runtime_error); #endif } TEST(RRawFile, Readln) { FileRaii linebreakGuard("testLinebreak", "foo\r\none\nline\r\n\r\n"); auto f = RRawFile::Create("testLinebreak"); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("foo", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("one\nline", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_TRUE(line.empty()); EXPECT_FALSE(f->Readln(line)); } TEST(RRawFile, ReadV) { FileRaii readvGuard("test_rawfile_readv", "Hello, World"); auto f = RRawFile::Create("test_rawfile_readv"); char buffer[2]; buffer[0] = buffer[1] = 0; RRawFile::RIOVec iovec[2]; iovec[0].fBuffer = &buffer[0]; iovec[0].fOffset = 0; iovec[0].fSize = 1; iovec[1].fBuffer = &buffer[1]; iovec[1].fOffset = 11; iovec[1].fSize = 2; f->ReadV(iovec, 2); EXPECT_EQ(1U, iovec[0].fOutBytes); EXPECT_EQ(1U, iovec[1].fOutBytes); EXPECT_EQ('H', buffer[0]); EXPECT_EQ('d', buffer[1]); } TEST(RRawFile, SplitUrl) { EXPECT_STREQ("C:\\Data\\events.root", RRawFile::GetLocation("C:\\Data\\events.root").c_str()); EXPECT_STREQ("///many/slashes", RRawFile::GetLocation("///many/slashes").c_str()); EXPECT_STREQ("/many/slashes", RRawFile::GetLocation(":///many/slashes").c_str()); EXPECT_STREQ("file", RRawFile::GetTransport("/foo").c_str()); EXPECT_STREQ("http", RRawFile::GetTransport("http://").c_str()); EXPECT_STREQ("", RRawFile::GetLocation("http://").c_str()); EXPECT_STREQ("http", RRawFile::GetTransport("http://file:///bar").c_str()); } TEST(RRawFile, ReadDirect) { FileRaii directGuard("testDirect", "abc"); char buffer; RRawFile::ROptions options; options.fBlockSize = 0; auto f = RRawFile::Create("testDirect"); EXPECT_EQ(0u, f->Read(&buffer, 0)); EXPECT_EQ(1u, f->Read(&buffer, 1)); EXPECT_EQ('a', buffer); EXPECT_EQ(1u, f->ReadAt(&buffer, 1, 2)); EXPECT_EQ('c', buffer); } TEST(RRawFile, ReadBuffered) { char buffer[8]; RRawFile::ROptions options; options.fBlockSize = 2; std::unique_ptr<RRawFileMock> f(new RRawFileMock("abcdef", options)); buffer[3] = '\0'; EXPECT_EQ(3u, f->ReadAt(buffer, 3, 1)); EXPECT_STREQ("bcd", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; buffer[2] = '\0'; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2)); EXPECT_STREQ("cd", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0)); EXPECT_STREQ("ab", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2)); EXPECT_STREQ("cd", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1)); EXPECT_STREQ("bc", buffer); EXPECT_EQ(2u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0)); EXPECT_STREQ("ab", buffer); EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1)); EXPECT_STREQ("bb", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1)); EXPECT_STREQ("bc", buffer); EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 3)); EXPECT_STREQ("de", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(1u, f->ReadAt(buffer, 1, 2)); EXPECT_STREQ("ce", buffer); EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1)); EXPECT_STREQ("be", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; } TEST(RRawFile, Mmap) { std::uint64_t mapdOffset; std::unique_ptr<RRawFileMock> m(new RRawFileMock("", RRawFile::ROptions())); EXPECT_FALSE(m->GetFeatures() & RRawFile::kFeatureHasMmap); EXPECT_THROW(m->Map(1, 0, mapdOffset), std::runtime_error); EXPECT_THROW(m->Unmap(this, 1), std::runtime_error); void *region; FileRaii basicGuard("test_rawfile_mmap", "foo"); auto f = RRawFile::Create("test_rawfile_mmap"); if (!(f->GetFeatures() & RRawFile::kFeatureHasMmap)) return; region = f->Map(2, 1, mapdOffset); auto innerOffset = 1 - mapdOffset; ASSERT_NE(region, nullptr); EXPECT_EQ("oo", std::string(reinterpret_cast<char *>(region) + innerOffset, 2)); auto mapdLength = 2 + innerOffset; f->Unmap(region, mapdLength); } <commit_msg>[io] make RRawFile test pass for the unimplemented io_uring ReadV<commit_after>#include "RConfigure.h" #include "ROOT/RRawFile.hxx" #include "ROOT/RMakeUnique.hxx" #include <algorithm> #include <cstdio> #include <cstring> #include <fstream> #include <memory> #include <stdexcept> #include <string> #include <utility> #include "gtest/gtest.h" #include "gmock/gmock.h" using RRawFile = ROOT::Internal::RRawFile; namespace { /** * An RAII wrapper around an open temporary file on disk. It cleans up the guarded file when the wrapper object * goes out of scope. */ class FileRaii { private: std::string fPath; public: FileRaii(const std::string &path, const std::string &content) : fPath(path) { std::ofstream ostrm(path, std::ios::binary | std::ios::out | std::ios::trunc); ostrm << content; } FileRaii(const FileRaii&) = delete; FileRaii& operator=(const FileRaii&) = delete; ~FileRaii() { std::remove(fPath.c_str()); } }; /** * A minimal RRawFile implementation that serves data from a string. It keeps a counter of the number of read calls * to help veryfing the buffer logic in the base class. */ class RRawFileMock : public RRawFile { public: std::string fContent; unsigned fNumReadAt; RRawFileMock(const std::string &content, RRawFile::ROptions options) : RRawFile("", options), fContent(content), fNumReadAt(0) { } std::unique_ptr<RRawFile> Clone() const final { return std::make_unique<RRawFileMock>(fContent, fOptions); } void OpenImpl() final { } size_t ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset) final { fNumReadAt++; if (offset > fContent.length()) return 0; auto slice = fContent.substr(offset, nbytes); memcpy(buffer, slice.data(), slice.length()); return slice.length(); } std::uint64_t GetSizeImpl() final { return fContent.size(); } int GetFeatures() const final { return kFeatureHasSize; } }; } // anonymous namespace TEST(RRawFile, Empty) { FileRaii emptyGuard("testEmpty", ""); auto f = RRawFile::Create("testEmpty"); EXPECT_TRUE(f->GetFeatures() & RRawFile::kFeatureHasSize); EXPECT_EQ(0u, f->GetSize()); EXPECT_EQ(0u, f->Read(nullptr, 0)); EXPECT_EQ(0u, f->ReadAt(nullptr, 0, 1)); std::string line; EXPECT_FALSE(f->Readln(line)); } TEST(RRawFile, Basic) { FileRaii basicGuard("testBasic", "foo\nbar"); auto f = RRawFile::Create("testBasic"); EXPECT_EQ(7u, f->GetSize()); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("foo", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("bar", line.c_str()); EXPECT_FALSE(f->Readln(line)); auto clone = f->Clone(); /// file pointer is reset by clone EXPECT_TRUE(clone->Readln(line)); EXPECT_STREQ("foo", line.c_str()); auto f2 = RRawFile::Create("NoSuchFile"); EXPECT_THROW(f2->Readln(line), std::runtime_error); auto f3 = RRawFile::Create("FiLE://testBasic"); EXPECT_EQ(7u, f3->GetSize()); EXPECT_THROW(RRawFile::Create("://testBasic"), std::runtime_error); EXPECT_THROW(RRawFile::Create("Communicator://Kirk"), std::runtime_error); } TEST(RRawFile, Remote) { #ifdef R__HAS_DAVIX auto f = RRawFile::Create("http://root.cern.ch/files/davix.test"); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("Hello, World", line.c_str()); #else EXPECT_THROW(RRawFile::Create("http://root.cern.ch/files/davix.test"), std::runtime_error); #endif } TEST(RRawFile, Readln) { FileRaii linebreakGuard("testLinebreak", "foo\r\none\nline\r\n\r\n"); auto f = RRawFile::Create("testLinebreak"); std::string line; EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("foo", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_STREQ("one\nline", line.c_str()); EXPECT_TRUE(f->Readln(line)); EXPECT_TRUE(line.empty()); EXPECT_FALSE(f->Readln(line)); } TEST(RRawFile, ReadV) { FileRaii readvGuard("test_rawfile_readv", "Hello, World"); auto f = RRawFile::Create("test_rawfile_readv"); char buffer[2]; buffer[0] = buffer[1] = 0; RRawFile::RIOVec iovec[2]; iovec[0].fBuffer = &buffer[0]; iovec[0].fOffset = 0; iovec[0].fSize = 1; iovec[1].fBuffer = &buffer[1]; iovec[1].fOffset = 11; iovec[1].fSize = 2; #ifdef R__HAS_URING try { f->ReadV(iovec, 2); FAIL() << "ReadV unimplemented for io_uring backend, should throw"; } catch (const std::runtime_error& err) { EXPECT_THAT(err.what(), testing::HasSubstr("io_uring ReadV unimplemented!")); } #else f->ReadV(iovec, 2); EXPECT_EQ(1U, iovec[0].fOutBytes); EXPECT_EQ(1U, iovec[1].fOutBytes); EXPECT_EQ('H', buffer[0]); EXPECT_EQ('d', buffer[1]); #endif } TEST(RRawFile, SplitUrl) { EXPECT_STREQ("C:\\Data\\events.root", RRawFile::GetLocation("C:\\Data\\events.root").c_str()); EXPECT_STREQ("///many/slashes", RRawFile::GetLocation("///many/slashes").c_str()); EXPECT_STREQ("/many/slashes", RRawFile::GetLocation(":///many/slashes").c_str()); EXPECT_STREQ("file", RRawFile::GetTransport("/foo").c_str()); EXPECT_STREQ("http", RRawFile::GetTransport("http://").c_str()); EXPECT_STREQ("", RRawFile::GetLocation("http://").c_str()); EXPECT_STREQ("http", RRawFile::GetTransport("http://file:///bar").c_str()); } TEST(RRawFile, ReadDirect) { FileRaii directGuard("testDirect", "abc"); char buffer; RRawFile::ROptions options; options.fBlockSize = 0; auto f = RRawFile::Create("testDirect"); EXPECT_EQ(0u, f->Read(&buffer, 0)); EXPECT_EQ(1u, f->Read(&buffer, 1)); EXPECT_EQ('a', buffer); EXPECT_EQ(1u, f->ReadAt(&buffer, 1, 2)); EXPECT_EQ('c', buffer); } TEST(RRawFile, ReadBuffered) { char buffer[8]; RRawFile::ROptions options; options.fBlockSize = 2; std::unique_ptr<RRawFileMock> f(new RRawFileMock("abcdef", options)); buffer[3] = '\0'; EXPECT_EQ(3u, f->ReadAt(buffer, 3, 1)); EXPECT_STREQ("bcd", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; buffer[2] = '\0'; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2)); EXPECT_STREQ("cd", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0)); EXPECT_STREQ("ab", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 2)); EXPECT_STREQ("cd", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1)); EXPECT_STREQ("bc", buffer); EXPECT_EQ(2u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 0)); EXPECT_STREQ("ab", buffer); EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1)); EXPECT_STREQ("bb", buffer); EXPECT_EQ(2u, f->ReadAt(buffer, 2, 1)); EXPECT_STREQ("bc", buffer); EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(2u, f->ReadAt(buffer, 2, 3)); EXPECT_STREQ("de", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(1u, f->ReadAt(buffer, 1, 2)); EXPECT_STREQ("ce", buffer); EXPECT_EQ(0u, f->fNumReadAt); f->fNumReadAt = 0; EXPECT_EQ(1u, f->ReadAt(buffer, 1, 1)); EXPECT_STREQ("be", buffer); EXPECT_EQ(1u, f->fNumReadAt); f->fNumReadAt = 0; } TEST(RRawFile, Mmap) { std::uint64_t mapdOffset; std::unique_ptr<RRawFileMock> m(new RRawFileMock("", RRawFile::ROptions())); EXPECT_FALSE(m->GetFeatures() & RRawFile::kFeatureHasMmap); EXPECT_THROW(m->Map(1, 0, mapdOffset), std::runtime_error); EXPECT_THROW(m->Unmap(this, 1), std::runtime_error); void *region; FileRaii basicGuard("test_rawfile_mmap", "foo"); auto f = RRawFile::Create("test_rawfile_mmap"); if (!(f->GetFeatures() & RRawFile::kFeatureHasMmap)) return; region = f->Map(2, 1, mapdOffset); auto innerOffset = 1 - mapdOffset; ASSERT_NE(region, nullptr); EXPECT_EQ("oo", std::string(reinterpret_cast<char *>(region) + innerOffset, 2)); auto mapdLength = 2 + innerOffset; f->Unmap(region, mapdLength); } <|endoftext|>
<commit_before>#include <string.h> #include <fstream> #include <iostream> #include <string> #include <complex> #include <math.h> #include <set> #include <vector> #include <map> #include <queue> #include <stdio.h> #include <stack> #include <algorithm> #include <list> #include <ctime> #include <memory.h> #include <ctime> #include <assert.h> #define pi 3.14159 #define mod 1000000007 using namespace std; int gcd(int a, int b) { if(b == 0) { return a; } else { return gcd(b , a%b); } } int main() { int a,b,n,token=0,flag=0; scanf("%d%d%d",&a,&b,&n); while(1) { if(token == 0) { flag = gcd(a,n); n = n - flag; token = 1; } else { flag = gcd(b,n); n = n - flag; token = 0; } if(n <= 0) { break; } } if(token == 0) { printf("1"); } else { printf("0"); } return 0; } // function gcd(a, b) // if b = 0 // return a; // else // return gcd(b, a mod b); <commit_msg>Delete Epic.Game.cpp<commit_after><|endoftext|>
<commit_before>#include "stdafx.h" // Other crap #include <SADXModLoader.h> #include <limits.h> #include "minmax.h" // This namespace #include "input.h" #include "rumble.h" #include "DreamPad.h" // TODO: mouse buttons // TODO: fix alt+f4 struct KeyboardStick : NJS_POINT2I { Uint32 directions; void update() { auto horizontal = directions & (Buttons_Left | Buttons_Right); if (horizontal == Buttons_Left) { x = -SHRT_MAX; } else if (horizontal == Buttons_Right) { x = SHRT_MAX; } else { x = 0; } auto vertical = directions & (Buttons_Up | Buttons_Down); if (vertical == Buttons_Up) { y = -SHRT_MAX; } else if (vertical == Buttons_Down) { y = SHRT_MAX; } else { y = 0; } } }; struct AnalogThing { Angle angle; float magnitude; }; DataArray(AnalogThing, NormalizedAnalogs, 0x03B0E7A0, 8); DataPointer(int, MouseMode, 0x03B0EAE0); DataPointer(int, CursorY, 0x03B0E990); DataPointer(int, CursorX, 0x03B0E994); DataPointer(int, CursorMagnitude, 0x03B0E998); DataPointer(int, CursorCos, 0x03B0E99C); DataPointer(int, CursorSin, 0x03B0E9A0); static bool mouse_update = false; static NJS_POINT2I cursor = {}; static KeyboardStick sticks[2] = {}; static uint32 add_buttons = 0; inline void set_button(Uint32& i, Uint32 value, bool key_down) { if (key_down) { i |= value; } else { i &= ~value; } } static void UpdateKeyboardButtons(Uint32 key, bool down) { switch (key) { default: break; case UINT_MAX: set_button(add_buttons, key, down); break; case 'X': case VK_SPACE: set_button(add_buttons, Buttons_A, down); break; case 'Z': set_button(add_buttons, Buttons_B, down); break; case 'A': set_button(add_buttons, Buttons_X, down); break; case 'S': set_button(add_buttons, Buttons_Y, down); break; case 'Q': set_button(add_buttons, Buttons_L, down); break; case 'W': set_button(add_buttons, Buttons_R, down); break; case VK_RETURN: set_button(add_buttons, Buttons_Start, down); break; case 'D': set_button(add_buttons, Buttons_Z, down); break; case 'C': set_button(add_buttons, Buttons_C, down); break; case 'E': set_button(add_buttons, Buttons_D, down); break; // D-Pad case VK_NUMPAD8: set_button(add_buttons, Buttons_Up, down); break; case VK_NUMPAD5: set_button(add_buttons, Buttons_Down, down); break; case VK_NUMPAD4: set_button(add_buttons, Buttons_Left, down); break; case VK_NUMPAD6: set_button(add_buttons, Buttons_Right, down); break; // Left stick case VK_UP: set_button(sticks[0].directions, Buttons_Up, down); break; case VK_DOWN: set_button(sticks[0].directions, Buttons_Down, down); break; case VK_LEFT: set_button(sticks[0].directions, Buttons_Left, down); break; case VK_RIGHT: set_button(sticks[0].directions, Buttons_Right, down); break; // Right stick case 'I': set_button(sticks[1].directions, Buttons_Up, down); break; case 'K': set_button(sticks[1].directions, Buttons_Down, down); break; case 'J': set_button(sticks[1].directions, Buttons_Left, down); break; case 'L': set_button(sticks[1].directions, Buttons_Right, down); break; } } static void UpdateCursor(Sint32 xrel, Sint32 yrel) { if (!mouse_update) { return; } CursorX = clamp(CursorX + xrel, -200, 200); CursorY = clamp(CursorY + yrel, -200, 200); auto& x = CursorX; auto& y = CursorY; auto m = x * x + y * y; if (m <= 625) { CursorMagnitude = 0; return; } CursorMagnitude = m / 361; if (CursorMagnitude >= 1) { if (CursorMagnitude > 120) { CursorMagnitude = 127; } } else { CursorMagnitude = 1; } njPushMatrix((NJS_MATRIX*)0x0389D650); auto r = (Angle)(atan2((double)x, (double)y) * 65536.0 * 0.1591549762031479); if (r) { njRotateZ(nullptr, r); } NJS_VECTOR v = { 0.0f, (float)CursorMagnitude * 1.2f, 0.0f }; njCalcVector(nullptr, &v, &v); CursorCos = (int)v.x; CursorSin = (int)v.y; auto& p = cursor; p.x = (Sint16)clamp((int)(-v.x / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX); p.y = (Sint16)clamp((int)(v.y / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX); njPopMatrix(1); } static void ResetCursor() { CursorMagnitude = 0; CursorCos = 0; CursorSin = 0; CursorX = 0; CursorY = 0; cursor = {}; mouse_update = false; } static void UpdateMouseButtons(Uint32 button, bool down) { switch (button) { case VK_LBUTTON: if (!down && !MouseMode) { ResetCursor(); } mouse_update = down; break; case VK_MBUTTON: case VK_RBUTTON: break; default: break; } } DataPointer(HWND, hWnd, 0x3D0FD30); WNDPROC lpPrevWndFunc = nullptr; namespace input { ControllerData RawInput[GAMEPAD_COUNT]; bool _ControllerEnabled[GAMEPAD_COUNT]; bool debug = false; LRESULT __stdcall PollKeyboardMouse(HWND handle, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_KEYDOWN: case WM_KEYUP: if (wParam <= VK_XBUTTON2) { UpdateMouseButtons(wParam, Msg == WM_KEYDOWN); } else { UpdateKeyboardButtons(wParam, Msg == WM_KEYDOWN); } break; case WM_MOUSEMOVE: break; case WM_MOUSEWHEEL: break; default: break; } return CallWindowProc(lpPrevWndFunc, handle, Msg, wParam, lParam); } void HookWndProc() { if (lpPrevWndFunc == nullptr) { lpPrevWndFunc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)PollKeyboardMouse); } } void PollControllers() { HookWndProc(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { default: break; case SDL_CONTROLLERDEVICEADDED: { int which = event.cdevice.which; for (uint i = 0; i < GAMEPAD_COUNT; i++) { // Checking for both in cases like the DualShock 4 and DS4Windows where the controller might be // "connected" twice with the same ID. DreamPad::Open automatically closes if already open. if (!DreamPad::Controllers[i].Connected() || DreamPad::Controllers[i].ControllerID() == which) { DreamPad::Controllers[i].Open(which); break; } } break; } case SDL_CONTROLLERDEVICEREMOVED: { int which = event.cdevice.which; for (uint i = 0; i < GAMEPAD_COUNT; i++) { if (DreamPad::Controllers[i].ControllerID() == which) { DreamPad::Controllers[i].Close(); break; } } break; } #if 0 case SDL_MOUSEMOTION: { UpdateCursor(event.motion.xrel, event.motion.yrel); break; } #endif } } sticks[0].update(); sticks[1].update(); if (sticks[0].x || sticks[0].y) { ResetCursor(); } else { (NJS_POINT2I)sticks[0] = cursor; } for (uint i = 0; i < GAMEPAD_COUNT; i++) { DreamPad& dpad = DreamPad::Controllers[i]; auto buttons = !i ? add_buttons : 0; NJS_POINT2I* ls = !i ? &sticks[0] : nullptr; NJS_POINT2I* rs = !i ? &sticks[1] : nullptr; dpad.Poll(buttons, ls, rs); dpad.Copy(RawInput[i]); // Compatibility for mods who use ControllersRaw directly. // This will only copy the first four controllers. if (i < ControllersRaw_Length) { ControllersRaw[i] = RawInput[i]; } #ifdef EXTENDED_BUTTONS if (debug && RawInput[i].HeldButtons & Buttons_C) { ControllerData* pad = &RawInput[i]; Motor m = DreamPad::Controllers[i].GetActiveMotor(); DisplayDebugStringFormatted(NJM_LOCATION(0, 8 + (3 * i)), "P%d B: %08X LT/RT: %03d/%03d V: %d%d", (i + 1), pad->HeldButtons, pad->LTriggerPressure, pad->RTriggerPressure, (m & Motor::Large), (m & Motor::Small) >> 1); DisplayDebugStringFormatted(NJM_LOCATION(4, 9 + (3 * i)), "LS: % 4d/% 4d RS: % 4d/% 4d", pad->LeftStickX, pad->LeftStickY, pad->RightStickX, pad->RightStickY); if (pad->HeldButtons & Buttons_Z) { int pressed = pad->PressedButtons; if (pressed & Buttons_Up) { dpad.settings.rumbleFactor += 0.125f; } else if (pressed & Buttons_Down) { dpad.settings.rumbleFactor -= 0.125f; } else if (pressed & Buttons_Left) { rumble::RumbleA(i, 0); } else if (pressed & Buttons_Right) { rumble::RumbleB(i, 7, 59, 6); } DisplayDebugStringFormatted(NJM_LOCATION(4, 10 + (3 * i)), "Rumble factor (U/D): %f (L/R to test)", dpad.settings.rumbleFactor); } } #endif } } static void FixAnalogs() { if (!ControlEnabled) { return; } for (uint i = 0; i < GAMEPAD_COUNT; i++) { if (!_ControllerEnabled[i]) { continue; } const DreamPad& dreamPad = DreamPad::Controllers[i]; if (dreamPad.Connected()) { const ControllerData& pad = dreamPad.DreamcastData(); // SADX's internal deadzone is 12 of 127. It doesn't set the relative forward direction // unless this is exceeded in WriteAnalogs(), so the analog shouldn't be set otherwise. if (abs(pad.LeftStickX) > 12 || abs(pad.LeftStickY) > 12) { NormalizedAnalogs[i].magnitude = dreamPad.NormalizedL(); } } } } void __declspec(naked) WriteAnalogs_Hook() { __asm { call FixAnalogs ret } } static void RedirectRawControllers() { for (uint i = 0; i < GAMEPAD_COUNT; i++) { ControllerPointers[i] = &RawInput[i]; } } void __declspec(naked) RedirectRawControllers_Hook() { __asm { call RedirectRawControllers ret } } void EnableController_hook(Uint8 index) { // default behavior if (index > 1) { _ControllerEnabled[0] = true; _ControllerEnabled[1] = true; } if (index > GAMEPAD_COUNT) { for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++) { EnableController_hook(i); } } else { _ControllerEnabled[index] = true; } } void DisableController_hook(Uint8 index) { // default behavior if (index > 1) { _ControllerEnabled[0] = false; _ControllerEnabled[1] = false; } if (index > GAMEPAD_COUNT) { for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++) { DisableController_hook(i); } } else { _ControllerEnabled[index] = false; } } } <commit_msg>oops I forgot the mouse<commit_after>#include "stdafx.h" // Other crap #include <SADXModLoader.h> #include <limits.h> #include "minmax.h" // This namespace #include "input.h" #include "rumble.h" #include "DreamPad.h" // TODO: mouse buttons // TODO: fix alt+f4 struct KeyboardStick : NJS_POINT2I { Uint32 directions; void update() { auto horizontal = directions & (Buttons_Left | Buttons_Right); if (horizontal == Buttons_Left) { x = -SHRT_MAX; } else if (horizontal == Buttons_Right) { x = SHRT_MAX; } else { x = 0; } auto vertical = directions & (Buttons_Up | Buttons_Down); if (vertical == Buttons_Up) { y = -SHRT_MAX; } else if (vertical == Buttons_Down) { y = SHRT_MAX; } else { y = 0; } } }; struct AnalogThing { Angle angle; float magnitude; }; DataArray(AnalogThing, NormalizedAnalogs, 0x03B0E7A0, 8); DataPointer(int, MouseMode, 0x03B0EAE0); DataPointer(int, CursorY, 0x03B0E990); DataPointer(int, CursorX, 0x03B0E994); DataPointer(int, CursorMagnitude, 0x03B0E998); DataPointer(int, CursorCos, 0x03B0E99C); DataPointer(int, CursorSin, 0x03B0E9A0); static bool mouse_update = false; static NJS_POINT2I cursor = {}; static KeyboardStick sticks[2] = {}; static uint32 add_buttons = 0; inline void set_button(Uint32& i, Uint32 value, bool key_down) { if (key_down) { i |= value; } else { i &= ~value; } } static void UpdateKeyboardButtons(Uint32 key, bool down) { switch (key) { default: break; case UINT_MAX: set_button(add_buttons, key, down); break; case 'X': case VK_SPACE: set_button(add_buttons, Buttons_A, down); break; case 'Z': set_button(add_buttons, Buttons_B, down); break; case 'A': set_button(add_buttons, Buttons_X, down); break; case 'S': set_button(add_buttons, Buttons_Y, down); break; case 'Q': set_button(add_buttons, Buttons_L, down); break; case 'W': set_button(add_buttons, Buttons_R, down); break; case VK_RETURN: set_button(add_buttons, Buttons_Start, down); break; case 'D': set_button(add_buttons, Buttons_Z, down); break; case 'C': set_button(add_buttons, Buttons_C, down); break; case 'E': set_button(add_buttons, Buttons_D, down); break; // D-Pad case VK_NUMPAD8: set_button(add_buttons, Buttons_Up, down); break; case VK_NUMPAD5: set_button(add_buttons, Buttons_Down, down); break; case VK_NUMPAD4: set_button(add_buttons, Buttons_Left, down); break; case VK_NUMPAD6: set_button(add_buttons, Buttons_Right, down); break; // Left stick case VK_UP: set_button(sticks[0].directions, Buttons_Up, down); break; case VK_DOWN: set_button(sticks[0].directions, Buttons_Down, down); break; case VK_LEFT: set_button(sticks[0].directions, Buttons_Left, down); break; case VK_RIGHT: set_button(sticks[0].directions, Buttons_Right, down); break; // Right stick case 'I': set_button(sticks[1].directions, Buttons_Up, down); break; case 'K': set_button(sticks[1].directions, Buttons_Down, down); break; case 'J': set_button(sticks[1].directions, Buttons_Left, down); break; case 'L': set_button(sticks[1].directions, Buttons_Right, down); break; } } static void UpdateCursor(Sint32 xrel, Sint32 yrel) { if (!mouse_update) { return; } CursorX = clamp(CursorX + xrel, -200, 200); CursorY = clamp(CursorY + yrel, -200, 200); auto& x = CursorX; auto& y = CursorY; auto m = x * x + y * y; if (m <= 625) { CursorMagnitude = 0; return; } CursorMagnitude = m / 361; if (CursorMagnitude >= 1) { if (CursorMagnitude > 120) { CursorMagnitude = 127; } } else { CursorMagnitude = 1; } njPushMatrix((NJS_MATRIX*)0x0389D650); auto r = (Angle)(atan2((double)x, (double)y) * 65536.0 * 0.1591549762031479); if (r) { njRotateZ(nullptr, r); } NJS_VECTOR v = { 0.0f, (float)CursorMagnitude * 1.2f, 0.0f }; njCalcVector(nullptr, &v, &v); CursorCos = (int)v.x; CursorSin = (int)v.y; auto& p = cursor; p.x = (Sint16)clamp((int)(-v.x / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX); p.y = (Sint16)clamp((int)(v.y / 128.0f * SHRT_MAX), -SHRT_MAX, SHRT_MAX); njPopMatrix(1); } static void ResetCursor() { CursorMagnitude = 0; CursorCos = 0; CursorSin = 0; CursorX = 0; CursorY = 0; cursor = {}; mouse_update = false; } static void UpdateMouseButtons(Uint32 button, bool down) { switch (button) { case VK_LBUTTON: if (!down && !MouseMode) { ResetCursor(); } mouse_update = down; break; case VK_MBUTTON: case VK_RBUTTON: break; default: break; } } DataPointer(HWND, hWnd, 0x3D0FD30); static WNDPROC lpPrevWndFunc = nullptr; static Sint16 mouse_x = 0; static Sint16 mouse_y = 0; namespace input { ControllerData RawInput[GAMEPAD_COUNT]; bool _ControllerEnabled[GAMEPAD_COUNT]; bool debug = false; LRESULT __stdcall PollKeyboardMouse(HWND handle, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_LBUTTONDOWN: case WM_LBUTTONUP: UpdateMouseButtons(VK_LBUTTON, Msg == WM_LBUTTONDOWN); break; case WM_RBUTTONDOWN: case WM_RBUTTONUP: UpdateMouseButtons(VK_RBUTTON, Msg == WM_RBUTTONDOWN); break; case WM_MBUTTONDOWN: case WM_MBUTTONUP: UpdateMouseButtons(VK_MBUTTON, Msg == WM_MBUTTONDOWN); break; case WM_SYSKEYUP: case WM_SYSKEYDOWN: case WM_KEYDOWN: case WM_KEYUP: UpdateKeyboardButtons(wParam, Msg == WM_KEYDOWN || Msg == WM_SYSKEYDOWN); break; case WM_MOUSEMOVE: { auto x = (short)(lParam & 0xFFFF); auto y = (short)(lParam >> 16); UpdateCursor(x - mouse_x, y - mouse_y); mouse_x = x; mouse_y = y; break; } case WM_MOUSEWHEEL: break; default: break; } return CallWindowProc(lpPrevWndFunc, handle, Msg, wParam, lParam); } void HookWndProc() { if (lpPrevWndFunc == nullptr) { lpPrevWndFunc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)PollKeyboardMouse); } } void PollControllers() { HookWndProc(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { default: break; case SDL_CONTROLLERDEVICEADDED: { int which = event.cdevice.which; for (uint i = 0; i < GAMEPAD_COUNT; i++) { // Checking for both in cases like the DualShock 4 and DS4Windows where the controller might be // "connected" twice with the same ID. DreamPad::Open automatically closes if already open. if (!DreamPad::Controllers[i].Connected() || DreamPad::Controllers[i].ControllerID() == which) { DreamPad::Controllers[i].Open(which); break; } } break; } case SDL_CONTROLLERDEVICEREMOVED: { int which = event.cdevice.which; for (uint i = 0; i < GAMEPAD_COUNT; i++) { if (DreamPad::Controllers[i].ControllerID() == which) { DreamPad::Controllers[i].Close(); break; } } break; } } } sticks[0].update(); sticks[1].update(); if (sticks[0].x || sticks[0].y) { ResetCursor(); } else { *(NJS_POINT2I*)&sticks[0] = cursor; } for (uint i = 0; i < GAMEPAD_COUNT; i++) { DreamPad& dpad = DreamPad::Controllers[i]; auto buttons = !i ? add_buttons : 0; NJS_POINT2I* ls = !i ? &sticks[0] : nullptr; NJS_POINT2I* rs = !i ? &sticks[1] : nullptr; dpad.Poll(buttons, ls, rs); dpad.Copy(RawInput[i]); // Compatibility for mods who use ControllersRaw directly. // This will only copy the first four controllers. if (i < ControllersRaw_Length) { ControllersRaw[i] = RawInput[i]; } #ifdef EXTENDED_BUTTONS if (debug && RawInput[i].HeldButtons & Buttons_C) { ControllerData* pad = &RawInput[i]; Motor m = DreamPad::Controllers[i].GetActiveMotor(); DisplayDebugStringFormatted(NJM_LOCATION(0, 8 + (3 * i)), "P%d B: %08X LT/RT: %03d/%03d V: %d%d", (i + 1), pad->HeldButtons, pad->LTriggerPressure, pad->RTriggerPressure, (m & Motor::Large), (m & Motor::Small) >> 1); DisplayDebugStringFormatted(NJM_LOCATION(4, 9 + (3 * i)), "LS: % 4d/% 4d RS: % 4d/% 4d", pad->LeftStickX, pad->LeftStickY, pad->RightStickX, pad->RightStickY); if (pad->HeldButtons & Buttons_Z) { int pressed = pad->PressedButtons; if (pressed & Buttons_Up) { dpad.settings.rumbleFactor += 0.125f; } else if (pressed & Buttons_Down) { dpad.settings.rumbleFactor -= 0.125f; } else if (pressed & Buttons_Left) { rumble::RumbleA(i, 0); } else if (pressed & Buttons_Right) { rumble::RumbleB(i, 7, 59, 6); } DisplayDebugStringFormatted(NJM_LOCATION(4, 10 + (3 * i)), "Rumble factor (U/D): %f (L/R to test)", dpad.settings.rumbleFactor); } } #endif } } static void FixAnalogs() { if (!ControlEnabled) { return; } for (uint i = 0; i < GAMEPAD_COUNT; i++) { if (!_ControllerEnabled[i]) { continue; } const DreamPad& dreamPad = DreamPad::Controllers[i]; if (dreamPad.Connected()) { const ControllerData& pad = dreamPad.DreamcastData(); // SADX's internal deadzone is 12 of 127. It doesn't set the relative forward direction // unless this is exceeded in WriteAnalogs(), so the analog shouldn't be set otherwise. if (abs(pad.LeftStickX) > 12 || abs(pad.LeftStickY) > 12) { NormalizedAnalogs[i].magnitude = dreamPad.NormalizedL(); } } } } void __declspec(naked) WriteAnalogs_Hook() { __asm { call FixAnalogs ret } } static void RedirectRawControllers() { for (uint i = 0; i < GAMEPAD_COUNT; i++) { ControllerPointers[i] = &RawInput[i]; } } void __declspec(naked) RedirectRawControllers_Hook() { __asm { call RedirectRawControllers ret } } void EnableController_hook(Uint8 index) { // default behavior if (index > 1) { _ControllerEnabled[0] = true; _ControllerEnabled[1] = true; } if (index > GAMEPAD_COUNT) { for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++) { EnableController_hook(i); } } else { _ControllerEnabled[index] = true; } } void DisableController_hook(Uint8 index) { // default behavior if (index > 1) { _ControllerEnabled[0] = false; _ControllerEnabled[1] = false; } if (index > GAMEPAD_COUNT) { for (Uint32 i = 0; i < min(index, (Uint8)GAMEPAD_COUNT); i++) { DisableController_hook(i); } } else { _ControllerEnabled[index] = false; } } } <|endoftext|>
<commit_before> #include <assert.h> #include <thread> #include "LinkedList.hpp" void test0() { LinkedList<int> l; l._checkSanity(); auto item = l.push_back(); item->value = 42; item = NULL; l._checkSanity(); assert(l.size() == 1); auto ret = l.pop_front(); assert(ret); assert(ret->value == 42); ret = NULL; assert(l.empty()); assert(l.size() == 0); l._checkSanity(); } void test1() { LinkedList<int> l; l._checkSanity(); for(int i = 0; i < 100; ++i) { auto item = l.push_back(); l._checkSanity(); item->value = i; } for(int i = 0; i < 100; ++i) { auto ret = l.pop_front(); l._checkSanity(); assert(ret); assert(ret->value == i); } assert(l.empty()); } void test2() { LinkedList<int> l; l._checkSanity(); auto producer = [&l](){ for(int i = 0; i < 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } }; auto consumer = [&l](){ for(int i = 0; i < 100; ++i) { while(l.empty()); // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } }; for(int i = 0; i < 1000; ++i) { std::thread t1(producer), t2(consumer); t1.join(); t2.join(); assert(l.empty()); l._checkSanity(); } } int main() { test0(); test1(); test2(); } <commit_msg>more testing<commit_after> #include <assert.h> #include <thread> #include "LinkedList.hpp" void test0() { LinkedList<int> l; assert(l.empty()); l._checkSanity(); auto item = l.push_back(); item->value = 42; item = NULL; l._checkSanity(); assert(!l.empty()); assert(l.size() == 1); auto ret = l.pop_front(); assert(ret); assert(ret->value == 42); ret = NULL; assert(l.empty()); assert(l.size() == 0); l._checkSanity(); } void test1() { LinkedList<int> l; l._checkSanity(); for(int i = 0; i < 100; ++i) { auto item = l.push_back(); l._checkSanity(); item->value = i; } assert(!l.empty()); assert(l.size() == 100); for(int i = 0; i < 100; ++i) { auto ret = l.pop_front(); l._checkSanity(); assert(ret); assert(ret->value == i); } assert(l.empty()); } void test2() { LinkedList<int> l; l._checkSanity(); auto producer = [&l](){ for(int i = 0; i < 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } }; auto consumer = [&l](){ for(int i = 0; i < 100; ++i) { while(l.empty()); // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } }; for(int i = 0; i < 1000; ++i) { std::thread t1(producer), t2(consumer); t1.join(); t2.join(); assert(l.empty()); l._checkSanity(); } } int main() { test0(); test1(); test2(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return NULL; } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser <commit_msg>Use the non-touch popup frame instead of NULL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return new PopupNonClientFrameView(frame); } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <thread> namespace etl { #ifdef ETL_VECTORIZE_FULL //VECTORIZE_FULL enables VECTORIZE_EXPR #ifndef ETL_VECTORIZE_EXPR #define ETL_VECTORIZE_EXPR #endif //VECTORIZE_FULL enables VECTORIZE_IMPL #ifndef ETL_VECTORIZE_IMPL #define ETL_VECTORIZE_IMPL #endif #endif //ETL_VECTORIZE_FULL //Flag to enable auto-vectorization of expressions #ifdef ETL_VECTORIZE_EXPR constexpr const bool vectorize_expr = true; #else constexpr const bool vectorize_expr = false; #endif //Flag to enable vectorized implementation of algorithms #ifdef ETL_VECTORIZE_IMPL constexpr const bool vectorize_impl = true; #else constexpr const bool vectorize_impl = false; #endif //Flag to disable the creation of temporary in expressions #ifdef ETL_NO_TEMPORARY constexpr const bool create_temporary = false; #else constexpr const bool create_temporary = true; #endif #ifdef ETL_PARALLEL constexpr const bool parallel = true; #else constexpr const bool parallel = false; #endif #ifdef ETL_PARALLEL_THREADS constexpr const std::size_t threads = ETL_PARALLEL_THREADS; #else const std::size_t threads = std::thread::hardware_concurrency(); #endif #ifdef ETL_MKL_MODE //MKL mode enables BLAS mode #ifndef ETL_BLAS_MODE #define ETL_BLAS_MODE #endif struct is_mkl_enabled : std::true_type {}; struct has_fast_fft : std::true_type {}; #else struct is_mkl_enabled : std::false_type {}; struct has_fast_fft : std::false_type {}; #endif //Flag to enable the use of CBLAS library #ifdef ETL_BLAS_MODE struct is_cblas_enabled : std::true_type {}; #else struct is_cblas_enabled : std::false_type {}; #endif #ifdef ETL_CUBLAS_MODE struct is_cublas_enabled : std::true_type {}; #else struct is_cublas_enabled : std::false_type {}; #endif #ifdef ETL_CUFFT_MODE struct is_cufft_enabled : std::true_type {}; #else struct is_cufft_enabled : std::false_type {}; #endif //Flag to perform elementwise multiplication by default (operator*) //instead of matrix(vector) multiplication #ifdef ETL_ELEMENT_WISE_MULTIPLICATION constexpr const bool is_element_wise_mul_default = true; #else constexpr const bool is_element_wise_mul_default = false; #endif //Flag to prevent division to be done by multiplication #ifdef ETL_STRICT_DIV constexpr const bool is_div_strict = true; #else constexpr const bool is_div_strict = false; #endif //Flag to enable unrolling of vectorized loops #ifdef ETL_UNROLL_VECT constexpr const bool unroll_vectorized_loops = true; #else constexpr const bool unroll_vectorized_loops = false; #endif //Flag to enable unrolling of non-vectorized loops #ifdef ETL_UNROLL_NON_VECT constexpr const bool unroll_normal_loops = true; #else constexpr const bool unroll_normal_loops = false; #endif enum class vector_mode_t { NONE, SSE3, AVX }; #ifdef __AVX__ constexpr const vector_mode_t vector_mode = vector_mode_t::AVX; #elif defined(__SSE3__) constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3; #else constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; #endif } //end of namespace etl <commit_msg>Disable parallel if only one thread is enabled<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <thread> namespace etl { #ifdef ETL_VECTORIZE_FULL //VECTORIZE_FULL enables VECTORIZE_EXPR #ifndef ETL_VECTORIZE_EXPR #define ETL_VECTORIZE_EXPR #endif //VECTORIZE_FULL enables VECTORIZE_IMPL #ifndef ETL_VECTORIZE_IMPL #define ETL_VECTORIZE_IMPL #endif #endif //ETL_VECTORIZE_FULL //Flag to enable auto-vectorization of expressions #ifdef ETL_VECTORIZE_EXPR constexpr const bool vectorize_expr = true; #else constexpr const bool vectorize_expr = false; #endif //Flag to enable vectorized implementation of algorithms #ifdef ETL_VECTORIZE_IMPL constexpr const bool vectorize_impl = true; #else constexpr const bool vectorize_impl = false; #endif //Flag to disable the creation of temporary in expressions #ifdef ETL_NO_TEMPORARY constexpr const bool create_temporary = false; #else constexpr const bool create_temporary = true; #endif #ifdef ETL_PARALLEL_THREADS constexpr const std::size_t threads = ETL_PARALLEL_THREADS; #else const std::size_t threads = std::thread::hardware_concurrency(); #endif #ifdef ETL_PARALLEL const bool parallel = threads > 1; #else constexpr const bool parallel = false; #endif #ifdef ETL_MKL_MODE //MKL mode enables BLAS mode #ifndef ETL_BLAS_MODE #define ETL_BLAS_MODE #endif struct is_mkl_enabled : std::true_type {}; struct has_fast_fft : std::true_type {}; #else struct is_mkl_enabled : std::false_type {}; struct has_fast_fft : std::false_type {}; #endif //Flag to enable the use of CBLAS library #ifdef ETL_BLAS_MODE struct is_cblas_enabled : std::true_type {}; #else struct is_cblas_enabled : std::false_type {}; #endif #ifdef ETL_CUBLAS_MODE struct is_cublas_enabled : std::true_type {}; #else struct is_cublas_enabled : std::false_type {}; #endif #ifdef ETL_CUFFT_MODE struct is_cufft_enabled : std::true_type {}; #else struct is_cufft_enabled : std::false_type {}; #endif //Flag to perform elementwise multiplication by default (operator*) //instead of matrix(vector) multiplication #ifdef ETL_ELEMENT_WISE_MULTIPLICATION constexpr const bool is_element_wise_mul_default = true; #else constexpr const bool is_element_wise_mul_default = false; #endif //Flag to prevent division to be done by multiplication #ifdef ETL_STRICT_DIV constexpr const bool is_div_strict = true; #else constexpr const bool is_div_strict = false; #endif //Flag to enable unrolling of vectorized loops #ifdef ETL_UNROLL_VECT constexpr const bool unroll_vectorized_loops = true; #else constexpr const bool unroll_vectorized_loops = false; #endif //Flag to enable unrolling of non-vectorized loops #ifdef ETL_UNROLL_NON_VECT constexpr const bool unroll_normal_loops = true; #else constexpr const bool unroll_normal_loops = false; #endif enum class vector_mode_t { NONE, SSE3, AVX }; #ifdef __AVX__ constexpr const vector_mode_t vector_mode = vector_mode_t::AVX; #elif defined(__SSE3__) constexpr const vector_mode_t vector_mode = vector_mode_t::SSE3; #else constexpr const vector_mode_t vector_mode = vector_mode_t::NONE; #endif } //end of namespace etl <|endoftext|>
<commit_before>/* Rescorer.C * * Copyright (C) 2011 Marcel Schumann * * This program free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ // ---------------------------------------------------- // $Maintainer: Marcel Schumann $ // $Authors: Marcel Schumann $ // ---------------------------------------------------- #include <BALL/FORMAT/molFileFactory.h> #include <BALL/FORMAT/dockResultFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/DOCKING/COMMON/dockingAlgorithm.h> #include <BALL/DOCKING/COMMON/structurePreparer.h> #include <BALL/SCORING/FUNCTIONS/gridedMM.h> #include <BALL/SCORING/FUNCTIONS/MMScoring.h> #include <BALL/SCORING/FUNCTIONS/PBScoring.h> #include <BALL/SCORING/FUNCTIONS/gridedPLP.h> #include <BALL/SCORING/FUNCTIONS/PLPScoring.h> #include <BALL/SCORING/FUNCTIONS/rescoring3D.h> #include <BALL/SCORING/FUNCTIONS/rescoring4D.h> #include <BALL/SCORING/FUNCTIONS/rescoring1D.h> #include <BALL/SCORING/COMMON/rescorer.h> #include "version.h" using namespace BALL; int main(int argc, char* argv[]) { CommandlineParser par("SimpleRescorer", "rescore docking results", VERSION, String(__DATE__), "Rescoring"); par.registerParameter("rec", "receptor pdb-file", INFILE, true); par.registerParameter("rl", "reference-ligand", INFILE, true); par.registerParameter(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME, "configuration file", INFILE); par.registerParameter("i", "compounds to be rescored", INFILE, true); par.registerParameter("o", "rescored compounds", OUTFILE, true); par.registerParameter("write_ini", "write ini-file w/ default parameters (and don't do anything else)", OUTFILE); par.registerParameter("function", "scoring function: 'MM', 'PLP' or 'PB'", STRING); par.registerFlag("rm", "remove input file when finished"); String man = "This tool rescores docking output poses.\nA scoring function is used to evaluate the binding-free-energy of each compound. This is similar to the scoring done during docking; details depend on the config-file (if one is specified).\n\nAs input we need:\n\ * a file containing a protonated protein in pdb-format\n\ * a file containing a reference ligand. This reference ligand should be located in the binding pocket. Supported formats are mol2, sdf or drf (DockResultFile, xml-based).\n\ * a file containing the compounds that are to be rescored. Supported formats are mol2, sdf or drf (DockResultFile, xml-based). Those compound should have been docked into the specified protein.\n\nOutput of this tool is a file in the same format as the input ligand file containing all compounds with scores obtained by rescoring in form of a property 're-score'."; par.setToolManual(man); list<String> slist; slist.push_back("MM"); slist.push_back("PLP"); slist.push_back("PB"); par.setParameterRestrictions("function",slist); par.setSupportedFormats("rec","pdb"); par.setSupportedFormats("rl",MolFileFactory::getSupportedFormats()); par.setSupportedFormats(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME,"ini"); par.setSupportedFormats("i",MolFileFactory::getSupportedFormats()); par.setSupportedFormats("o","mol2,sdf,drf"); par.setSupportedFormats("write_ini","ini"); par.setOutputFormatSource("o","i"); Options default_options; ScoringFunction::getDefaultOptions(default_options); par.registerAdvancedParameters(default_options); par.setSupportedFormats("filename","ini"); par.parse(argc, argv); int status = Rescorer::runRescoring(par, true, false); if (status == 0 && par.has("rm")) { File::remove(par.get("i")); } return status; } <commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/FORMAT/molFileFactory.h> #include <BALL/FORMAT/dockResultFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/DOCKING/COMMON/dockingAlgorithm.h> #include <BALL/DOCKING/COMMON/structurePreparer.h> #include <BALL/SCORING/FUNCTIONS/gridedMM.h> #include <BALL/SCORING/FUNCTIONS/MMScoring.h> #include <BALL/SCORING/FUNCTIONS/PBScoring.h> #include <BALL/SCORING/FUNCTIONS/gridedPLP.h> #include <BALL/SCORING/FUNCTIONS/PLPScoring.h> #include <BALL/SCORING/FUNCTIONS/rescoring3D.h> #include <BALL/SCORING/FUNCTIONS/rescoring4D.h> #include <BALL/SCORING/FUNCTIONS/rescoring1D.h> #include <BALL/SCORING/COMMON/rescorer.h> #include "version.h" using namespace BALL; int main(int argc, char* argv[]) { CommandlineParser par("SimpleRescorer", "rescore docking results", VERSION, String(__DATE__), "Rescoring"); par.registerParameter("rec", "receptor pdb-file", INFILE, true); par.registerParameter("rl", "reference-ligand", INFILE, true); par.registerParameter(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME, "configuration file", INFILE); par.registerParameter("i", "compounds to be rescored", INFILE, true); par.registerParameter("o", "rescored compounds", OUTFILE, true); par.registerParameter("write_ini", "write ini-file w/ default parameters (and don't do anything else)", OUTFILE); par.registerParameter("function", "scoring function: 'MM', 'PLP' or 'PB'", STRING); par.registerFlag("rm", "remove input file when finished"); String man = "This tool rescores docking output poses.\nA scoring function is used to evaluate the binding-free-energy of each compound. This is similar to the scoring done during docking; details depend on the config-file (if one is specified).\n\nAs input we need:\n\ * a file containing a protonated protein in pdb-format\n\ * a file containing a reference ligand. This reference ligand should be located in the binding pocket. Supported formats are mol2, sdf or drf (DockResultFile, xml-based).\n\ * a file containing the compounds that are to be rescored. Supported formats are mol2, sdf or drf (DockResultFile, xml-based). Those compound should have been docked into the specified protein.\n\nOutput of this tool is a file in the same format as the input ligand file containing all compounds with scores obtained by rescoring in form of a property 're-score'."; par.setToolManual(man); list<String> slist; slist.push_back("MM"); slist.push_back("PLP"); slist.push_back("PB"); par.setParameterRestrictions("function",slist); par.setSupportedFormats("rec","pdb"); par.setSupportedFormats("rl",MolFileFactory::getSupportedFormats()); par.setSupportedFormats(DockingAlgorithm::OPTION_FILE_PARAMETER_NAME,"ini"); par.setSupportedFormats("i",MolFileFactory::getSupportedFormats()); par.setSupportedFormats("o","mol2,sdf,drf"); par.setSupportedFormats("write_ini","ini"); par.setOutputFormatSource("o","i"); Options default_options; ScoringFunction::getDefaultOptions(default_options); par.registerAdvancedParameters(default_options); par.setSupportedFormats("filename","ini"); par.parse(argc, argv); int status = Rescorer::runRescoring(par, true, false); if (status == 0 && par.has("rm")) { File::remove(par.get("i")); } return status; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // // Class to analyze ZDC data // // // ///////////////////////////////////////////////////////////// #include <TList.h> #include <TH2F.h> #include <TH1F.h> #include <TFile.h> #include <TString.h> #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" #include "AliVEvent.h" #include "AliESD.h" #include "AliESDEvent.h" #include "AliESDHeader.h" #include "AliESDInputHandler.h" #include "AliESDZDC.h" #include "AliMultiplicity.h" #include "AliAODHandler.h" #include "AliAODEvent.h" #include "AliAODVertex.h" #include "AliAODMCHeader.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliHeader.h" #include "AliAODMCParticle.h" #include "AliAnalysisTaskSE.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliPhysicsSelectionTask.h" #include "AliPhysicsSelection.h" #include "AliBackgroundSelection.h" #include "AliTriggerAnalysis.h" #include "AliCentrality.h" #include "AliAnalysisTaskZDCpp.h" ClassImp(AliAnalysisTaskZDCpp) //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(): AliAnalysisTaskSE(), fDebug(0), fIsMCInput(kFALSE), fOutput(0x0), fhTDCZNSum(0x0), fhTDCZNDiff(0x0), fhZNCSpectrum(0x0), fhZNASpectrum(0x0), fhZPCSpectrum(0x0), fhZPASpectrum(0x0), fhZEM1Spectrum(0x0), fhZEM2Spectrum(0x0), fhZNCpmc(0x0), fhZNApmc(0x0), fhZPCpmc(0x0), fhZPApmc(0x0), fhZNCCentroid(0x0), fhZNACentroid(0x0), fDebunch(0x0), fhTDCZNC(0x0), fhTDCZNA(0x0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const char *name): AliAnalysisTaskSE(name), fDebug(0), fIsMCInput(kFALSE), fOutput(0x0), fhTDCZNSum(0x0), fhTDCZNDiff(0x0), fhZNCSpectrum(0x0), fhZNASpectrum(0x0), fhZPCSpectrum(0x0), fhZPASpectrum(0x0), fhZEM1Spectrum(0x0), fhZEM2Spectrum(0x0), fhZNCpmc(0x0), fhZNApmc(0x0), fhZPCpmc(0x0), fhZPApmc(0x0), fhZNCCentroid(0x0), fhZNACentroid(0x0), fDebunch(0x0) , fhTDCZNC(0x0), fhTDCZNA(0x0) { // Output slot #1 writes into a TList container DefineOutput(1, TList::Class()); } //________________________________________________________________________ AliAnalysisTaskZDCpp& AliAnalysisTaskZDCpp::operator=(const AliAnalysisTaskZDCpp& c) { // // Assignment operator // if (this!=&c) { AliAnalysisTaskSE::operator=(c); } return *this; } //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const AliAnalysisTaskZDCpp& ana): AliAnalysisTaskSE(ana), fDebug(ana.fDebug), fIsMCInput(ana.fIsMCInput), fOutput(ana.fOutput), fhTDCZNSum(ana.fhTDCZNSum), fhTDCZNDiff(ana.fhTDCZNDiff), fhZNCSpectrum(ana.fhZNCSpectrum), fhZNASpectrum(ana.fhZNASpectrum), fhZPCSpectrum(ana.fhZPCSpectrum), fhZPASpectrum(ana.fhZPASpectrum), fhZEM1Spectrum(ana.fhZEM1Spectrum), fhZEM2Spectrum(ana.fhZEM2Spectrum), fhZNCpmc(ana.fhZNCpmc), fhZNApmc(ana.fhZNApmc), fhZPCpmc(ana.fhZPCpmc), fhZPApmc(ana.fhZPApmc), fhZNCCentroid(ana.fhZNCCentroid), fhZNACentroid(ana.fhZNACentroid), fDebunch(ana.fDebunch), fhTDCZNC(ana.fhTDCZNC), fhTDCZNA(ana.fhTDCZNA) { // // Copy Constructor // } //________________________________________________________________________ AliAnalysisTaskZDCpp::~AliAnalysisTaskZDCpp() { // Destructor if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){ delete fOutput; fOutput=0; } } //________________________________________________________________________ void AliAnalysisTaskZDCpp::UserCreateOutputObjects() { // Create the output containers fOutput = new TList; fOutput->SetOwner(); //fOutput->SetName("output"); fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,30.); fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNSum); fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.); fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNDiff); fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 2000.); fOutput->Add(fhZNCSpectrum); fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 2000.) ; fOutput->Add(fhZNASpectrum); fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 140,0., 1400.) ; fOutput->Add(fhZPCSpectrum); fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 140,0., 1400.) ; fOutput->Add(fhZPASpectrum); fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 200,0., 2500.); fOutput->Add(fhZEM1Spectrum); fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 200,0., 2500.); fOutput->Add(fhZEM2Spectrum); fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 2000.); fOutput->Add(fhZNCpmc); fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 2000.); fOutput->Add(fhZNApmc); fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",140, 0., 1400.); fOutput->Add(fhZPCpmc); fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",140, 0., 1400.); fOutput->Add(fhZPApmc); fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5); fOutput->Add(fhZNCCentroid); fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5); fOutput->Add(fhZNACentroid); fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,30); fOutput->Add(fDebunch); fhTDCZNC = new TH1F("fhTDCZNC","TDC_{ZNC}",60,-30.,30.); fhTDCZNC->GetXaxis()->SetTitle("TDC_{ZNC} (ns)"); fOutput->Add(fhTDCZNC); fhTDCZNA = new TH1F("fhTDCZNA","TDC_{ZNA}",60,-30.,30.); fhTDCZNA->GetXaxis()->SetTitle("TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNA); PostData(1, fOutput); } //________________________________________________________________________ void AliAnalysisTaskZDCpp::UserExec(Option_t */*option*/) { // Execute analysis for current event: if(fDebug>1) printf(" **** AliAnalysisTaskZDCpp::UserExec() \n"); if (!InputEvent()) { Printf("ERROR: InputEvent not available"); return; } AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent()); if(!esd) return; // Select PHYSICS events (type=7, for data) //if(!fIsMCInput && esd->GetEventType()!=7) return; // ********* MC INFO ********************************* if(fIsMCInput){ AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { Printf("ERROR: Could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("ERROR: Could not retrieve MC event"); return; } } // **************************************************** AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); AliESDZDC *esdZDC = esd->GetESDZDC(); if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){ fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy()); fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy()); fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy()); fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy()); fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.); fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.); const Double_t * towZNC = esdZDC->GetZN1TowerEnergy(); const Double_t * towZPC = esdZDC->GetZP1TowerEnergy(); const Double_t * towZNA = esdZDC->GetZN2TowerEnergy(); const Double_t * towZPA = esdZDC->GetZP2TowerEnergy(); // fhZNCpmc->Fill(towZNC[0]); fhZNApmc->Fill(towZNA[0]); fhZPCpmc->Fill(towZPC[0]); fhZPApmc->Fill(towZPA[0]); Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.}; esdZDC->GetZNCentroidInpp(xyZNC, xyZNA); fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]); fhZNACentroid->Fill(xyZNA[0], xyZNA[1]); const Double_t * towZNCLG = esdZDC->GetZN1TowerEnergyLR(); const Double_t * towZNALG = esdZDC->GetZN2TowerEnergyLR(); Double_t znclg=0., znalg=0.; for(Int_t iq=0; iq<5; iq++){ znclg += towZNCLG[iq]; znalg += towZNALG[iq]; } } Float_t tdcC=999., tdcA=999; Float_t tdcSum=999., tdcDiff=999; for(int i=0; i<4; i++){ if(esdZDC->GetZDCTDCData(esdZDC->GetZNCTDCChannel() ,i) != 0.){ tdcC = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i); fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i)); if(esdZDC->GetZDCTDCData(esdZDC->GetZNATDCChannel(),i) != 0.){ tdcA = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i); fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i)); tdcSum = tdcC+tdcA; tdcDiff = tdcC-tdcA; } } if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum); if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff); if(tdcSum!=999. && tdcDiff!=999.) fDebunch->Fill(tdcDiff, tdcSum); } PostData(1, fOutput); } //________________________________________________________________________ void AliAnalysisTaskZDCpp::Terminate(Option_t */*option*/) { // Terminate analysis // } <commit_msg>Removing unused variables<commit_after>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // // Class to analyze ZDC data // // // ///////////////////////////////////////////////////////////// #include <TList.h> #include <TH2F.h> #include <TH1F.h> #include <TFile.h> #include <TString.h> #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" #include "AliVEvent.h" #include "AliESD.h" #include "AliESDEvent.h" #include "AliESDHeader.h" #include "AliESDInputHandler.h" #include "AliESDZDC.h" #include "AliMultiplicity.h" #include "AliAODHandler.h" #include "AliAODEvent.h" #include "AliAODVertex.h" #include "AliAODMCHeader.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliHeader.h" #include "AliAODMCParticle.h" #include "AliAnalysisTaskSE.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliPhysicsSelectionTask.h" #include "AliPhysicsSelection.h" #include "AliBackgroundSelection.h" #include "AliTriggerAnalysis.h" #include "AliCentrality.h" #include "AliAnalysisTaskZDCpp.h" ClassImp(AliAnalysisTaskZDCpp) //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(): AliAnalysisTaskSE(), fDebug(0), fIsMCInput(kFALSE), fOutput(0x0), fhTDCZNSum(0x0), fhTDCZNDiff(0x0), fhZNCSpectrum(0x0), fhZNASpectrum(0x0), fhZPCSpectrum(0x0), fhZPASpectrum(0x0), fhZEM1Spectrum(0x0), fhZEM2Spectrum(0x0), fhZNCpmc(0x0), fhZNApmc(0x0), fhZPCpmc(0x0), fhZPApmc(0x0), fhZNCCentroid(0x0), fhZNACentroid(0x0), fDebunch(0x0), fhTDCZNC(0x0), fhTDCZNA(0x0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const char *name): AliAnalysisTaskSE(name), fDebug(0), fIsMCInput(kFALSE), fOutput(0x0), fhTDCZNSum(0x0), fhTDCZNDiff(0x0), fhZNCSpectrum(0x0), fhZNASpectrum(0x0), fhZPCSpectrum(0x0), fhZPASpectrum(0x0), fhZEM1Spectrum(0x0), fhZEM2Spectrum(0x0), fhZNCpmc(0x0), fhZNApmc(0x0), fhZPCpmc(0x0), fhZPApmc(0x0), fhZNCCentroid(0x0), fhZNACentroid(0x0), fDebunch(0x0) , fhTDCZNC(0x0), fhTDCZNA(0x0) { // Output slot #1 writes into a TList container DefineOutput(1, TList::Class()); } //________________________________________________________________________ AliAnalysisTaskZDCpp& AliAnalysisTaskZDCpp::operator=(const AliAnalysisTaskZDCpp& c) { // // Assignment operator // if (this!=&c) { AliAnalysisTaskSE::operator=(c); } return *this; } //________________________________________________________________________ AliAnalysisTaskZDCpp::AliAnalysisTaskZDCpp(const AliAnalysisTaskZDCpp& ana): AliAnalysisTaskSE(ana), fDebug(ana.fDebug), fIsMCInput(ana.fIsMCInput), fOutput(ana.fOutput), fhTDCZNSum(ana.fhTDCZNSum), fhTDCZNDiff(ana.fhTDCZNDiff), fhZNCSpectrum(ana.fhZNCSpectrum), fhZNASpectrum(ana.fhZNASpectrum), fhZPCSpectrum(ana.fhZPCSpectrum), fhZPASpectrum(ana.fhZPASpectrum), fhZEM1Spectrum(ana.fhZEM1Spectrum), fhZEM2Spectrum(ana.fhZEM2Spectrum), fhZNCpmc(ana.fhZNCpmc), fhZNApmc(ana.fhZNApmc), fhZPCpmc(ana.fhZPCpmc), fhZPApmc(ana.fhZPApmc), fhZNCCentroid(ana.fhZNCCentroid), fhZNACentroid(ana.fhZNACentroid), fDebunch(ana.fDebunch), fhTDCZNC(ana.fhTDCZNC), fhTDCZNA(ana.fhTDCZNA) { // // Copy Constructor // } //________________________________________________________________________ AliAnalysisTaskZDCpp::~AliAnalysisTaskZDCpp() { // Destructor if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){ delete fOutput; fOutput=0; } } //________________________________________________________________________ void AliAnalysisTaskZDCpp::UserCreateOutputObjects() { // Create the output containers fOutput = new TList; fOutput->SetOwner(); //fOutput->SetName("output"); fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,30.); fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNSum); fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.); fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNDiff); fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 2000.); fOutput->Add(fhZNCSpectrum); fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 2000.) ; fOutput->Add(fhZNASpectrum); fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 140,0., 1400.) ; fOutput->Add(fhZPCSpectrum); fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 140,0., 1400.) ; fOutput->Add(fhZPASpectrum); fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 200,0., 2500.); fOutput->Add(fhZEM1Spectrum); fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 200,0., 2500.); fOutput->Add(fhZEM2Spectrum); fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 2000.); fOutput->Add(fhZNCpmc); fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 2000.); fOutput->Add(fhZNApmc); fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",140, 0., 1400.); fOutput->Add(fhZPCpmc); fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",140, 0., 1400.); fOutput->Add(fhZPApmc); fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5); fOutput->Add(fhZNCCentroid); fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5); fOutput->Add(fhZNACentroid); fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,30); fOutput->Add(fDebunch); fhTDCZNC = new TH1F("fhTDCZNC","TDC_{ZNC}",60,-30.,30.); fhTDCZNC->GetXaxis()->SetTitle("TDC_{ZNC} (ns)"); fOutput->Add(fhTDCZNC); fhTDCZNA = new TH1F("fhTDCZNA","TDC_{ZNA}",60,-30.,30.); fhTDCZNA->GetXaxis()->SetTitle("TDC_{ZNA} (ns)"); fOutput->Add(fhTDCZNA); PostData(1, fOutput); } //________________________________________________________________________ void AliAnalysisTaskZDCpp::UserExec(Option_t */*option*/) { // Execute analysis for current event: if(fDebug>1) printf(" **** AliAnalysisTaskZDCpp::UserExec() \n"); if (!InputEvent()) { Printf("ERROR: InputEvent not available"); return; } AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent()); if(!esd) return; // Select PHYSICS events (type=7, for data) //if(!fIsMCInput && esd->GetEventType()!=7) return; // ********* MC INFO ********************************* if(fIsMCInput){ AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); if (!eventHandler) { Printf("ERROR: Could not retrieve MC event handler"); return; } AliMCEvent* mcEvent = eventHandler->MCEvent(); if (!mcEvent) { Printf("ERROR: Could not retrieve MC event"); return; } } // **************************************************** AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); AliESDZDC *esdZDC = esd->GetESDZDC(); if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){ fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy()); fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy()); fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy()); fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy()); fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.); fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.); const Double_t * towZNC = esdZDC->GetZN1TowerEnergy(); const Double_t * towZPC = esdZDC->GetZP1TowerEnergy(); const Double_t * towZNA = esdZDC->GetZN2TowerEnergy(); const Double_t * towZPA = esdZDC->GetZP2TowerEnergy(); // fhZNCpmc->Fill(towZNC[0]); fhZNApmc->Fill(towZNA[0]); fhZPCpmc->Fill(towZPC[0]); fhZPApmc->Fill(towZPA[0]); Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.}; esdZDC->GetZNCentroidInpp(xyZNC, xyZNA); fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]); fhZNACentroid->Fill(xyZNA[0], xyZNA[1]); } Float_t tdcC=999., tdcA=999; Float_t tdcSum=999., tdcDiff=999; for(int i=0; i<4; i++){ if(esdZDC->GetZDCTDCData(esdZDC->GetZNCTDCChannel() ,i) != 0.){ tdcC = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i); fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNCTDCChannel(),i)); if(esdZDC->GetZDCTDCData(esdZDC->GetZNATDCChannel(),i) != 0.){ tdcA = esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i); fhTDCZNC->Fill(esdZDC->GetZDCTDCCorrected(esdZDC->GetZNATDCChannel(),i)); tdcSum = tdcC+tdcA; tdcDiff = tdcC-tdcA; } } if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum); if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff); if(tdcSum!=999. && tdcDiff!=999.) fDebunch->Fill(tdcDiff, tdcSum); } PostData(1, fOutput); } //________________________________________________________________________ void AliAnalysisTaskZDCpp::Terminate(Option_t */*option*/) { // Terminate analysis // } <|endoftext|>
<commit_before>//===-- ASTResultSynthesizer.cpp --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdlib.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/Stmt.h" #include "clang/Parse/Parser.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include "lldb/Core/Log.h" #include "lldb/Expression/ASTResultSynthesizer.h" using namespace llvm; using namespace clang; using namespace lldb_private; ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough, TypeFromUser desired_type) : m_ast_context (NULL), m_passthrough (passthrough), m_passthrough_sema (NULL), m_sema (NULL), m_desired_type (desired_type) { if (!m_passthrough) return; m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough); } ASTResultSynthesizer::~ASTResultSynthesizer() { } void ASTResultSynthesizer::Initialize(ASTContext &Context) { m_ast_context = &Context; if (m_passthrough) m_passthrough->Initialize(Context); } void ASTResultSynthesizer::TransformTopLevelDecl(Decl* D) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); if (NamedDecl *named_decl = dyn_cast<NamedDecl>(D)) { if (log) { if (named_decl->getIdentifier()) log->Printf("TransformTopLevelDecl(%s)", named_decl->getIdentifier()->getNameStart()); else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) log->Printf("TransformTopLevelDecl(%s)", method_decl->getSelector().getAsString().c_str()); else log->Printf("TransformTopLevelDecl(<complex>)"); } } if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D)) { RecordDecl::decl_iterator decl_iterator; for (decl_iterator = linkage_spec_decl->decls_begin(); decl_iterator != linkage_spec_decl->decls_end(); ++decl_iterator) { TransformTopLevelDecl(*decl_iterator); } } else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) { if (m_ast_context && !method_decl->getSelector().getAsString().compare("$__lldb_expr:")) { SynthesizeObjCMethodResult(method_decl); } } else if (FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D)) { if (m_ast_context && !function_decl->getNameInfo().getAsString().compare("$__lldb_expr")) { SynthesizeFunctionResult(function_decl); } } } void ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D) { DeclGroupRef::iterator decl_iterator; for (decl_iterator = D.begin(); decl_iterator != D.end(); ++decl_iterator) { Decl *decl = *decl_iterator; TransformTopLevelDecl(decl); } if (m_passthrough) m_passthrough->HandleTopLevelDecl(D); } bool ASTResultSynthesizer::SynthesizeFunctionResult (FunctionDecl *FunDecl) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); if (!m_sema) return false; FunctionDecl *function_decl = FunDecl; if (!function_decl) return false; if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); Ctx.getTranslationUnitDecl()->print(os); os.flush(); log->Printf("AST context before transforming:\n%s", s.c_str()); } Stmt *function_body = function_decl->getBody(); CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body); bool ret = SynthesizeBodyResult (compound_stmt, function_decl); if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); function_decl->print(os); os.flush(); log->Printf ("Transformed function AST:\n%s", s.c_str()); } return ret; } bool ASTResultSynthesizer::SynthesizeObjCMethodResult (ObjCMethodDecl *MethodDecl) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); if (!m_sema) return false; if (!MethodDecl) return false; if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); Ctx.getTranslationUnitDecl()->print(os); os.flush(); log->Printf("AST context before transforming:\n%s", s.c_str()); } Stmt *method_body = MethodDecl->getBody(); CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body); bool ret = SynthesizeBodyResult (compound_stmt, MethodDecl); if (log) { std::string s; raw_string_ostream os(s); MethodDecl->print(os); os.flush(); log->Printf("Transformed function AST:\n%s", s.c_str()); } return ret; } bool ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body, DeclContext *DC) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(Body); if (!compound_stmt) return false; if (compound_stmt->body_empty()) return false; Stmt **last_stmt_ptr = compound_stmt->body_end() - 1; Stmt *last_stmt = *last_stmt_ptr; while (dyn_cast<NullStmt>(last_stmt)) { if (last_stmt_ptr != compound_stmt->body_begin()) { last_stmt_ptr--; last_stmt = *last_stmt_ptr; } else { return false; } } Expr *last_expr = dyn_cast<Expr>(last_stmt); if (!last_expr) // No auxiliary variable necessary; expression returns void return true; // is_lvalue is used to record whether the expression returns an assignable Lvalue or an // Rvalue. This is relevant because they are handled differently. // // For Lvalues // // - In AST result synthesis (here!) the expression E is transformed into an initialization // T *$__lldb_expr_result_ptr = &E. // // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be // passed into the expression. // // - In IR transformations, reads and writes to $__lldb_expr_result_ptr are redirected at // an entry in the struct ($__lldb_arg) passed into the expression. (Other persistent // variables are treated similarly, having been materialized as references, but in those // cases the value of the reference itself is never modified.) // // - During materialization, $0 (the result persistent variable) is ignored. // // - During dematerialization, $0 is marked up as a load address with value equal to the // contents of the structure entry. // // For Rvalues // // - In AST result synthesis the expression E is transformed into an initialization // static T $__lldb_expr_result = E. // // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be // passed into the expression. // // - In IR transformations, an instruction is inserted at the beginning of the function to // dereference the pointer resident in the slot. Reads and writes to $__lldb_expr_result // are redirected at that dereferenced version. Guard variables for the static variable // are excised. // // - During materialization, $0 (the result persistent variable) is populated with the location // of a newly-allocated area of memory. // // - During dematerialization, $0 is ignored. bool is_lvalue = (last_expr->getValueKind() == VK_LValue || last_expr->getValueKind() == VK_XValue) && (last_expr->getObjectKind() == OK_Ordinary); QualType expr_qual_type = last_expr->getType(); const clang::Type *expr_type = expr_qual_type.getTypePtr(); if (!expr_type) return false; if (expr_type->isVoidType()) return true; if (log) { std::string s = expr_qual_type.getAsString(); log->Printf("Last statement is an %s with type: %s", (is_lvalue ? "lvalue" : "rvalue"), s.c_str()); } clang::VarDecl *result_decl = NULL; if (is_lvalue) { IdentifierInfo &result_ptr_id = Ctx.Idents.get("$__lldb_expr_result_ptr"); QualType ptr_qual_type = Ctx.getPointerType(expr_qual_type); result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), &result_ptr_id, ptr_qual_type, NULL, SC_Static, SC_Static); if (!result_decl) return false; ExprResult address_of_expr = m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr); m_sema->AddInitializerToDecl(result_decl, address_of_expr.take(), true, true); } else { IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result"); result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), &result_id, expr_qual_type, NULL, SC_Static, SC_Static); if (!result_decl) return false; m_sema->AddInitializerToDecl(result_decl, last_expr, true, true); } DC->addDecl(result_decl); /////////////////////////////// // call AddInitializerToDecl // //m_sema->AddInitializerToDecl(result_decl, last_expr); ///////////////////////////////// // call ConvertDeclToDeclGroup // Sema::DeclGroupPtrTy result_decl_group_ptr; result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl); //////////////////////// // call ActOnDeclStmt // StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt(result_decl_group_ptr, SourceLocation(), SourceLocation())); //////////////////////////////////////////////// // replace the old statement with the new one // *last_stmt_ptr = reinterpret_cast<Stmt*>(result_initialization_stmt_result.take()); return true; } void ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx) { if (m_passthrough) m_passthrough->HandleTranslationUnit(Ctx); } void ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D) { if (m_passthrough) m_passthrough->HandleTagDeclDefinition(D); } void ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D) { if (m_passthrough) m_passthrough->CompleteTentativeDefinition(D); } void ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) { if (m_passthrough) m_passthrough->HandleVTable(RD, DefinitionRequired); } void ASTResultSynthesizer::PrintStats() { if (m_passthrough) m_passthrough->PrintStats(); } void ASTResultSynthesizer::InitializeSema(Sema &S) { m_sema = &S; if (m_passthrough_sema) m_passthrough_sema->InitializeSema(S); } void ASTResultSynthesizer::ForgetSema() { m_sema = NULL; if (m_passthrough_sema) m_passthrough_sema->ForgetSema(); } <commit_msg>Removed a redundant dyn_cast. Thanks to Felipe Cabecinhas.<commit_after>//===-- ASTResultSynthesizer.cpp --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdlib.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/Stmt.h" #include "clang/Parse/Parser.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include "lldb/Core/Log.h" #include "lldb/Expression/ASTResultSynthesizer.h" using namespace llvm; using namespace clang; using namespace lldb_private; ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough, TypeFromUser desired_type) : m_ast_context (NULL), m_passthrough (passthrough), m_passthrough_sema (NULL), m_sema (NULL), m_desired_type (desired_type) { if (!m_passthrough) return; m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough); } ASTResultSynthesizer::~ASTResultSynthesizer() { } void ASTResultSynthesizer::Initialize(ASTContext &Context) { m_ast_context = &Context; if (m_passthrough) m_passthrough->Initialize(Context); } void ASTResultSynthesizer::TransformTopLevelDecl(Decl* D) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); if (NamedDecl *named_decl = dyn_cast<NamedDecl>(D)) { if (log) { if (named_decl->getIdentifier()) log->Printf("TransformTopLevelDecl(%s)", named_decl->getIdentifier()->getNameStart()); else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) log->Printf("TransformTopLevelDecl(%s)", method_decl->getSelector().getAsString().c_str()); else log->Printf("TransformTopLevelDecl(<complex>)"); } } if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D)) { RecordDecl::decl_iterator decl_iterator; for (decl_iterator = linkage_spec_decl->decls_begin(); decl_iterator != linkage_spec_decl->decls_end(); ++decl_iterator) { TransformTopLevelDecl(*decl_iterator); } } else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) { if (m_ast_context && !method_decl->getSelector().getAsString().compare("$__lldb_expr:")) { SynthesizeObjCMethodResult(method_decl); } } else if (FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D)) { if (m_ast_context && !function_decl->getNameInfo().getAsString().compare("$__lldb_expr")) { SynthesizeFunctionResult(function_decl); } } } void ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D) { DeclGroupRef::iterator decl_iterator; for (decl_iterator = D.begin(); decl_iterator != D.end(); ++decl_iterator) { Decl *decl = *decl_iterator; TransformTopLevelDecl(decl); } if (m_passthrough) m_passthrough->HandleTopLevelDecl(D); } bool ASTResultSynthesizer::SynthesizeFunctionResult (FunctionDecl *FunDecl) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); if (!m_sema) return false; FunctionDecl *function_decl = FunDecl; if (!function_decl) return false; if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); Ctx.getTranslationUnitDecl()->print(os); os.flush(); log->Printf("AST context before transforming:\n%s", s.c_str()); } Stmt *function_body = function_decl->getBody(); CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body); bool ret = SynthesizeBodyResult (compound_stmt, function_decl); if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); function_decl->print(os); os.flush(); log->Printf ("Transformed function AST:\n%s", s.c_str()); } return ret; } bool ASTResultSynthesizer::SynthesizeObjCMethodResult (ObjCMethodDecl *MethodDecl) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); if (!m_sema) return false; if (!MethodDecl) return false; if (log && log->GetVerbose()) { std::string s; raw_string_ostream os(s); Ctx.getTranslationUnitDecl()->print(os); os.flush(); log->Printf("AST context before transforming:\n%s", s.c_str()); } Stmt *method_body = MethodDecl->getBody(); CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body); bool ret = SynthesizeBodyResult (compound_stmt, MethodDecl); if (log) { std::string s; raw_string_ostream os(s); MethodDecl->print(os); os.flush(); log->Printf("Transformed function AST:\n%s", s.c_str()); } return ret; } bool ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body, DeclContext *DC) { lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); ASTContext &Ctx(*m_ast_context); if (!Body) return false; if (Body->body_empty()) return false; Stmt **last_stmt_ptr = Body->body_end() - 1; Stmt *last_stmt = *last_stmt_ptr; while (dyn_cast<NullStmt>(last_stmt)) { if (last_stmt_ptr != Body->body_begin()) { last_stmt_ptr--; last_stmt = *last_stmt_ptr; } else { return false; } } Expr *last_expr = dyn_cast<Expr>(last_stmt); if (!last_expr) // No auxiliary variable necessary; expression returns void return true; // is_lvalue is used to record whether the expression returns an assignable Lvalue or an // Rvalue. This is relevant because they are handled differently. // // For Lvalues // // - In AST result synthesis (here!) the expression E is transformed into an initialization // T *$__lldb_expr_result_ptr = &E. // // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be // passed into the expression. // // - In IR transformations, reads and writes to $__lldb_expr_result_ptr are redirected at // an entry in the struct ($__lldb_arg) passed into the expression. (Other persistent // variables are treated similarly, having been materialized as references, but in those // cases the value of the reference itself is never modified.) // // - During materialization, $0 (the result persistent variable) is ignored. // // - During dematerialization, $0 is marked up as a load address with value equal to the // contents of the structure entry. // // For Rvalues // // - In AST result synthesis the expression E is transformed into an initialization // static T $__lldb_expr_result = E. // // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be // passed into the expression. // // - In IR transformations, an instruction is inserted at the beginning of the function to // dereference the pointer resident in the slot. Reads and writes to $__lldb_expr_result // are redirected at that dereferenced version. Guard variables for the static variable // are excised. // // - During materialization, $0 (the result persistent variable) is populated with the location // of a newly-allocated area of memory. // // - During dematerialization, $0 is ignored. bool is_lvalue = (last_expr->getValueKind() == VK_LValue || last_expr->getValueKind() == VK_XValue) && (last_expr->getObjectKind() == OK_Ordinary); QualType expr_qual_type = last_expr->getType(); const clang::Type *expr_type = expr_qual_type.getTypePtr(); if (!expr_type) return false; if (expr_type->isVoidType()) return true; if (log) { std::string s = expr_qual_type.getAsString(); log->Printf("Last statement is an %s with type: %s", (is_lvalue ? "lvalue" : "rvalue"), s.c_str()); } clang::VarDecl *result_decl = NULL; if (is_lvalue) { IdentifierInfo &result_ptr_id = Ctx.Idents.get("$__lldb_expr_result_ptr"); QualType ptr_qual_type = Ctx.getPointerType(expr_qual_type); result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), &result_ptr_id, ptr_qual_type, NULL, SC_Static, SC_Static); if (!result_decl) return false; ExprResult address_of_expr = m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr); m_sema->AddInitializerToDecl(result_decl, address_of_expr.take(), true, true); } else { IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result"); result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), &result_id, expr_qual_type, NULL, SC_Static, SC_Static); if (!result_decl) return false; m_sema->AddInitializerToDecl(result_decl, last_expr, true, true); } DC->addDecl(result_decl); /////////////////////////////// // call AddInitializerToDecl // //m_sema->AddInitializerToDecl(result_decl, last_expr); ///////////////////////////////// // call ConvertDeclToDeclGroup // Sema::DeclGroupPtrTy result_decl_group_ptr; result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl); //////////////////////// // call ActOnDeclStmt // StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt(result_decl_group_ptr, SourceLocation(), SourceLocation())); //////////////////////////////////////////////// // replace the old statement with the new one // *last_stmt_ptr = reinterpret_cast<Stmt*>(result_initialization_stmt_result.take()); return true; } void ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx) { if (m_passthrough) m_passthrough->HandleTranslationUnit(Ctx); } void ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D) { if (m_passthrough) m_passthrough->HandleTagDeclDefinition(D); } void ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D) { if (m_passthrough) m_passthrough->CompleteTentativeDefinition(D); } void ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) { if (m_passthrough) m_passthrough->HandleVTable(RD, DefinitionRequired); } void ASTResultSynthesizer::PrintStats() { if (m_passthrough) m_passthrough->PrintStats(); } void ASTResultSynthesizer::InitializeSema(Sema &S) { m_sema = &S; if (m_passthrough_sema) m_passthrough_sema->InitializeSema(S); } void ASTResultSynthesizer::ForgetSema() { m_sema = NULL; if (m_passthrough_sema) m_passthrough_sema->ForgetSema(); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_roostats /// \notebook -js /// 'Bernstein Correction' RooStats tutorial macro /// /// This tutorial shows usage of a the BernsteinCorrection utility in RooStats. /// The idea is that one has a distribution coming either from data or Monte Carlo /// (called "reality" in the macro) and a nominal model that is not sufficiently /// flexible to take into account the real distribution. One wants to take into /// account the systematic associated with this imperfect modeling by augmenting /// the nominal model with some correction term (in this case a polynomial). /// The BernsteinCorrection utility will import into your workspace a corrected model /// given by nominal(x) * poly_N(x), where poly_N is an n-th order polynomial in /// the Bernstein basis. The degree N of the polynomial is chosen by specifying the tolerance /// one has in adding an extra term to the polynomial. /// The Bernstein basis is nice because it only has positive-definite terms /// and works well with PDFs. /// Finally, the macro makes a plot of: /// - the data (drawn from 'reality'), /// - the best fit of the nominal model (blue) /// - and the best fit corrected model. /// /// \macro_image /// \macro_output /// \macro_code /// /// \author Kyle Cranmer #include "RooDataSet.h" #include "RooRealVar.h" #include "RooConstVar.h" #include "RooBernstein.h" #include "TCanvas.h" #include "RooAbsPdf.h" #include "RooFit.h" #include "RooFitResult.h" #include "RooPlot.h" #include <string> #include <vector> #include <stdio.h> #include <sstream> #include <iostream> #include "RooProdPdf.h" #include "RooAddPdf.h" #include "RooGaussian.h" #include "RooNLLVar.h" #include "RooMinuit.h" #include "RooProfileLL.h" #include "RooWorkspace.h" #include "RooStats/BernsteinCorrection.h" // use this order for safety on library loading using namespace RooFit; using namespace RooStats; //____________________________________ void rs_bernsteinCorrection(){ // set range of observable Double_t lowRange = -1, highRange =5; // make a RooRealVar for the observable RooRealVar x("x", "x", lowRange, highRange); // true model RooGaussian narrow("narrow","",x,RooConst(0.), RooConst(.8)); RooGaussian wide("wide","",x,RooConst(0.), RooConst(2.)); RooAddPdf reality("reality","",RooArgList(narrow, wide), RooConst(0.8)); RooDataSet* data = reality.generate(x,1000); // nominal model RooRealVar sigma("sigma","",1.,0,10); RooGaussian nominal("nominal","",x,RooConst(0.), sigma); RooWorkspace* wks = new RooWorkspace("myWorksspace"); wks->import(*data, Rename("data")); wks->import(nominal); // use Minuit2 ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); // The tolerance sets the probability to add an unnecessary term. // lower tolerance will add fewer terms, while higher tolerance // will add more terms and provide a more flexible function. Double_t tolerance = 0.05; BernsteinCorrection bernsteinCorrection(tolerance); Int_t degree = bernsteinCorrection.ImportCorrectedPdf(wks,"nominal","x","data"); if (degree < 0) { Error("rs_bernsteinCorrection","Bernstein correction failed ! "); return; } cout << " Correction based on Bernstein Poly of degree " << degree << endl; RooPlot* frame = x.frame(); data->plotOn(frame); // plot the best fit nominal model in blue TString minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType(); nominal.fitTo(*data,PrintLevel(0),Minimizer(minimType)); nominal.plotOn(frame); // plot the best fit corrected model in red RooAbsPdf* corrected = wks->pdf("corrected"); if (!corrected) return; // fit corrected model corrected->fitTo(*data,PrintLevel(0),Minimizer(minimType) ); corrected->plotOn(frame,LineColor(kRed)); // plot the correction term (* norm constant) in dashed green // should make norm constant just be 1, not depend on binning of data RooAbsPdf* poly = wks->pdf("poly"); if (poly) poly->plotOn(frame,LineColor(kGreen), LineStyle(kDashed)); // this is a switch to check the sampling distribution // of -2 log LR for two comparisons: // the first is for n-1 vs. n degree polynomial corrections // the second is for n vs. n+1 degree polynomial corrections // Here we choose n to be the one chosen by the tolerance // criterion above, eg. n = "degree" in the code. // Setting this to true is takes about 10 min. bool checkSamplingDist = true; int numToyMC = 20; // increase this value for sensible results TCanvas* c1 = new TCanvas(); if(checkSamplingDist) { c1->Divide(1,2); c1->cd(1); } frame->Draw(); gPad->Update(); if(checkSamplingDist) { // check sampling dist ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(-1); TH1F* samplingDist = new TH1F("samplingDist","",20,0,10); TH1F* samplingDistExtra = new TH1F("samplingDistExtra","",20,0,10); bernsteinCorrection.CreateQSamplingDist(wks,"nominal","x","data",samplingDist, samplingDistExtra, degree,numToyMC); c1->cd(2); samplingDistExtra->SetLineColor(kRed); samplingDistExtra->Draw(); samplingDist->Draw("same"); } } <commit_msg>Only enable Minuit2 if ROOT was configured with it!<commit_after>/// \file /// \ingroup tutorial_roostats /// \notebook -js /// 'Bernstein Correction' RooStats tutorial macro /// /// This tutorial shows usage of a the BernsteinCorrection utility in RooStats. /// The idea is that one has a distribution coming either from data or Monte Carlo /// (called "reality" in the macro) and a nominal model that is not sufficiently /// flexible to take into account the real distribution. One wants to take into /// account the systematic associated with this imperfect modeling by augmenting /// the nominal model with some correction term (in this case a polynomial). /// The BernsteinCorrection utility will import into your workspace a corrected model /// given by nominal(x) * poly_N(x), where poly_N is an n-th order polynomial in /// the Bernstein basis. The degree N of the polynomial is chosen by specifying the tolerance /// one has in adding an extra term to the polynomial. /// The Bernstein basis is nice because it only has positive-definite terms /// and works well with PDFs. /// Finally, the macro makes a plot of: /// - the data (drawn from 'reality'), /// - the best fit of the nominal model (blue) /// - and the best fit corrected model. /// /// \macro_image /// \macro_output /// \macro_code /// /// \author Kyle Cranmer #include "RooDataSet.h" #include "RooRealVar.h" #include "RooConstVar.h" #include "RooBernstein.h" #include "TCanvas.h" #include "RooAbsPdf.h" #include "RooFit.h" #include "RooFitResult.h" #include "RooPlot.h" #include <string> #include <vector> #include <stdio.h> #include <sstream> #include <iostream> #include "RooProdPdf.h" #include "RooAddPdf.h" #include "RooGaussian.h" #include "RooNLLVar.h" #include "RooMinuit.h" #include "RooProfileLL.h" #include "RooWorkspace.h" #include "RooStats/BernsteinCorrection.h" // use this order for safety on library loading using namespace RooFit; using namespace RooStats; //____________________________________ void rs_bernsteinCorrection(){ // set range of observable Double_t lowRange = -1, highRange =5; // make a RooRealVar for the observable RooRealVar x("x", "x", lowRange, highRange); // true model RooGaussian narrow("narrow","",x,RooConst(0.), RooConst(.8)); RooGaussian wide("wide","",x,RooConst(0.), RooConst(2.)); RooAddPdf reality("reality","",RooArgList(narrow, wide), RooConst(0.8)); RooDataSet* data = reality.generate(x,1000); // nominal model RooRealVar sigma("sigma","",1.,0,10); RooGaussian nominal("nominal","",x,RooConst(0.), sigma); RooWorkspace* wks = new RooWorkspace("myWorksspace"); wks->import(*data, Rename("data")); wks->import(nominal); if (TClass::GetClass("ROOT::Minuit2::Minuit2Minimizer")) { // use Minuit2 if ROOT was built with support for it: ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2"); } // The tolerance sets the probability to add an unnecessary term. // lower tolerance will add fewer terms, while higher tolerance // will add more terms and provide a more flexible function. Double_t tolerance = 0.05; BernsteinCorrection bernsteinCorrection(tolerance); Int_t degree = bernsteinCorrection.ImportCorrectedPdf(wks,"nominal","x","data"); if (degree < 0) { Error("rs_bernsteinCorrection","Bernstein correction failed ! "); return; } cout << " Correction based on Bernstein Poly of degree " << degree << endl; RooPlot* frame = x.frame(); data->plotOn(frame); // plot the best fit nominal model in blue TString minimType = ROOT::Math::MinimizerOptions::DefaultMinimizerType(); nominal.fitTo(*data,PrintLevel(0),Minimizer(minimType)); nominal.plotOn(frame); // plot the best fit corrected model in red RooAbsPdf* corrected = wks->pdf("corrected"); if (!corrected) return; // fit corrected model corrected->fitTo(*data,PrintLevel(0),Minimizer(minimType) ); corrected->plotOn(frame,LineColor(kRed)); // plot the correction term (* norm constant) in dashed green // should make norm constant just be 1, not depend on binning of data RooAbsPdf* poly = wks->pdf("poly"); if (poly) poly->plotOn(frame,LineColor(kGreen), LineStyle(kDashed)); // this is a switch to check the sampling distribution // of -2 log LR for two comparisons: // the first is for n-1 vs. n degree polynomial corrections // the second is for n vs. n+1 degree polynomial corrections // Here we choose n to be the one chosen by the tolerance // criterion above, eg. n = "degree" in the code. // Setting this to true is takes about 10 min. bool checkSamplingDist = true; int numToyMC = 20; // increase this value for sensible results TCanvas* c1 = new TCanvas(); if(checkSamplingDist) { c1->Divide(1,2); c1->cd(1); } frame->Draw(); gPad->Update(); if(checkSamplingDist) { // check sampling dist ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(-1); TH1F* samplingDist = new TH1F("samplingDist","",20,0,10); TH1F* samplingDistExtra = new TH1F("samplingDistExtra","",20,0,10); bernsteinCorrection.CreateQSamplingDist(wks,"nominal","x","data",samplingDist, samplingDistExtra, degree,numToyMC); c1->cd(2); samplingDistExtra->SetLineColor(kRed); samplingDistExtra->Draw(); samplingDist->Draw("same"); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opump.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:44:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_io.hxx" #include <stdio.h> #include <osl/diagnose.h> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataSink.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/io/XConnectable.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/registry/XRegistryKey.hpp> #include <uno/dispatcher.h> #include <uno/mapping.hxx> #include <cppuhelper/implbase5.hxx> #include <cppuhelper/factory.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <osl/mutex.hxx> #include <osl/thread.h> using namespace osl; using namespace std; using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace com::sun::star::io; #include "factreg.hxx" namespace io_stm { class Pump : public WeakImplHelper5< XActiveDataSource, XActiveDataSink, XActiveDataControl, XConnectable, XServiceInfo > { Mutex m_aMutex; oslThread m_aThread; Reference< XConnectable > m_xPred; Reference< XConnectable > m_xSucc; Reference< XInputStream > m_xInput; Reference< XOutputStream > m_xOutput; OInterfaceContainerHelper m_cnt; sal_Bool m_closeFired; void run(); static void static_run( void* pObject ); void close(); void fireClose(); void fireStarted(); void fireTerminated(); void fireError( const Any &a ); public: Pump(); virtual ~Pump(); // XActiveDataSource virtual void SAL_CALL setOutputStream( const Reference< ::com::sun::star::io::XOutputStream >& xOutput ) throw(); virtual Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream() throw(); // XActiveDataSink virtual void SAL_CALL setInputStream( const Reference< ::com::sun::star::io::XInputStream >& xStream ) throw(); virtual Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream() throw(); // XActiveDataControl virtual void SAL_CALL addListener( const Reference< ::com::sun::star::io::XStreamListener >& xListener ) throw(); virtual void SAL_CALL removeListener( const Reference< ::com::sun::star::io::XStreamListener >& xListener ) throw(); virtual void SAL_CALL start() throw( RuntimeException ); virtual void SAL_CALL terminate() throw(); // XConnectable virtual void SAL_CALL setPredecessor( const Reference< ::com::sun::star::io::XConnectable >& xPred ) throw(); virtual Reference< ::com::sun::star::io::XConnectable > SAL_CALL getPredecessor() throw(); virtual void SAL_CALL setSuccessor( const Reference< ::com::sun::star::io::XConnectable >& xSucc ) throw(); virtual Reference< ::com::sun::star::io::XConnectable > SAL_CALL getSuccessor() throw(); public: // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw( ); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw( ); virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw( ); }; Pump::Pump() : m_aThread( 0 ), m_cnt( m_aMutex ), m_closeFired( sal_False ) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt ); } Pump::~Pump() { // exit gracefully if( m_aThread ) { osl_joinWithThread( m_aThread ); osl_destroyThread( m_aThread ); } g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } void Pump::fireError( const Any & exception ) { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->error( exception ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::fireClose() { sal_Bool bFire = sal_False; { MutexGuard guard( m_aMutex ); if( ! m_closeFired ) { m_closeFired = sal_True; bFire = sal_True; } } if( bFire ) { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->closed( ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } } void Pump::fireStarted() { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->started( ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::fireTerminated() { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->terminated(); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::close() { // close streams and release references Reference< XInputStream > rInput; Reference< XOutputStream > rOutput; { MutexGuard guard( m_aMutex ); rInput = m_xInput; m_xInput.clear(); rOutput = m_xOutput; m_xOutput.clear(); m_xSucc.clear(); m_xPred.clear(); } if( rInput.is() ) { try { rInput->closeInput(); } catch( Exception & ) { // go down calm } } if( rOutput.is() ) { try { rOutput->closeOutput(); } catch( Exception & ) { // go down calm } } } void Pump::static_run( void* pObject ) { ((Pump*)pObject)->run(); ((Pump*)pObject)->release(); } void Pump::run() { try { fireStarted(); try { Reference< XInputStream > rInput; Reference< XOutputStream > rOutput; { Guard< Mutex > aGuard( m_aMutex ); rInput = m_xInput; rOutput = m_xOutput; } if( ! rInput.is() ) { NotConnectedException exception( OUString::createFromAscii( "no input stream set" ) , Reference<XInterface>((OWeakObject*)this) ); throw exception; } Sequence< sal_Int8 > aData; while( rInput->readSomeBytes( aData, 65536 ) ) { if( ! rOutput.is() ) { NotConnectedException exception( OUString::createFromAscii( "no output stream set" ) , Reference<XInterface>( (OWeakObject*)this) ); throw exception; } rOutput->writeBytes( aData ); osl_yieldThread(); } } catch ( IOException & e ) { fireError( makeAny( e ) ); } catch ( RuntimeException & e ) { fireError( makeAny( e ) ); } catch ( Exception & e ) { fireError( makeAny( e ) ); } close(); fireClose(); } catch ( com::sun::star::uno::Exception &e ) { // we are the last on the stack. // this is to avoid crashing the program, when e.g. a bridge crashes OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception", sMessage.getStr() ); } } // ------------------------------------------------------------ /* * XConnectable */ void Pump::setPredecessor( const Reference< XConnectable >& xPred ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xPred = xPred; } // ------------------------------------------------------------ Reference< XConnectable > Pump::getPredecessor() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xPred; } // ------------------------------------------------------------ void Pump::setSuccessor( const Reference< XConnectable >& xSucc ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xSucc = xSucc; } // ------------------------------------------------------------ Reference< XConnectable > Pump::getSuccessor() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xSucc; } // ----------------------------------------------------------------- /* * XActiveDataControl */ void Pump::addListener( const Reference< XStreamListener >& xListener ) throw() { m_cnt.addInterface( xListener ); } // ------------------------------------------------------------ void Pump::removeListener( const Reference< XStreamListener >& xListener ) throw() { m_cnt.removeInterface( xListener ); } // ------------------------------------------------------------ void Pump::start() throw( RuntimeException ) { Guard< Mutex > aGuard( m_aMutex ); m_aThread = osl_createSuspendedThread((oslWorkerFunction)Pump::static_run,this); if( m_aThread ) { // will be released by OPump::static_run acquire(); osl_resumeThread( m_aThread ); } else { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pump::start Couldn't create worker thread" )), *this); } } // ------------------------------------------------------------ void Pump::terminate() throw() { close(); // wait for the worker to die if( m_aThread ) osl_joinWithThread( m_aThread ); fireTerminated(); fireClose(); } // ------------------------------------------------------------ /* * XActiveDataSink */ void Pump::setInputStream( const Reference< XInputStream >& xStream ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xInput = xStream; Reference< XConnectable > xConnect( xStream, UNO_QUERY ); if( xConnect.is() ) xConnect->setSuccessor( this ); // data transfer starts in XActiveDataControl::start } // ------------------------------------------------------------ Reference< XInputStream > Pump::getInputStream() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xInput; } // ------------------------------------------------------------ /* * XActiveDataSource */ void Pump::setOutputStream( const Reference< XOutputStream >& xOut ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xOutput = xOut; Reference< XConnectable > xConnect( xOut, UNO_QUERY ); if( xConnect.is() ) xConnect->setPredecessor( this ); // data transfer starts in XActiveDataControl::start } // ------------------------------------------------------------ Reference< XOutputStream > Pump::getOutputStream() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xOutput; } // XServiceInfo OUString Pump::getImplementationName() throw( ) { return OPumpImpl_getImplementationName(); } // XServiceInfo sal_Bool Pump::supportsService(const OUString& ServiceName) throw( ) { Sequence< OUString > aSNL = getSupportedServiceNames(); const OUString * pArray = aSNL.getConstArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return sal_True; return sal_False; } // XServiceInfo Sequence< OUString > Pump::getSupportedServiceNames(void) throw( ) { return OPumpImpl_getSupportedServiceNames(); } Reference< XInterface > SAL_CALL OPumpImpl_CreateInstance( const Reference< XComponentContext > & ) throw (Exception) { return Reference< XInterface >( *new Pump ); } OUString OPumpImpl_getImplementationName() { return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.io.Pump") ); } Sequence<OUString> OPumpImpl_getSupportedServiceNames(void) { OUString s( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.io.Pump" ) ); Sequence< OUString > seq( &s , 1 ); return seq; } } <commit_msg>INTEGRATION: CWS changefileheader (1.12.28); FILE MERGED 2008/03/31 12:33:31 rt 1.12.28.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: opump.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_io.hxx" #include <stdio.h> #include <osl/diagnose.h> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataSink.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/io/XConnectable.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/registry/XRegistryKey.hpp> #include <uno/dispatcher.h> #include <uno/mapping.hxx> #include <cppuhelper/implbase5.hxx> #include <cppuhelper/factory.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <osl/mutex.hxx> #include <osl/thread.h> using namespace osl; using namespace std; using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace com::sun::star::io; #include "factreg.hxx" namespace io_stm { class Pump : public WeakImplHelper5< XActiveDataSource, XActiveDataSink, XActiveDataControl, XConnectable, XServiceInfo > { Mutex m_aMutex; oslThread m_aThread; Reference< XConnectable > m_xPred; Reference< XConnectable > m_xSucc; Reference< XInputStream > m_xInput; Reference< XOutputStream > m_xOutput; OInterfaceContainerHelper m_cnt; sal_Bool m_closeFired; void run(); static void static_run( void* pObject ); void close(); void fireClose(); void fireStarted(); void fireTerminated(); void fireError( const Any &a ); public: Pump(); virtual ~Pump(); // XActiveDataSource virtual void SAL_CALL setOutputStream( const Reference< ::com::sun::star::io::XOutputStream >& xOutput ) throw(); virtual Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream() throw(); // XActiveDataSink virtual void SAL_CALL setInputStream( const Reference< ::com::sun::star::io::XInputStream >& xStream ) throw(); virtual Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream() throw(); // XActiveDataControl virtual void SAL_CALL addListener( const Reference< ::com::sun::star::io::XStreamListener >& xListener ) throw(); virtual void SAL_CALL removeListener( const Reference< ::com::sun::star::io::XStreamListener >& xListener ) throw(); virtual void SAL_CALL start() throw( RuntimeException ); virtual void SAL_CALL terminate() throw(); // XConnectable virtual void SAL_CALL setPredecessor( const Reference< ::com::sun::star::io::XConnectable >& xPred ) throw(); virtual Reference< ::com::sun::star::io::XConnectable > SAL_CALL getPredecessor() throw(); virtual void SAL_CALL setSuccessor( const Reference< ::com::sun::star::io::XConnectable >& xSucc ) throw(); virtual Reference< ::com::sun::star::io::XConnectable > SAL_CALL getSuccessor() throw(); public: // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw( ); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw( ); virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw( ); }; Pump::Pump() : m_aThread( 0 ), m_cnt( m_aMutex ), m_closeFired( sal_False ) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt ); } Pump::~Pump() { // exit gracefully if( m_aThread ) { osl_joinWithThread( m_aThread ); osl_destroyThread( m_aThread ); } g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } void Pump::fireError( const Any & exception ) { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->error( exception ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::fireClose() { sal_Bool bFire = sal_False; { MutexGuard guard( m_aMutex ); if( ! m_closeFired ) { m_closeFired = sal_True; bFire = sal_True; } } if( bFire ) { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->closed( ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } } void Pump::fireStarted() { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->started( ); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::fireTerminated() { OInterfaceIteratorHelper iter( m_cnt ); while( iter.hasMoreElements() ) { try { static_cast< XStreamListener * > ( iter.next() )->terminated(); } catch ( RuntimeException &e ) { OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception during calling listeners", sMessage.getStr() ); } } } void Pump::close() { // close streams and release references Reference< XInputStream > rInput; Reference< XOutputStream > rOutput; { MutexGuard guard( m_aMutex ); rInput = m_xInput; m_xInput.clear(); rOutput = m_xOutput; m_xOutput.clear(); m_xSucc.clear(); m_xPred.clear(); } if( rInput.is() ) { try { rInput->closeInput(); } catch( Exception & ) { // go down calm } } if( rOutput.is() ) { try { rOutput->closeOutput(); } catch( Exception & ) { // go down calm } } } void Pump::static_run( void* pObject ) { ((Pump*)pObject)->run(); ((Pump*)pObject)->release(); } void Pump::run() { try { fireStarted(); try { Reference< XInputStream > rInput; Reference< XOutputStream > rOutput; { Guard< Mutex > aGuard( m_aMutex ); rInput = m_xInput; rOutput = m_xOutput; } if( ! rInput.is() ) { NotConnectedException exception( OUString::createFromAscii( "no input stream set" ) , Reference<XInterface>((OWeakObject*)this) ); throw exception; } Sequence< sal_Int8 > aData; while( rInput->readSomeBytes( aData, 65536 ) ) { if( ! rOutput.is() ) { NotConnectedException exception( OUString::createFromAscii( "no output stream set" ) , Reference<XInterface>( (OWeakObject*)this) ); throw exception; } rOutput->writeBytes( aData ); osl_yieldThread(); } } catch ( IOException & e ) { fireError( makeAny( e ) ); } catch ( RuntimeException & e ) { fireError( makeAny( e ) ); } catch ( Exception & e ) { fireError( makeAny( e ) ); } close(); fireClose(); } catch ( com::sun::star::uno::Exception &e ) { // we are the last on the stack. // this is to avoid crashing the program, when e.g. a bridge crashes OString sMessage = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); OSL_ENSURE( !"com.sun.star.comp.stoc.Pump: unexpected exception", sMessage.getStr() ); } } // ------------------------------------------------------------ /* * XConnectable */ void Pump::setPredecessor( const Reference< XConnectable >& xPred ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xPred = xPred; } // ------------------------------------------------------------ Reference< XConnectable > Pump::getPredecessor() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xPred; } // ------------------------------------------------------------ void Pump::setSuccessor( const Reference< XConnectable >& xSucc ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xSucc = xSucc; } // ------------------------------------------------------------ Reference< XConnectable > Pump::getSuccessor() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xSucc; } // ----------------------------------------------------------------- /* * XActiveDataControl */ void Pump::addListener( const Reference< XStreamListener >& xListener ) throw() { m_cnt.addInterface( xListener ); } // ------------------------------------------------------------ void Pump::removeListener( const Reference< XStreamListener >& xListener ) throw() { m_cnt.removeInterface( xListener ); } // ------------------------------------------------------------ void Pump::start() throw( RuntimeException ) { Guard< Mutex > aGuard( m_aMutex ); m_aThread = osl_createSuspendedThread((oslWorkerFunction)Pump::static_run,this); if( m_aThread ) { // will be released by OPump::static_run acquire(); osl_resumeThread( m_aThread ); } else { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Pump::start Couldn't create worker thread" )), *this); } } // ------------------------------------------------------------ void Pump::terminate() throw() { close(); // wait for the worker to die if( m_aThread ) osl_joinWithThread( m_aThread ); fireTerminated(); fireClose(); } // ------------------------------------------------------------ /* * XActiveDataSink */ void Pump::setInputStream( const Reference< XInputStream >& xStream ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xInput = xStream; Reference< XConnectable > xConnect( xStream, UNO_QUERY ); if( xConnect.is() ) xConnect->setSuccessor( this ); // data transfer starts in XActiveDataControl::start } // ------------------------------------------------------------ Reference< XInputStream > Pump::getInputStream() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xInput; } // ------------------------------------------------------------ /* * XActiveDataSource */ void Pump::setOutputStream( const Reference< XOutputStream >& xOut ) throw() { Guard< Mutex > aGuard( m_aMutex ); m_xOutput = xOut; Reference< XConnectable > xConnect( xOut, UNO_QUERY ); if( xConnect.is() ) xConnect->setPredecessor( this ); // data transfer starts in XActiveDataControl::start } // ------------------------------------------------------------ Reference< XOutputStream > Pump::getOutputStream() throw() { Guard< Mutex > aGuard( m_aMutex ); return m_xOutput; } // XServiceInfo OUString Pump::getImplementationName() throw( ) { return OPumpImpl_getImplementationName(); } // XServiceInfo sal_Bool Pump::supportsService(const OUString& ServiceName) throw( ) { Sequence< OUString > aSNL = getSupportedServiceNames(); const OUString * pArray = aSNL.getConstArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return sal_True; return sal_False; } // XServiceInfo Sequence< OUString > Pump::getSupportedServiceNames(void) throw( ) { return OPumpImpl_getSupportedServiceNames(); } Reference< XInterface > SAL_CALL OPumpImpl_CreateInstance( const Reference< XComponentContext > & ) throw (Exception) { return Reference< XInterface >( *new Pump ); } OUString OPumpImpl_getImplementationName() { return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.io.Pump") ); } Sequence<OUString> OPumpImpl_getSupportedServiceNames(void) { OUString s( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.io.Pump" ) ); Sequence< OUString > seq( &s , 1 ); return seq; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: semaphor.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 14:32:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _OSL_SEMAPHORE_HXX_ #define _OSL_SEMAPHORE_HXX_ #ifdef __cplusplus #include <osl/semaphor.h> namespace osl { class Semaphore { public: /** Creates a semaphore.<BR> @param InitialCount denotes the starting value the semaphore. If you set it to zero, the first acquire() blocks. Otherwise InitialCount acquire()s are immedeatly successfull. @return 0 if the semaphore could not be created, otherwise a handle to the sem. */ Semaphore(sal_uInt32 initialCount) { semaphore = osl_createSemaphore(initialCount); } /** Release the OS-structures and free semaphore data-structure @return fbbb */ ~Semaphore() { osl_destroySemaphore(semaphore); } /** acquire() decreases the count. It will block if it tries to decrease below zero. @return False if the system-call failed. */ sal_Bool acquire() { return osl_acquireSemaphore(semaphore); } /** tryToAcquire() tries to decreases the count. It will return with False if it would decrease the count below zero. (When acquire() would block.) If it could successfully decrease the count, it will return True. */ sal_Bool tryToAcquire() { return osl_tryToAcquireSemaphore(semaphore); } /** release() increases the count. @return False if the system-call failed. */ sal_Bool release() { return osl_releaseSemaphore(semaphore); } private: oslSemaphore semaphore; /** The underlying oslSemaphore has no reference count. Since the underlying oslSemaphore is not a reference counted object, copy constructed Semaphore may work on an already destructed oslSemaphore object. */ Semaphore(const Semaphore&); /** The underlying oslSemaphore has no reference count. When destructed, the Semaphore object destroys the undelying oslSemaphore, which might cause severe problems in case it's a temporary object. */ Semaphore(oslSemaphore Semaphore); /** This assignment operator is private for the same reason as the copy constructor. */ Semaphore& operator= (const Semaphore&); /** This assignment operator is private for the same reason as the constructor taking a oslSemaphore argument. */ Semaphore& operator= (oslSemaphore); }; } #endif /* __cplusplus */ #endif /* _OSL_SEMAPHORE_HXX_ */ <commit_msg>INTEGRATION: CWS changefileheader (1.8.378); FILE MERGED 2008/03/31 13:23:36 rt 1.8.378.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: semaphor.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _OSL_SEMAPHORE_HXX_ #define _OSL_SEMAPHORE_HXX_ #ifdef __cplusplus #include <osl/semaphor.h> namespace osl { class Semaphore { public: /** Creates a semaphore.<BR> @param InitialCount denotes the starting value the semaphore. If you set it to zero, the first acquire() blocks. Otherwise InitialCount acquire()s are immedeatly successfull. @return 0 if the semaphore could not be created, otherwise a handle to the sem. */ Semaphore(sal_uInt32 initialCount) { semaphore = osl_createSemaphore(initialCount); } /** Release the OS-structures and free semaphore data-structure @return fbbb */ ~Semaphore() { osl_destroySemaphore(semaphore); } /** acquire() decreases the count. It will block if it tries to decrease below zero. @return False if the system-call failed. */ sal_Bool acquire() { return osl_acquireSemaphore(semaphore); } /** tryToAcquire() tries to decreases the count. It will return with False if it would decrease the count below zero. (When acquire() would block.) If it could successfully decrease the count, it will return True. */ sal_Bool tryToAcquire() { return osl_tryToAcquireSemaphore(semaphore); } /** release() increases the count. @return False if the system-call failed. */ sal_Bool release() { return osl_releaseSemaphore(semaphore); } private: oslSemaphore semaphore; /** The underlying oslSemaphore has no reference count. Since the underlying oslSemaphore is not a reference counted object, copy constructed Semaphore may work on an already destructed oslSemaphore object. */ Semaphore(const Semaphore&); /** The underlying oslSemaphore has no reference count. When destructed, the Semaphore object destroys the undelying oslSemaphore, which might cause severe problems in case it's a temporary object. */ Semaphore(oslSemaphore Semaphore); /** This assignment operator is private for the same reason as the copy constructor. */ Semaphore& operator= (const Semaphore&); /** This assignment operator is private for the same reason as the constructor taking a oslSemaphore argument. */ Semaphore& operator= (oslSemaphore); }; } #endif /* __cplusplus */ #endif /* _OSL_SEMAPHORE_HXX_ */ <|endoftext|>
<commit_before>/* * msrSyncBlockCode.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include <boost/asio.hpp> #include "scheduler.h" #include "network.h" #include "msrSyncBlockCode.h" #include "msrSyncMessages.h" #include "msrSyncEvents.h" #include "configStat.h" #include "trace.h" using namespace std; using namespace BlinkyBlocks; #define COLOR_CHANGE_PERIOD_USEC (2*1000*1000) #define SIMULATION_DURATION_USEC (10*60*1000*1000) #define SYNCHRONIZATION #define SYNC_PERIOD (10*1000*1000) #define COM_DELAY (6*1000) #define LIMIT_NUM_ROUNDS 10 //#define PRINT_NODE_INFO #define INFO_NODE_ID 2 msrSyncBlockCode::msrSyncBlockCode(BlinkyBlocksBlock *host): BlinkyBlocksBlockCode(host) { a = 1; b = 0; round = 0; OUTPUT << "msrSyncBlockCode constructor" << endl; } msrSyncBlockCode::~msrSyncBlockCode() { OUTPUT << "msrSyncBlockCode destructor" << endl; } void msrSyncBlockCode::init() { //BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; /*uint64_t time = 0; while (time<SIMULATION_DURATION_USEC) { uint64_t globalTime = bb->getSchedulerTimeForLocalTime(time); Color c = getColor(time/COLOR_CHANGE_PERIOD_USEC); BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(globalTime,bb,c)); time += COLOR_CHANGE_PERIOD_USEC; }*/ #ifdef SYNCHRONIZATION if(hostBlock->blockId == 1) { // Time leader BlinkyBlocks::getScheduler()->schedule(new MsrSyncEvent(BaseSimulator::getScheduler()->now(),hostBlock)); } #endif } void msrSyncBlockCode::startup() { stringstream info; //BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info << " Starting msrSyncBlockCode in block " << hostBlock->blockId; BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); init(); } void msrSyncBlockCode::processLocalEvent(EventPtr pev) { stringstream info; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info.str(""); OUTPUT << bb->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; switch (pev->eventType) { case EVENT_SET_COLOR: { Color color = (boost::static_pointer_cast<SetColorEvent>(pev))->color; bb->setColor(color); info << "set color "<< color << endl; } break; case EVENT_MSRSYNC: { round++; info << "MASTER sync " << round; #ifdef PRINT_NODE_INFO cout << "MASTER SYNC " << getTime() << endl; #endif synchronize(NULL,getTime()); // schedule the next sync round if (round < LIMIT_NUM_ROUNDS) { uint64_t nextSync = hostBlock->getSchedulerTimeForLocalTime(hostBlock->getTime()+SYNC_PERIOD); //cout << nextSync << " " << BaseSimulator::getScheduler()->now() << endl; // or based on global time now ? BaseSimulator::getScheduler()->now()+SYNC_PERIOD BlinkyBlocks::getScheduler()->schedule(new MsrSyncEvent(nextSync,hostBlock)); } } break; case EVENT_NI_RECEIVE: { MessagePtr message = (boost::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; P2PNetworkInterface * recvInterface = message->destinationInterface; switch(message->type) { case SYNC_MSG_ID : { SyncMessagePtr recvMessage = boost::static_pointer_cast<SyncMessage>(message); info << "sync msg " << recvMessage->getRound(); //cout << "@" << hostBlock->blockId << ": " << getTime() << "/" << globalTime << endl; if (recvMessage->getRound() > round) { round = recvMessage->getRound(); uint64_t globalTime = recvMessage->getTime() + COM_DELAY; uint64_t localTime = hostBlock->getTime(); // window of 5 last measures syncPoints.push_back(make_pair(localTime,globalTime)); #ifdef PRINT_NODE_INFO if (hostBlock->blockId == INFO_NODE_ID) { cout << "Reception time: " << BaseSimulator::getScheduler()->now()/1000 << endl; cout << "a: " << a << endl; cout << "estimation: " << getTime()/1000 << "(" << hostBlock->getTime()/1000 << ")" << ", reception: " << recvMessage->getTime()/1000 << ", => " << globalTime/1000 << endl; } #endif error.push_back(abs(((double)getTime()-(double)globalTime)/1000)); if (syncPoints.size() > 5) { syncPoints.erase(syncPoints.begin()); } adjust(); #ifdef PRINT_NODE_INFO if (hostBlock->blockId == INFO_NODE_ID) { cout << "@" << hostBlock->blockId << " a: " << a << endl; } #endif synchronize(recvInterface, globalTime); } if (round == LIMIT_NUM_ROUNDS) { // display error vector #ifdef PRINT_NODE_INFO if (hostBlock->blockId == INFO_NODE_ID) { cout << "@" << hostBlock->blockId << " error: "; for (vector<uint64_t>::iterator it = error.begin() ; it != error.end(); it++){ cout << *it << " "; } cout << endl; } #endif } } break; default: ERRPUT << "*** ERROR *** : unknown message" << message->id << endl; } } break; default: ERRPUT << "*** ERROR *** : unknown local event" << endl; break; } if (info.str() != "") { BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } } Color msrSyncBlockCode::getColor(uint64_t time) { Color colors[6] = {RED,GREEN,YELLOW,BLUE,GREY,PINK}; int c = time%6; return colors[c]; } uint64_t msrSyncBlockCode::getTime() { return a*(double)hostBlock->getTime() + b; } void msrSyncBlockCode::synchronize(P2PNetworkInterface *exception, uint64_t globalTime) { list <P2PNetworkInterface*>::iterator it; for (it = hostBlock->getP2PNetworkInterfaceList().begin(); it !=hostBlock->getP2PNetworkInterfaceList().end(); it++) { if ((*it)->connectedInterface && (*it != exception)) { SyncMessage *message = new SyncMessage(globalTime,round); BaseSimulator::getScheduler()->schedule(new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(), message,*it)); } } } void msrSyncBlockCode::adjust() { // Linear regression (same as in hardware bb) // https://github.com/claytronics/oldbb/blob/master/build/src-bobby/system/clock.bb // x: local time // y: global time double xAvg = 0, yAvg = 0; double sum1 = 0, sum2 = 0; if (syncPoints.size() == 0) { a = 1; return; } if (syncPoints.size() == 1) { if (syncPoints.begin()->first != 0) { a = syncPoints.begin()->second / syncPoints.begin()->first; } else { a = 1; } //A = 1; return; } for (vector<pair<uint64_t,uint64_t> >::iterator it = syncPoints.begin() ; it != syncPoints.end(); it++){ xAvg += it->first; yAvg += it->second; } xAvg = xAvg/syncPoints.size(); yAvg = yAvg/syncPoints.size(); for (vector<pair<uint64_t,uint64_t> >::iterator it = syncPoints.begin() ; it != syncPoints.end(); it++){ sum1 += (it->first - xAvg) * (it->second - yAvg); sum2 += pow(it->first - xAvg,2); } a = sum1/sum2; // b ? } BlinkyBlocks::BlinkyBlocksBlockCode* msrSyncBlockCode::buildNewBlockCode(BlinkyBlocksBlock *host) { return(new msrSyncBlockCode(host)); } <commit_msg>study noise impact on clock synchronization<commit_after>/* * msrSyncBlockCode.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include <boost/asio.hpp> #include "scheduler.h" #include "network.h" #include "msrSyncBlockCode.h" #include "msrSyncMessages.h" #include "msrSyncEvents.h" #include "configStat.h" #include "trace.h" using namespace std; using namespace BlinkyBlocks; #define COLOR_CHANGE_PERIOD_USEC (2*1000*1000) #define SIMULATION_DURATION_USEC (10*60*1000*1000) #define SYNCHRONIZATION #define SYNC_PERIOD (10*1000*1000) #define COM_DELAY (6*1000) #define LIMIT_NUM_ROUNDS 10 #define PRINT_NODE_INFO #define INFO_NODE_ID 200 msrSyncBlockCode::msrSyncBlockCode(BlinkyBlocksBlock *host): BlinkyBlocksBlockCode(host) { a = 1; b = 0; round = 0; OUTPUT << "msrSyncBlockCode constructor" << endl; } msrSyncBlockCode::~msrSyncBlockCode() { OUTPUT << "msrSyncBlockCode destructor" << endl; } void msrSyncBlockCode::init() { //BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; /*uint64_t time = 0; while (time<SIMULATION_DURATION_USEC) { uint64_t globalTime = bb->getSchedulerTimeForLocalTime(time); Color c = getColor(time/COLOR_CHANGE_PERIOD_USEC); BlinkyBlocks::getScheduler()->schedule(new SetColorEvent(globalTime,bb,c)); time += COLOR_CHANGE_PERIOD_USEC; }*/ #ifdef SYNCHRONIZATION if(hostBlock->blockId == 1) { // Time leader BlinkyBlocks::getScheduler()->schedule(new MsrSyncEvent(BaseSimulator::getScheduler()->now(),hostBlock)); } #endif } void msrSyncBlockCode::startup() { stringstream info; //BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info << " Starting msrSyncBlockCode in block " << hostBlock->blockId; BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); init(); } void msrSyncBlockCode::processLocalEvent(EventPtr pev) { stringstream info; BlinkyBlocksBlock *bb = (BlinkyBlocksBlock*) hostBlock; info.str(""); OUTPUT << bb->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; switch (pev->eventType) { case EVENT_SET_COLOR: { Color color = (boost::static_pointer_cast<SetColorEvent>(pev))->color; bb->setColor(color); info << "set color "<< color << endl; } break; case EVENT_MSRSYNC: { round++; info << "MASTER sync " << round; #ifdef PRINT_NODE_INFO // cout << "MASTER SYNC " << getTime() << endl; #endif synchronize(NULL,getTime()); // schedule the next sync round if (round < LIMIT_NUM_ROUNDS) { uint64_t nextSync = hostBlock->getSchedulerTimeForLocalTime(hostBlock->getTime()+SYNC_PERIOD); //cout << nextSync << " " << BaseSimulator::getScheduler()->now() << endl; // or based on global time now ? BaseSimulator::getScheduler()->now()+SYNC_PERIOD BlinkyBlocks::getScheduler()->schedule(new MsrSyncEvent(nextSync,hostBlock)); } } break; case EVENT_NI_RECEIVE: { MessagePtr message = (boost::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; P2PNetworkInterface * recvInterface = message->destinationInterface; switch(message->type) { case SYNC_MSG_ID : { SyncMessagePtr recvMessage = boost::static_pointer_cast<SyncMessage>(message); info << "sync msg " << recvMessage->getRound(); //cout << "@" << hostBlock->blockId << ": " << getTime() << "/" << globalTime << endl; if (recvMessage->getRound() > round) { round = recvMessage->getRound(); uint64_t globalTime = recvMessage->getTime() + COM_DELAY; uint64_t localTime = hostBlock->getTime(); // window of 5 last measures syncPoints.push_back(make_pair(localTime,globalTime)); #ifdef PRINT_NODE_INFO if (hostBlock->blockId == INFO_NODE_ID) { cout << "Reception time: " << BaseSimulator::getScheduler()->now()/1000 << endl; cout << "a: " << a << endl; cout << "estimation: " << getTime()/1000 << "(" << hostBlock->getTime()/1000 << ")" << ", reception: " << recvMessage->getTime()/1000 << ", => " << globalTime/1000 << endl; } #endif error.push_back(abs(((double)getTime()-(double)globalTime)/1000)); if (syncPoints.size() > 5) { syncPoints.erase(syncPoints.begin()); } adjust(); #ifdef PRINT_NODE_INFO if (hostBlock->blockId == INFO_NODE_ID) { cout << "@" << hostBlock->blockId << " a: " << a << endl; } #endif synchronize(recvInterface, globalTime); if (round == LIMIT_NUM_ROUNDS) { // display error vector #ifdef PRINT_NODE_INFO // if (hostBlock->blockId == INFO_NODE_ID) { cout << "@" << hostBlock->blockId << " error: "; for (vector<uint64_t>::iterator it = error.begin() ; it != error.end(); it++){ cout << *it << " "; } cout << endl; // } #endif } } } break; default: ERRPUT << "*** ERROR *** : unknown message" << message->id << endl; } } break; default: ERRPUT << "*** ERROR *** : unknown local event" << endl; break; } if (info.str() != "") { BlinkyBlocks::getScheduler()->trace(info.str(),hostBlock->blockId); } } Color msrSyncBlockCode::getColor(uint64_t time) { Color colors[6] = {RED,GREEN,YELLOW,BLUE,GREY,PINK}; int c = time%6; return colors[c]; } uint64_t msrSyncBlockCode::getTime() { return a*(double)hostBlock->getTime() + b; } void msrSyncBlockCode::synchronize(P2PNetworkInterface *exception, uint64_t globalTime) { list <P2PNetworkInterface*>::iterator it; for (it = hostBlock->getP2PNetworkInterfaceList().begin(); it !=hostBlock->getP2PNetworkInterfaceList().end(); it++) { if ((*it)->connectedInterface && (*it != exception)) { SyncMessage *message = new SyncMessage(globalTime,round); BaseSimulator::getScheduler()->schedule(new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(), message,*it)); } } } void msrSyncBlockCode::adjust() { // Linear regression (same as in hardware bb) // https://github.com/claytronics/oldbb/blob/master/build/src-bobby/system/clock.bb // x: local time // y: global time double xAvg = 0, yAvg = 0; double sum1 = 0, sum2 = 0; if (syncPoints.size() == 0) { a = 1; return; } if (syncPoints.size() == 1) { if (syncPoints.begin()->first != 0) { a = syncPoints.begin()->second / syncPoints.begin()->first; } else { a = 1; } //A = 1; return; } for (vector<pair<uint64_t,uint64_t> >::iterator it = syncPoints.begin() ; it != syncPoints.end(); it++){ xAvg += it->first; yAvg += it->second; } xAvg = xAvg/syncPoints.size(); yAvg = yAvg/syncPoints.size(); for (vector<pair<uint64_t,uint64_t> >::iterator it = syncPoints.begin() ; it != syncPoints.end(); it++){ sum1 += (it->first - xAvg) * (it->second - yAvg); sum2 += pow(it->first - xAvg,2); } a = sum1/sum2; // b ? } BlinkyBlocks::BlinkyBlocksBlockCode* msrSyncBlockCode::buildNewBlockCode(BlinkyBlocksBlock *host) { return(new msrSyncBlockCode(host)); } <|endoftext|>
<commit_before>/*************************************************************************** [email protected] - last modified on 28/11/2013 // //Lauches KStar analysis with rsn mini package //Allows basic configuration of pile-up check and event cuts // ****************************************************************************/ enum pairYCutSet { kPairDefault=0, kCentral //=1 }; enum eventCutSet { kEvtDefault=0, kNoPileUpCut, //=1 kDefaultVtx12,//=2 kDefaultVtx8, //=3 kDefaultVtx5, //=4 kMCEvtDefault, //=5 kSpecial1, //=6 kSpecial2, //=7 kNoEvtSel, //=8 kSpecial3//=9 }; enum eventMixConfig { kDisabled = -1, kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10 k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10 k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5 k5Evts5Cent }; AliRsnMiniAnalysisTask * AddTaskKStarPP8TeV_PID ( Bool_t isMC = kFALSE, Bool_t isPP = kTRUE, TString outNameSuffix = "tpc2stof3sveto", Int_t evtCutSetID = 0, Int_t pairCutSetID = 0, Int_t mixingConfigID = 0, Int_t aodFilterBit = 5, Int_t customQualityCutsID = -1, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, Float_t nsigmaPi = 2.0, Float_t nsigmaKa = 2.0, Bool_t enableMonitor = kTRUE, Bool_t IsMcTrueOnly = kFALSE, TString monitorOpt = "NoSIGN", Bool_t useMixLS = 0, Bool_t checkReflex = 0, AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt ) { //------------------------------------------- // event cuts //------------------------------------------- UInt_t triggerMask = AliVEvent::kINT7;//A Khuntia // if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny; Bool_t rejectPileUp = kTRUE; // Double_t vtxZcut = 10.0; //cm, default cut on vtx z if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} //cm if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} //cm if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}//cm if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}//cm if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off //------------------------------------------- //pair cuts //------------------------------------------- Double_t minYlab = -0.5; Double_t maxYlab = 0.5; if (pairCutSetID==pairYCutSet::kCentral) { //|y_cm|<0.3 minYlab = -0.3; maxYlab = 0.3; } //------------------------------------------- //mixing settings //------------------------------------------- Int_t nmix = 0; Float_t maxDiffVzMix = 1.0; Float_t maxDiffMultMix = 10.0; if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;} if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;} if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;} if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;} // // -- INITIALIZATION ---------------------------------------------------------------------------- // retrieve analysis manager // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAnalysisTaskTOFKStar", "No analysis manager to connect to."); return NULL; } // create the task and configure TString taskName = Form("TOFKStar%s%s_%i%i", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate ); AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC); //task->UseESDTriggerMask(triggerMask); //ESD //task->SelectCollisionCandidates(triggerMask); //AOD if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); //AOD if (isPP) task->UseMultiplicity("QUALITY"); else task->UseCentrality("V0M"); // set event mixing options task->UseContinuousMix(); //task->UseBinnedMix(); task->SetNMix(nmix); task->SetMaxDiffVz(maxDiffVzMix); task->SetMaxDiffMult(maxDiffMultMix); ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix)); mgr->AddTask(task); // // cut on primary vertex: // - 2nd argument --> |Vz| range // - 3rd argument --> minimum required number of contributors to vtx // - 4th argument --> tells if TPC stand-alone vertexes must be accepted AliRsnCutPrimaryVertex *cutVertex=0; if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){ cutVertex = new AliRsnCutPrimaryVertex("cutVertex", vtxZcut, 0, kFALSE); if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ(); }//vertex loop if (isPP && (!isMC)) { cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF")); //cutVertex->SetCheckZResolutionSPD();//A Khuntia //cutVertex->SetCheckDispersionSPD();//A Khuntia //cutVertex->SetCheckZDifferenceSPDTrack();//A Khuntia } ///////----------AKhuntia----------////// /*AliRsnCutEventUtils* cutEventUtils=0; cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp); cutEventUtils->SetCheckIncompleteDAQ(); cutEventUtils->SetCheckSPDClusterVsTrackletBG();*/ //------------------------------------ // define and fill cut set for event cut AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent); eventCuts->AddCut(cutVertex); eventCuts->SetCutScheme(Form("%s", cutVertex->GetName())); task->SetEventCuts(eventCuts); // // -- EVENT-ONLY COMPUTATIONS ------------------------------------------------------------------- // //vertex Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE); AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT"); outVtx->AddAxis(vtxID, 240, -12.0, 12.0); //multiplicity or centrality Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE); AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT"); if (isPP) outMult->AddAxis(multID, 400, 0.0, 400.0); else outMult->AddAxis(multID, 100, 0.0, 100.0); TH2F* hvz=new TH2F("hVzVsCent","", 100, 0., 100., 240, -12.0, 12.0); task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member TH2F* hmc=new TH2F("MultiVsCent","", 100, 0., 100., 400, 0., 400.); hmc->GetYaxis()->SetTitle("QUALITY"); task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member // // -- PAIR CUTS (common to all resonances) ------------------------------------------------------ // AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange); cutY->SetRangeD(minYlab, maxYlab); AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother); cutsPair->AddCut(cutY); cutsPair->SetCutScheme(cutY->GetName()); // // -- CONFIG ANALYSIS -------------------------------------------------------------------------- // gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP8TeV_PID.C"); //gROOT->LoadMacro("ConfigKStarPP8TeV_PID.C"); if (!ConfigKStarPP8TeV_PID(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0; // // -- CONTAINERS -------------------------------------------------------------------------------- // TString outputFileName = AliAnalysisManager::GetCommonFileName(); // outputFileName += ":Rsn"; Printf("AddAnalysisTaskTOFKStar - Set OutputFileName : \n %s\n", outputFileName.Data() ); AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, output); return task; } <commit_msg>bug found in the macro and solved it for KStar analysis in pp at 8 TeV<commit_after>/*************************************************************************** [email protected] - last modified on 28/11/2013 // //Lauches KStar analysis with rsn mini package //Allows basic configuration of pile-up check and event cuts // ****************************************************************************/ enum pairYCutSet { kPairDefault=0, kCentral //=1 }; enum eventCutSet { kEvtDefault=0, kNoPileUpCut, //=1 kDefaultVtx12,//=2 kDefaultVtx8, //=3 kDefaultVtx5, //=4 kMCEvtDefault, //=5 kSpecial1, //=6 kSpecial2, //=7 kNoEvtSel, //=8 kSpecial3//=9 }; enum eventMixConfig { kDisabled = -1, kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10 k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10 k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5 k5Evts5Cent }; AliRsnMiniAnalysisTask * AddTaskKStarPP8TeV_PID ( Bool_t isMC = kFALSE, Bool_t isPP = kTRUE, TString outNameSuffix = "tpc2stof3sveto", Int_t evtCutSetID = 0, Int_t pairCutSetID = 0, Int_t mixingConfigID = 0, Int_t aodFilterBit = 5, Int_t customQualityCutsID = -1, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, Float_t nsigmaPi = 2.0, Float_t nsigmaKa = 2.0, Bool_t enableMonitor = kTRUE, Bool_t IsMcTrueOnly = kFALSE, TString monitorOpt = "NoSIGN", Bool_t useMixLS = 0, Bool_t checkReflex = 0, AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt ) { //------------------------------------------- // event cuts //------------------------------------------- UInt_t triggerMask = AliVEvent::kINT7;//A Khuntia // if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny; Bool_t rejectPileUp = kTRUE; // Double_t vtxZcut = 10.0; //cm, default cut on vtx z if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} //cm if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} //cm if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}//cm if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}//cm if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off //------------------------------------------- //pair cuts //------------------------------------------- Double_t minYlab = -0.5; Double_t maxYlab = 0.5; if (pairCutSetID==pairYCutSet::kCentral) { //|y_cm|<0.3 minYlab = -0.3; maxYlab = 0.3; } //------------------------------------------- //mixing settings //------------------------------------------- Int_t nmix = 0; Float_t maxDiffVzMix = 1.0; Float_t maxDiffMultMix = 10.0; if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;} if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;} if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;} if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;} // // -- INITIALIZATION ---------------------------------------------------------------------------- // retrieve analysis manager // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAnalysisTaskTOFKStar", "No analysis manager to connect to."); return NULL; } // create the task and configure TString taskName = Form("TOFKStar%s%s_%i%i", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate ); AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC); //task->UseESDTriggerMask(triggerMask); //ESD //task->SelectCollisionCandidates(triggerMask); //AOD if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); //AOD if (isPP) task->UseMultiplicity("QUALITY"); else task->UseCentrality("V0M"); // set event mixing options task->UseContinuousMix(); //task->UseBinnedMix(); task->SetNMix(nmix); task->SetMaxDiffVz(maxDiffVzMix); task->SetMaxDiffMult(maxDiffMultMix); ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix)); mgr->AddTask(task); // // cut on primary vertex: // - 2nd argument --> |Vz| range // - 3rd argument --> minimum required number of contributors to vtx // - 4th argument --> tells if TPC stand-alone vertexes must be accepted AliRsnCutPrimaryVertex *cutVertex=0; if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){ cutVertex = new AliRsnCutPrimaryVertex("cutVertex", vtxZcut, 0, kFALSE); if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ(); }//vertex loop if (isPP && (!isMC)&&cutVertex) { cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF")); //cutVertex->SetCheckZResolutionSPD();//A Khuntia //cutVertex->SetCheckDispersionSPD();//A Khuntia //cutVertex->SetCheckZDifferenceSPDTrack();//A Khuntia } ///////----------AKhuntia----------////// /*AliRsnCutEventUtils* cutEventUtils=0; cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp); cutEventUtils->SetCheckIncompleteDAQ(); cutEventUtils->SetCheckSPDClusterVsTrackletBG();*/ //------------------------------------ // define and fill cut set for event cut AliRsnCutSet* eventCuts=0; if(cutVertex){ eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent); eventCuts->AddCut(cutVertex); eventCuts->SetCutScheme(Form("%s", cutVertex->GetName())); task->SetEventCuts(eventCuts); } // // -- EVENT-ONLY COMPUTATIONS ------------------------------------------------------------------- // //vertex Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE); AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT"); outVtx->AddAxis(vtxID, 240, -12.0, 12.0); //multiplicity or centrality Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE); AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT"); if (isPP) outMult->AddAxis(multID, 400, 0.0, 400.0); else outMult->AddAxis(multID, 100, 0.0, 100.0); TH2F* hvz=new TH2F("hVzVsCent","", 100, 0., 100., 240, -12.0, 12.0); task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member TH2F* hmc=new TH2F("MultiVsCent","", 100, 0., 100., 400, 0., 400.); hmc->GetYaxis()->SetTitle("QUALITY"); task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member // // -- PAIR CUTS (common to all resonances) ------------------------------------------------------ // AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange); cutY->SetRangeD(minYlab, maxYlab); AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother); cutsPair->AddCut(cutY); cutsPair->SetCutScheme(cutY->GetName()); // // -- CONFIG ANALYSIS -------------------------------------------------------------------------- // gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP8TeV_PID.C"); //gROOT->LoadMacro("ConfigKStarPP8TeV_PID.C"); if (!ConfigKStarPP8TeV_PID(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0; // // -- CONTAINERS -------------------------------------------------------------------------------- // TString outputFileName = AliAnalysisManager::GetCommonFileName(); // outputFileName += ":Rsn"; Printf("AddAnalysisTaskTOFKStar - Set OutputFileName : \n %s\n", outputFileName.Data() ); AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, output); return task; } <|endoftext|>
<commit_before><commit_msg>Handle missing SIZE_MAX<commit_after><|endoftext|>
<commit_before>/* * DensifyPointCloud.cpp * * Copyright (c) 2014-2015 SEACAVE * * Author(s): * * cDc <[email protected]> * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. */ #include "../../libs/MVS/Common.h" #include "../../libs/MVS/Scene.h" #include <boost/program_options.hpp> using namespace MVS; // D E F I N E S /////////////////////////////////////////////////// #define APPNAME _T("DensifyPointCloud") // S T R U C T S /////////////////////////////////////////////////// namespace OPT { String strInputFileName; String strOutputFileName; String strMeshFileName; String strDenseConfigFileName; float fSampleMesh; int thFilterPointCloud; int nArchiveType; int nProcessPriority; unsigned nMaxThreads; String strConfigFileName; boost::program_options::variables_map vm; } // namespace OPT // initialize and parse the command line parameters bool Initialize(size_t argc, LPCTSTR* argv) { // initialize log and console OPEN_LOG(); OPEN_LOGCONSOLE(); // group of options allowed only on command line boost::program_options::options_description generic("Generic options"); generic.add_options() ("help,h", "produce this help message") ("working-folder,w", boost::program_options::value<std::string>(&WORKING_FOLDER), "working directory (default current directory)") ("config-file,c", boost::program_options::value<std::string>(&OPT::strConfigFileName)->default_value(APPNAME _T(".cfg")), "file name containing program options") ("archive-type", boost::program_options::value(&OPT::nArchiveType)->default_value(2), "project archive type: 0-text, 1-binary, 2-compressed binary") ("process-priority", boost::program_options::value(&OPT::nProcessPriority)->default_value(-1), "process priority (below normal by default)") ("max-threads", boost::program_options::value(&OPT::nMaxThreads)->default_value(0), "maximum number of threads (0 for using all available cores)") #if TD_VERBOSE != TD_VERBOSE_OFF ("verbosity,v", boost::program_options::value(&g_nVerbosityLevel)->default_value( #if TD_VERBOSE == TD_VERBOSE_DEBUG 3 #else 2 #endif ), "verbosity level") #endif ; // group of options allowed both on command line and in config file unsigned nResolutionLevel; unsigned nMaxResolution; unsigned nMinResolution; unsigned nNumViews; unsigned nMinViewsFuse; unsigned nOptimize; unsigned nEstimateColors; unsigned nEstimateNormals; boost::program_options::options_description config("Densify options"); config.add_options() ("input-file,i", boost::program_options::value<std::string>(&OPT::strInputFileName), "input filename containing camera poses and image list") ("output-file,o", boost::program_options::value<std::string>(&OPT::strOutputFileName), "output filename for storing the dense point-cloud") ("resolution-level", boost::program_options::value(&nResolutionLevel)->default_value(1), "how many times to scale down the images before point cloud computation") ("max-resolution", boost::program_options::value(&nMaxResolution)->default_value(3200), "do not scale images higher than this resolution") ("min-resolution", boost::program_options::value(&nMinResolution)->default_value(640), "do not scale images lower than this resolution") ("number-views", boost::program_options::value(&nNumViews)->default_value(5), "number of views used for depth-map estimation (0 - all neighbor views available)") ("number-views-fuse", boost::program_options::value(&nMinViewsFuse)->default_value(3), "minimum number of images that agrees with an estimate during fusion in order to consider it inlier") ("optimize", boost::program_options::value(&nOptimize)->default_value(7), "filter used after depth-map estimation (0 - disabled, 1 - remove speckles, 2 - fill gaps, 4 - cross-adjust)") ("estimate-colors", boost::program_options::value(&nEstimateColors)->default_value(2), "estimate the colors for the dense point-cloud") ("estimate-normals", boost::program_options::value(&nEstimateNormals)->default_value(0), "estimate the normals for the dense point-cloud") ("sample-mesh", boost::program_options::value(&OPT::fSampleMesh)->default_value(0.f), "uniformly samples points on a mesh (0 - disabled, <0 - number of points, >0 - sample density per square unit)") ("filter-point-cloud", boost::program_options::value(&OPT::thFilterPointCloud)->default_value(0), "filter dense point-cloud based on visibility (0 - disabled)") ; // hidden options, allowed both on command line and // in config file, but will not be shown to the user boost::program_options::options_description hidden("Hidden options"); hidden.add_options() ("dense-config-file", boost::program_options::value<std::string>(&OPT::strDenseConfigFileName), "optional configuration file for the densifier (overwritten by the command line options)") ; boost::program_options::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); boost::program_options::options_description config_file_options; config_file_options.add(config).add(hidden); boost::program_options::positional_options_description p; p.add("input-file", -1); try { // parse command line options boost::program_options::store(boost::program_options::command_line_parser((int)argc, argv).options(cmdline_options).positional(p).run(), OPT::vm); boost::program_options::notify(OPT::vm); INIT_WORKING_FOLDER; // parse configuration file std::ifstream ifs(MAKE_PATH_SAFE(OPT::strConfigFileName)); if (ifs) { boost::program_options::store(parse_config_file(ifs, config_file_options), OPT::vm); boost::program_options::notify(OPT::vm); } } catch (const std::exception& e) { LOG(e.what()); return false; } // initialize the log file OPEN_LOGFILE(MAKE_PATH(APPNAME _T("-")+Util::getUniqueName(0)+_T(".log")).c_str()); // print application details: version and command line Util::LogBuild(); LOG(_T("Command line:%s"), Util::CommandLineToString(argc, argv).c_str()); // validate input Util::ensureValidPath(OPT::strInputFileName); Util::ensureUnifySlash(OPT::strInputFileName); if (OPT::vm.count("help") || OPT::strInputFileName.IsEmpty()) { boost::program_options::options_description visible("Available options"); visible.add(generic).add(config); GET_LOG() << visible; } if (OPT::strInputFileName.IsEmpty()) return false; // initialize optional options Util::ensureValidPath(OPT::strOutputFileName); Util::ensureUnifySlash(OPT::strOutputFileName); if (OPT::strOutputFileName.IsEmpty()) OPT::strOutputFileName = Util::getFileFullName(OPT::strInputFileName) + _T("_dense.mvs"); // init dense options if (!Util::isFullPath(OPT::strDenseConfigFileName)) OPT::strDenseConfigFileName = MAKE_PATH(OPT::strDenseConfigFileName); OPTDENSE::init(); const bool bValidConfig(OPTDENSE::oConfig.Load(OPT::strDenseConfigFileName)); OPTDENSE::update(); OPTDENSE::nResolutionLevel = nResolutionLevel; OPTDENSE::nMaxResolution = nMaxResolution; OPTDENSE::nMinResolution = nMinResolution; OPTDENSE::nNumViews = nNumViews; OPTDENSE::nMinViewsFuse = nMinViewsFuse; OPTDENSE::nOptimize = nOptimize; OPTDENSE::nEstimateColors = nEstimateColors; OPTDENSE::nEstimateNormals = nEstimateNormals; if (!bValidConfig) OPTDENSE::oConfig.Save(OPT::strDenseConfigFileName); // initialize global options Process::setCurrentProcessPriority((Process::Priority)OPT::nProcessPriority); #ifdef _USE_OPENMP if (OPT::nMaxThreads != 0) omp_set_num_threads(OPT::nMaxThreads); #endif #ifdef _USE_BREAKPAD // start memory dumper MiniDumper::Create(APPNAME, WORKING_FOLDER); #endif Util::Init(); return true; } // finalize application instance void Finalize() { #if TD_VERBOSE != TD_VERBOSE_OFF // print memory statistics Util::LogMemoryInfo(); #endif CLOSE_LOGFILE(); CLOSE_LOGCONSOLE(); CLOSE_LOG(); } int main(int argc, LPCTSTR* argv) { #ifdef _DEBUGINFO // set _crtBreakAlloc index to stop in <dbgheap.c> at allocation _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);// | _CRTDBG_CHECK_ALWAYS_DF); #endif if (!Initialize(argc, argv)) return EXIT_FAILURE; Scene scene(OPT::nMaxThreads); if (OPT::fSampleMesh != 0) { // sample input mesh and export the obtained point-cloud if (!scene.mesh.Load(MAKE_PATH_SAFE(OPT::strInputFileName))) return EXIT_FAILURE; TD_TIMER_START(); PointCloud pointcloud; if (OPT::fSampleMesh > 0) scene.mesh.SamplePoints(OPT::fSampleMesh, 0, pointcloud); else scene.mesh.SamplePoints((unsigned)ROUND2INT(-OPT::fSampleMesh), pointcloud); VERBOSE("Sample mesh completed: %u points (%s)", pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str()); pointcloud.Save(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T(".ply")); Finalize(); return EXIT_SUCCESS; } // load and estimate a dense point-cloud if (!scene.Load(MAKE_PATH_SAFE(OPT::strInputFileName))) return EXIT_FAILURE; if (scene.pointcloud.IsEmpty()) { VERBOSE("error: empty initial point-cloud"); return EXIT_FAILURE; } if (OPT::thFilterPointCloud < 0) { // filter point-cloud based on camera-point visibility intersections scene.PointCloudFilter(OPT::thFilterPointCloud); const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T("_filtered")); scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType); scene.pointcloud.Save(baseFileName+_T(".ply")); Finalize(); return EXIT_SUCCESS; } if ((ARCHIVE_TYPE)OPT::nArchiveType != ARCHIVE_MVS) { TD_TIMER_START(); if (!scene.DenseReconstruction()) return EXIT_FAILURE; VERBOSE("Densifying point-cloud completed: %u points (%s)", scene.pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str()); } // save the final mesh const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))); scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType); scene.pointcloud.Save(baseFileName+_T(".ply")); #if TD_VERBOSE != TD_VERBOSE_OFF if (VERBOSITY_LEVEL > 2) scene.ExportCamerasMLP(baseFileName+_T(".mlp"), baseFileName+_T(".ply")); #endif Finalize(); return EXIT_SUCCESS; } /*----------------------------------------------------------------*/ <commit_msg>dense: fix crash when working directory is provided (#460)<commit_after>/* * DensifyPointCloud.cpp * * Copyright (c) 2014-2015 SEACAVE * * Author(s): * * cDc <[email protected]> * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. */ #include "../../libs/MVS/Common.h" #include "../../libs/MVS/Scene.h" #include <boost/program_options.hpp> using namespace MVS; // D E F I N E S /////////////////////////////////////////////////// #define APPNAME _T("DensifyPointCloud") // S T R U C T S /////////////////////////////////////////////////// namespace OPT { String strInputFileName; String strOutputFileName; String strMeshFileName; String strDenseConfigFileName; float fSampleMesh; int thFilterPointCloud; int nArchiveType; int nProcessPriority; unsigned nMaxThreads; String strConfigFileName; boost::program_options::variables_map vm; } // namespace OPT // initialize and parse the command line parameters bool Initialize(size_t argc, LPCTSTR* argv) { // initialize log and console OPEN_LOG(); OPEN_LOGCONSOLE(); // group of options allowed only on command line boost::program_options::options_description generic("Generic options"); generic.add_options() ("help,h", "produce this help message") ("working-folder,w", boost::program_options::value<std::string>(&WORKING_FOLDER), "working directory (default current directory)") ("config-file,c", boost::program_options::value<std::string>(&OPT::strConfigFileName)->default_value(APPNAME _T(".cfg")), "file name containing program options") ("archive-type", boost::program_options::value(&OPT::nArchiveType)->default_value(2), "project archive type: 0-text, 1-binary, 2-compressed binary") ("process-priority", boost::program_options::value(&OPT::nProcessPriority)->default_value(-1), "process priority (below normal by default)") ("max-threads", boost::program_options::value(&OPT::nMaxThreads)->default_value(0), "maximum number of threads (0 for using all available cores)") #if TD_VERBOSE != TD_VERBOSE_OFF ("verbosity,v", boost::program_options::value(&g_nVerbosityLevel)->default_value( #if TD_VERBOSE == TD_VERBOSE_DEBUG 3 #else 2 #endif ), "verbosity level") #endif ; // group of options allowed both on command line and in config file unsigned nResolutionLevel; unsigned nMaxResolution; unsigned nMinResolution; unsigned nNumViews; unsigned nMinViewsFuse; unsigned nOptimize; unsigned nEstimateColors; unsigned nEstimateNormals; boost::program_options::options_description config("Densify options"); config.add_options() ("input-file,i", boost::program_options::value<std::string>(&OPT::strInputFileName), "input filename containing camera poses and image list") ("output-file,o", boost::program_options::value<std::string>(&OPT::strOutputFileName), "output filename for storing the dense point-cloud") ("resolution-level", boost::program_options::value(&nResolutionLevel)->default_value(1), "how many times to scale down the images before point cloud computation") ("max-resolution", boost::program_options::value(&nMaxResolution)->default_value(3200), "do not scale images higher than this resolution") ("min-resolution", boost::program_options::value(&nMinResolution)->default_value(640), "do not scale images lower than this resolution") ("number-views", boost::program_options::value(&nNumViews)->default_value(5), "number of views used for depth-map estimation (0 - all neighbor views available)") ("number-views-fuse", boost::program_options::value(&nMinViewsFuse)->default_value(3), "minimum number of images that agrees with an estimate during fusion in order to consider it inlier") ("optimize", boost::program_options::value(&nOptimize)->default_value(7), "filter used after depth-map estimation (0 - disabled, 1 - remove speckles, 2 - fill gaps, 4 - cross-adjust)") ("estimate-colors", boost::program_options::value(&nEstimateColors)->default_value(2), "estimate the colors for the dense point-cloud") ("estimate-normals", boost::program_options::value(&nEstimateNormals)->default_value(0), "estimate the normals for the dense point-cloud") ("sample-mesh", boost::program_options::value(&OPT::fSampleMesh)->default_value(0.f), "uniformly samples points on a mesh (0 - disabled, <0 - number of points, >0 - sample density per square unit)") ("filter-point-cloud", boost::program_options::value(&OPT::thFilterPointCloud)->default_value(0), "filter dense point-cloud based on visibility (0 - disabled)") ; // hidden options, allowed both on command line and // in config file, but will not be shown to the user boost::program_options::options_description hidden("Hidden options"); hidden.add_options() ("dense-config-file", boost::program_options::value<std::string>(&OPT::strDenseConfigFileName), "optional configuration file for the densifier (overwritten by the command line options)") ; boost::program_options::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); boost::program_options::options_description config_file_options; config_file_options.add(config).add(hidden); boost::program_options::positional_options_description p; p.add("input-file", -1); try { // parse command line options boost::program_options::store(boost::program_options::command_line_parser((int)argc, argv).options(cmdline_options).positional(p).run(), OPT::vm); boost::program_options::notify(OPT::vm); INIT_WORKING_FOLDER; // parse configuration file std::ifstream ifs(MAKE_PATH_SAFE(OPT::strConfigFileName)); if (ifs) { boost::program_options::store(parse_config_file(ifs, config_file_options), OPT::vm); boost::program_options::notify(OPT::vm); } } catch (const std::exception& e) { LOG(e.what()); return false; } // initialize the log file OPEN_LOGFILE(MAKE_PATH(APPNAME _T("-")+Util::getUniqueName(0)+_T(".log")).c_str()); // print application details: version and command line Util::LogBuild(); LOG(_T("Command line:%s"), Util::CommandLineToString(argc, argv).c_str()); // validate input Util::ensureValidPath(OPT::strInputFileName); Util::ensureUnifySlash(OPT::strInputFileName); if (OPT::vm.count("help") || OPT::strInputFileName.IsEmpty()) { boost::program_options::options_description visible("Available options"); visible.add(generic).add(config); GET_LOG() << visible; } if (OPT::strInputFileName.IsEmpty()) return false; // initialize optional options Util::ensureValidPath(OPT::strOutputFileName); Util::ensureUnifySlash(OPT::strOutputFileName); if (OPT::strOutputFileName.IsEmpty()) OPT::strOutputFileName = Util::getFileFullName(OPT::strInputFileName) + _T("_dense.mvs"); // init dense options if (!OPT::strDenseConfigFileName.IsEmpty()) OPT::strDenseConfigFileName = MAKE_PATH_SAFE(OPT::strDenseConfigFileName); OPTDENSE::init(); const bool bValidConfig(OPTDENSE::oConfig.Load(OPT::strDenseConfigFileName)); OPTDENSE::update(); OPTDENSE::nResolutionLevel = nResolutionLevel; OPTDENSE::nMaxResolution = nMaxResolution; OPTDENSE::nMinResolution = nMinResolution; OPTDENSE::nNumViews = nNumViews; OPTDENSE::nMinViewsFuse = nMinViewsFuse; OPTDENSE::nOptimize = nOptimize; OPTDENSE::nEstimateColors = nEstimateColors; OPTDENSE::nEstimateNormals = nEstimateNormals; if (!bValidConfig && !OPT::strDenseConfigFileName.IsEmpty()) OPTDENSE::oConfig.Save(OPT::strDenseConfigFileName); // initialize global options Process::setCurrentProcessPriority((Process::Priority)OPT::nProcessPriority); #ifdef _USE_OPENMP if (OPT::nMaxThreads != 0) omp_set_num_threads(OPT::nMaxThreads); #endif #ifdef _USE_BREAKPAD // start memory dumper MiniDumper::Create(APPNAME, WORKING_FOLDER); #endif Util::Init(); return true; } // finalize application instance void Finalize() { #if TD_VERBOSE != TD_VERBOSE_OFF // print memory statistics Util::LogMemoryInfo(); #endif CLOSE_LOGFILE(); CLOSE_LOGCONSOLE(); CLOSE_LOG(); } int main(int argc, LPCTSTR* argv) { #ifdef _DEBUGINFO // set _crtBreakAlloc index to stop in <dbgheap.c> at allocation _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);// | _CRTDBG_CHECK_ALWAYS_DF); #endif if (!Initialize(argc, argv)) return EXIT_FAILURE; Scene scene(OPT::nMaxThreads); if (OPT::fSampleMesh != 0) { // sample input mesh and export the obtained point-cloud if (!scene.mesh.Load(MAKE_PATH_SAFE(OPT::strInputFileName))) return EXIT_FAILURE; TD_TIMER_START(); PointCloud pointcloud; if (OPT::fSampleMesh > 0) scene.mesh.SamplePoints(OPT::fSampleMesh, 0, pointcloud); else scene.mesh.SamplePoints((unsigned)ROUND2INT(-OPT::fSampleMesh), pointcloud); VERBOSE("Sample mesh completed: %u points (%s)", pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str()); pointcloud.Save(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T(".ply")); Finalize(); return EXIT_SUCCESS; } // load and estimate a dense point-cloud if (!scene.Load(MAKE_PATH_SAFE(OPT::strInputFileName))) return EXIT_FAILURE; if (scene.pointcloud.IsEmpty()) { VERBOSE("error: empty initial point-cloud"); return EXIT_FAILURE; } if (OPT::thFilterPointCloud < 0) { // filter point-cloud based on camera-point visibility intersections scene.PointCloudFilter(OPT::thFilterPointCloud); const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T("_filtered")); scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType); scene.pointcloud.Save(baseFileName+_T(".ply")); Finalize(); return EXIT_SUCCESS; } if ((ARCHIVE_TYPE)OPT::nArchiveType != ARCHIVE_MVS) { TD_TIMER_START(); if (!scene.DenseReconstruction()) return EXIT_FAILURE; VERBOSE("Densifying point-cloud completed: %u points (%s)", scene.pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str()); } // save the final mesh const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))); scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType); scene.pointcloud.Save(baseFileName+_T(".ply")); #if TD_VERBOSE != TD_VERBOSE_OFF if (VERBOSITY_LEVEL > 2) scene.ExportCamerasMLP(baseFileName+_T(".mlp"), baseFileName+_T(".ply")); #endif Finalize(); return EXIT_SUCCESS; } /*----------------------------------------------------------------*/ <|endoftext|>
<commit_before>#include "bct.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> bool bct::safe_mode = false; /* M * Returns a vector of indices of the elements in m that satisfy a condition * given by a comparison with cmprVal. Presently, the comparsion operators are * coded in the cmprFlag parameter, as follows: * 0 -> 'greater than operator, >' */ gsl_matrix* bct::find(const gsl_matrix* m, int cmprFlag, double cmprVal) { gsl_matrix* indices = gsl_matrix_alloc(2, m->size1 * m->size1); int size = 0; if(cmprFlag==0) { //means, perform a '>' for(int i = 0;i < m->size1;i++) { for(int j = 0;j < m->size2;j++) { double matrixVal = gsl_matrix_get(m, i, j); if(matrixVal > cmprVal) { gsl_matrix_set(indices, 0, size++, i); gsl_matrix_set(indices, 1, size++, j); } } } gsl_matrix* trimIndices = gsl_matrix_alloc(2, size * size); gsl_matrix_view trim = gsl_matrix_submatrix((gsl_matrix*)m, 0, 0, size-1, size-1); gsl_matrix_memcpy(trimIndices, &trim.matrix); gsl_matrix_free(indices); return trimIndices; } } /* M * Strip a vector by picking only those cells where there is a corresponding * number 1 in the 'pick vector'. */ gsl_vector* bct::pick_cells(const gsl_vector* srcV, const gsl_vector* pickV) { int stripVindex = 0; int nnzV = nnz(pickV); gsl_vector* stripV = gsl_vector_alloc(nnzV); for(int i = 0;i < srcV->size;i++) { //1 or 1.0, does it make a difference? //Nevertheless, pickV is created by logical_not method and it sets integer values if(gsl_vector_get(pickV, i) == 1) gsl_vector_set(stripV, stripVindex++, gsl_vector_get(srcV, i)); } return stripV; } /* * Turns safe mode on or off. */ void bct::set_safe_mode(bool safe_mode) { bct::safe_mode = safe_mode; } /* M * Splice two vectors into one */ gsl_vector* bct::splice(const gsl_vector* v1, const gsl_vector* v2) { int spliceVindex = 0; gsl_vector* spliceV = gsl_vector_alloc(v1->size + v2->size); for(int i = 0;i < v1->size;i++) gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v1, i)); for(int i = 0;i < v2->size;i++) gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v2, i)); return spliceV; } <commit_msg>modified pick_cells method to return an "empty" vector if nnz returns nothing<commit_after>#include "bct.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <cassert> bool bct::safe_mode = false; /* M * Returns a vector of indices of the elements in m that satisfy a condition * given by a comparison with cmprVal. Presently, the comparsion operators are * coded in the cmprFlag parameter, as follows: * 0 -> 'greater than operator, >' */ gsl_matrix* bct::find(const gsl_matrix* m, int cmprFlag, double cmprVal) { gsl_matrix* indices = gsl_matrix_alloc(2, m->size1 * m->size1); int size = 0; if(cmprFlag==0) { //means, perform a '>' for(int i = 0;i < m->size1;i++) { for(int j = 0;j < m->size2;j++) { double matrixVal = gsl_matrix_get(m, i, j); if(matrixVal > cmprVal) { gsl_matrix_set(indices, 0, size++, i); gsl_matrix_set(indices, 1, size++, j); } } } gsl_matrix* trimIndices = gsl_matrix_alloc(2, size * size); gsl_matrix_view trim = gsl_matrix_submatrix((gsl_matrix*)m, 0, 0, size-1, size-1); gsl_matrix_memcpy(trimIndices, &trim.matrix); gsl_matrix_free(indices); return trimIndices; } } /* M * Strip a vector by picking only those cells where there is a corresponding * number 1 in the 'pick vector'. */ gsl_vector* bct::pick_cells(const gsl_vector* srcV, const gsl_vector* pickV) { int stripVindex = 0; int nnzV = nnz(pickV); if(!(nnzV > 0)) { //Matlab returns an empty matrix in this case, here it needs to be handled differently gsl_vector* stripV = gsl_vector_alloc(1); gsl_vector_set(stripV, 0, 0); return stripV; } else { gsl_vector* stripV = gsl_vector_alloc(nnzV); for(int i = 0;i < srcV->size;i++) { //1 or 1.0, does it make a difference? //Nevertheless, pickV is created by logical_not method and it sets integer values if(gsl_vector_get(pickV, i) == 1) gsl_vector_set(stripV, stripVindex++, gsl_vector_get(srcV, i)); } return stripV; } } /* * Turns safe mode on or off. */ void bct::set_safe_mode(bool safe_mode) { bct::safe_mode = safe_mode; } /* M * Splice two vectors into one */ gsl_vector* bct::splice(const gsl_vector* v1, const gsl_vector* v2) { int spliceVindex = 0; gsl_vector* spliceV = gsl_vector_alloc(v1->size + v2->size); for(int i = 0;i < v1->size;i++) gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v1, i)); for(int i = 0;i < v2->size;i++) gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v2, i)); return spliceV; } <|endoftext|>
<commit_before>#ifndef UTILITY_HPP # define UTILITY_HPP #include <cstddef> #include <type_traits> namespace generic { template <::std::size_t...> struct indices { }; namespace detail { // indices template<class A, class B> struct catenate_indices; template <::std::size_t ...Is, ::std::size_t ...Js> struct catenate_indices<indices<Is...>, indices<Js...> > { using indices_type = indices<Is..., Js...>; }; template <::std::size_t, ::std::size_t, typename = void> struct expand_indices; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A == B>::type> { using indices_type = indices<A>; }; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A != B>::type> { static_assert(A < B, "A >= B"); using indices_type = typename catenate_indices< typename expand_indices<A, (A + B) / 2>::indices_type, typename expand_indices<(A + B) / 2 + 1, B>::indices_type >::indices_type; }; } template <::std::size_t A> struct make_indices : detail::expand_indices<0, A>::indices_type { }; template <::std::size_t A, ::std::size_t B> struct make_indices_range : detail::expand_indices<A, B>::indices_type { }; // sequences template <::std::size_t I, typename A, typename ...B> struct type_at : type_at<I - 1, B...> { }; template <typename A, typename ...B> struct type_at<0, A, B...> { using type = A; }; template <typename A, typename ...B> struct front { using type = A; }; template <typename A, typename ...B> struct back : back<B...> { }; template <typename A> struct back<A> { using type = A; }; template <bool B> using bool_ = ::std::integral_constant<bool, B>; template <class A, class ...B> struct all_of : bool_<A::value && all_of<B...>::value> { }; template <class A> struct all_of<A> : bool_<A::value> { }; } #endif // UTILITY_HPP <commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP # define UTILITY_HPP #include <cstddef> #include <type_traits> namespace generic { template <::std::size_t...> struct indices { }; namespace detail { // indices template<class A, class B> struct catenate_indices; template <::std::size_t ...Is, ::std::size_t ...Js> struct catenate_indices<indices<Is...>, indices<Js...> > { using indices_type = indices<Is..., Js...>; }; template <::std::size_t, ::std::size_t, typename = void> struct expand_indices; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A == B>::type> { using indices_type = indices<A>; }; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A != B>::type> { static_assert(A < B, "A > B"); using indices_type = typename catenate_indices< typename expand_indices<A, (A + B) / 2>::indices_type, typename expand_indices<(A + B) / 2 + 1, B>::indices_type >::indices_type; }; } template <::std::size_t A> struct make_indices : detail::expand_indices<0, A>::indices_type { }; template <::std::size_t A, ::std::size_t B> struct make_indices_range : detail::expand_indices<A, B>::indices_type { }; // sequences template <::std::size_t I, typename A, typename ...B> struct type_at : type_at<I - 1, B...> { }; template <typename A, typename ...B> struct type_at<0, A, B...> { using type = A; }; template <typename A, typename ...B> struct front { using type = A; }; template <typename A, typename ...B> struct back : back<B...> { }; template <typename A> struct back<A> { using type = A; }; template <bool B> using bool_ = ::std::integral_constant<bool, B>; template <class A, class ...B> struct all_of : bool_<A::value && all_of<B...>::value> { }; template <class A> struct all_of<A> : bool_<A::value> { }; } #endif // UTILITY_HPP <|endoftext|>
<commit_before>#ifndef UTILITY_HPP # define UTILITY_HPP #include <cstddef> #include <type_traits> namespace generic { template<typename T> constexpr inline T const& as_const(T& t) { return t; } template <::std::size_t...> struct indices { }; namespace detail { // indices template<class, class> struct catenate_indices; template <::std::size_t ...Is, ::std::size_t ...Js> struct catenate_indices<indices<Is...>, indices<Js...> > { using indices_type = indices<Is..., Js...>; }; template <::std::size_t, ::std::size_t, typename = void> struct expand_indices; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A == B>::type> { using indices_type = indices<A>; }; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A != B>::type> { static_assert(A < B, "A > B"); using indices_type = typename catenate_indices< typename expand_indices<A, (A + B) / 2>::indices_type, typename expand_indices<(A + B) / 2 + 1, B>::indices_type >::indices_type; }; } template <::std::size_t A> struct make_indices : detail::expand_indices<0, A - 1>::indices_type; template <> struct make_indices<0> : indices<> { }; template <::std::size_t A, ::std::size_t B> struct make_indices_range : detail::expand_indices<A, B - 1>::indices_type { }; template <::std::size_t A> struct make_indices_range<A, A> : indices<> { }; // sequences template <::std::size_t I, typename A, typename ...B> struct type_at : type_at<I - 1, B...> { }; template <typename A, typename ...B> struct type_at<0, A, B...> { using type = A; }; template <typename A, typename ...B> struct front { using type = A; }; template <typename A, typename ...B> struct back : back<B...> { }; template <typename A> struct back<A> { using type = A; }; template <bool B> using bool_ = ::std::integral_constant<bool, B>; template <class A, class ...B> struct all_of : bool_<A::value && all_of<B...>::value> { }; template <class A> struct all_of<A> : bool_<A::value> { }; } #endif // UTILITY_HPP <commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP # define UTILITY_HPP #include <cstddef> #include <type_traits> namespace generic { template<typename T> constexpr inline T const& as_const(T& t) { return t; } template <::std::size_t...> struct indices { }; namespace detail { // indices template<class, class> struct catenate_indices; template <::std::size_t ...Is, ::std::size_t ...Js> struct catenate_indices<indices<Is...>, indices<Js...> > { using indices_type = indices<Is..., Js...>; }; template <::std::size_t, ::std::size_t, typename = void> struct expand_indices; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A == B>::type> { using indices_type = indices<A>; }; template <::std::size_t A, ::std::size_t B> struct expand_indices<A, B, typename ::std::enable_if<A != B>::type> { static_assert(A < B, "A > B"); using indices_type = typename catenate_indices< typename expand_indices<A, (A + B) / 2>::indices_type, typename expand_indices<(A + B) / 2 + 1, B>::indices_type >::indices_type; }; } template <::std::size_t A> struct make_indices : detail::expand_indices<0, A - 1>::indices_type { }; template <> struct make_indices<0> : indices<> { }; template <::std::size_t A, ::std::size_t B> struct make_indices_range : detail::expand_indices<A, B - 1>::indices_type { }; template <::std::size_t A> struct make_indices_range<A, A> : indices<> { }; // sequences template <::std::size_t I, typename A, typename ...B> struct type_at : type_at<I - 1, B...> { }; template <typename A, typename ...B> struct type_at<0, A, B...> { using type = A; }; template <typename A, typename ...B> struct front { using type = A; }; template <typename A, typename ...B> struct back : back<B...> { }; template <typename A> struct back<A> { using type = A; }; template <bool B> using bool_ = ::std::integral_constant<bool, B>; template <class A, class ...B> struct all_of : bool_<A::value && all_of<B...>::value> { }; template <class A> struct all_of<A> : bool_<A::value> { }; } #endif // UTILITY_HPP <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_IOBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight 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. =========================================================================*/ #include "itkRawImageIO.h" #include "itkPNGImageIO.h" #include "itkMetaImageIO.h" #include "itkPNGImageIOFactory.h" #include "itkMetaImageIOFactory.h" #include "itkDicomImageIOFactory.h" #ifdef CABLE_CONFIGURATION #include "wrap_ITKIO.h" ITK_WRAP_CONFIG_GROUP(IOBase); ITK_WRAP_OBJECT(PNGImageIO); ITK_WRAP_OBJECT(MetaImageIO); ITK_WRAP_OBJECT(PNGImageIOFactory); ITK_WRAP_OBJECT(MetaImageIOFactory); ITK_WRAP_OBJECT(DicomImageIOFactory); ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF2, RawImageIO<float, 2>); ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF3, RawImageIO<float, 3>); #endif <commit_msg>ENH: Added wrapper for ImageIOBase.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: wrap_IOBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight 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. =========================================================================*/ #include "itkRawImageIO.h" #include "itkImageIOBase.h" #include "itkPNGImageIO.h" #include "itkMetaImageIO.h" #include "itkPNGImageIOFactory.h" #include "itkMetaImageIOFactory.h" #include "itkDicomImageIOFactory.h" #ifdef CABLE_CONFIGURATION #include "wrap_ITKIO.h" ITK_WRAP_CONFIG_GROUP(IOBase); ITK_WRAP_OBJECT(ImageIOBase); ITK_WRAP_OBJECT(PNGImageIO); ITK_WRAP_OBJECT(MetaImageIO); ITK_WRAP_OBJECT(PNGImageIOFactory); ITK_WRAP_OBJECT(MetaImageIOFactory); ITK_WRAP_OBJECT(DicomImageIOFactory); ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF2, RawImageIO<float, 2>); ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF3, RawImageIO<float, 3>); #endif <|endoftext|>
<commit_before>#include <string> #include "stdafx.h" #include "MainScene.h" #include "MCScene.h" Scene* MCScene::createScene() { auto scene = Scene::create(); auto layer = MCScene::create(); scene->addChild(layer); return scene; } bool MCScene::init() { if (!CCLayerColor::initWithColor(Color4B(0, 0, 0, 255))) { return false; } this->schedule(schedule_selector(MCScene::ChangeBackGroundColor), DELTA_TIME); auto backgroundGirl0 = Sprite::create("res/mc.jpg"); backgroundGirl0->setAnchorPoint(Point::ZERO); backgroundGirl0->setPosition(Point::ZERO); auto backgroundGirl1 = Sprite::create("res/mc.jpg"); backgroundGirl1->setAnchorPoint(Point::ZERO); backgroundGirl1->setPosition(Point(backgroundGirl0->getContentSize().width, 0)); backgroundGirl0->addChild(backgroundGirl1); backgroundGirl0->setScale(0.1); this->addChild(backgroundGirl0); auto GotoMainScene = MenuItemFont::create("Go to MainScene", CC_CALLBACK_1(MCScene::ChangeToMainScene, this)); auto GotoMainSceneMenu = Menu::create(GotoMainScene, NULL); GotoMainSceneMenu->setPosition(200, 300); this->addChild(GotoMainSceneMenu); auto taewooMission1 = Label::createWithTTF("JUMP!!!", "fonts/arial.ttf", 50); taewooMission1->setPosition(Point(200, 150)); taewooMission1->setName("twMissionLabel"); taewooMission1->setVisible(false); this->addChild(taewooMission1); auto dir = Director::getInstance(); auto screen = dir->getVisibleSize(); auto jinwookMission = Sprite::create("boy 31x40.png"); auto boysize = jinwookMission->getContentSize(); jinwookMission->setPosition(0 + boysize.width / 2, 0 + boysize.height / 2); jinwookMission->setName("boy"); this->addChild(jinwookMission); auto moveToRL = MoveBy::create(1, Point(screen.width - boysize.width, 0)); auto moveToRU = MoveBy::create(1, Point(0 , screen.height - boysize.height)); auto moveToLU = MoveBy::create(1, Point( -screen.width + boysize.width, 0)); auto moveToLL = MoveBy::create(1, Point(0, -screen.height + boysize.height)); auto moveArround = Sequence::create(moveToRL, moveToRU, moveToLU, moveToLL, NULL); auto repeat_action = RepeatForever::create(moveArround); jinwookMission->runAction(repeat_action); auto _mouseListener = EventListenerMouse::create(); _mouseListener->onMouseUp = CC_CALLBACK_1(MCScene::onMouseUp, this); _mouseListener->onMouseDown = CC_CALLBACK_1(MCScene::onMouseDown, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); auto aniSprite = Sprite::create(); aniSprite->setPosition(100, 100); this->addChild(aniSprite); //ִϸ̼ ߰ Vector<SpriteFrame*> animFrames; const int frameCut = 3;// const int AniCharheight = 70; const int AniCharWidth = 32; animFrames.reserve(frameCut); for (int i = 0; i < frameCut; i++) animFrames.pushBack(SpriteFrame::create("res/animSprite2.png", Rect(AniCharWidth * i*3, AniCharheight, AniCharWidth, AniCharheight))); // create the animation out of the frame Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); // run it and repeat it forever RepeatForever *aniAction = RepeatForever::create(animate); //׼  auto jump = JumpBy::create(0.5, Point(0, 0), 20, 1); RepeatForever *jumpForever = RepeatForever::create(jump); aniSprite->runAction(aniAction); //Ʈ(spr) aniSprite->runAction(jumpForever); return true; } void MCScene::ChangeToMainScene(Ref* pSender) { Director::getInstance()->replaceScene(MainScene::createScene()); } void MCScene::onMouseUp(Event *event) { auto label = this->getChildByName("twMissionLabel"); label->setVisible(false); } void MCScene::onMouseDown(Event *event) { auto e = (EventMouse*)event; auto blinkLabel = this->getChildByName("twMissionLabel"); blinkLabel->setVisible(true); auto runningBoy = this->getChildByName("boy"); auto moveToMouse = JumpBy::create(0.3, Point(0, 0), 50, 1); runningBoy->runAction(moveToMouse); } void MCScene::ChangeBackGroundColor(const float intervalTime) { this->setColor(Color3B((random() % 255), (random() % 255), (random() % 255))); }<commit_msg>내꺼 왜 스크롤이 제대로 안돼지<commit_after>#include <string> #include "stdafx.h" #include "MainScene.h" #include "MCScene.h" Scene* MCScene::createScene() { auto scene = Scene::create(); auto layer = MCScene::create(); scene->addChild(layer); return scene; } bool MCScene::init() { if (!CCLayerColor::initWithColor(Color4B(0, 0, 0, 255))) { return false; } this->schedule(schedule_selector(MCScene::ChangeBackGroundColor), DELTA_TIME); auto dir = Director::getInstance(); auto screen = dir->getVisibleSize(); auto backgroundGirl0 = Sprite::create("res/mc.jpg"); backgroundGirl0->setAnchorPoint(Point::ZERO); backgroundGirl0->setPosition(Point::ZERO); int width = backgroundGirl0->getContentSize().width; int height = backgroundGirl0->getContentSize().height; float scrollVelocity = 100; float scaleRatio = screen.height / height; backgroundGirl0->setScale(scaleRatio); auto backgroundGirl1 = Sprite::create("res/mc.jpg"); backgroundGirl1->setAnchorPoint(Point::ZERO); backgroundGirl1->setPosition(Point(width, 0)); auto moveRight = MoveTo::create(screen.width / (scrollVelocity * scaleRatio), Point(-width, 0)); auto moveBack = MoveTo::create(0, Point::ZERO); auto scrollBG = RepeatForever::create(Sequence::create(moveRight, moveBack, NULL)); backgroundGirl0->runAction(scrollBG); backgroundGirl0->addChild(backgroundGirl1); this->addChild(backgroundGirl0); auto GotoMainScene = MenuItemFont::create("Go to MainScene", CC_CALLBACK_1(MCScene::ChangeToMainScene, this)); auto GotoMainSceneMenu = Menu::create(GotoMainScene, NULL); GotoMainSceneMenu->setPosition(200, 300); this->addChild(GotoMainSceneMenu); auto taewooMission1 = Label::createWithTTF("JUMP!!!", "fonts/arial.ttf", 50); taewooMission1->setPosition(Point(200, 150)); taewooMission1->setName("twMissionLabel"); taewooMission1->setVisible(false); this->addChild(taewooMission1); auto jinwookMission = Sprite::create("boy 31x40.png"); auto boysize = jinwookMission->getContentSize(); jinwookMission->setPosition(0 + boysize.width / 2, 0 + boysize.height / 2); jinwookMission->setName("boy"); this->addChild(jinwookMission); auto moveToRL = MoveBy::create(1, Point(screen.width - boysize.width, 0)); auto moveToRU = MoveBy::create(1, Point(0 , screen.height - boysize.height)); auto moveToLU = MoveBy::create(1, Point( -screen.width + boysize.width, 0)); auto moveToLL = MoveBy::create(1, Point(0, -screen.height + boysize.height)); auto moveArround = Sequence::create(moveToRL, moveToRU, moveToLU, moveToLL, NULL); auto repeat_action = RepeatForever::create(moveArround); jinwookMission->runAction(repeat_action); auto _mouseListener = EventListenerMouse::create(); _mouseListener->onMouseUp = CC_CALLBACK_1(MCScene::onMouseUp, this); _mouseListener->onMouseDown = CC_CALLBACK_1(MCScene::onMouseDown, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); auto aniSprite = Sprite::create(); aniSprite->setPosition(100, 100); this->addChild(aniSprite); //ִϸ̼ ߰ Vector<SpriteFrame*> animFrames; const int frameCut = 3;// const int AniCharheight = 70; const int AniCharWidth = 32; animFrames.reserve(frameCut); for (int i = 0; i < frameCut; i++) animFrames.pushBack(SpriteFrame::create("res/animSprite2.png", Rect(AniCharWidth * i*3, AniCharheight, AniCharWidth, AniCharheight))); // create the animation out of the frame Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); // run it and repeat it forever RepeatForever *aniAction = RepeatForever::create(animate); //׼  auto jump = JumpBy::create(0.5, Point(0, 0), 20, 1); RepeatForever *jumpForever = RepeatForever::create(jump); aniSprite->runAction(aniAction); //Ʈ(spr) aniSprite->runAction(jumpForever); return true; } void MCScene::ChangeToMainScene(Ref* pSender) { Director::getInstance()->replaceScene(MainScene::createScene()); } void MCScene::onMouseUp(Event *event) { auto label = this->getChildByName("twMissionLabel"); label->setVisible(false); } void MCScene::onMouseDown(Event *event) { auto e = (EventMouse*)event; auto blinkLabel = this->getChildByName("twMissionLabel"); blinkLabel->setVisible(true); auto runningBoy = this->getChildByName("boy"); auto moveToMouse = JumpBy::create(0.3, Point(0, 0), 50, 1); runningBoy->runAction(moveToMouse); } void MCScene::ChangeBackGroundColor(const float intervalTime) { this->setColor(Color3B((random() % 255), (random() % 255), (random() % 255))); }<|endoftext|>
<commit_before>/** * @file prereqs.hpp * * The core includes that mlpack expects; standard C++ includes and Armadillo. */ #ifndef __MLPACK_PREREQS_HPP #define __MLPACK_PREREQS_HPP // First, check if Armadillo was included before, warning if so. #ifdef ARMA_INCLUDES #pragma message "Armadillo was included before mlpack; this can sometimes cause\ problems. It should only be necessary to include <mlpack/core.hpp> and not \ <armadillo>." #endif // Next, standard includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <float.h> #include <stdint.h> #include <iostream> #include <stdexcept> // Defining _USE_MATH_DEFINES should set M_PI. #define _USE_MATH_DEFINES #include <math.h> // For tgamma(). #include <boost/math/special_functions/gamma.hpp> // But if it's not defined, we'll do it. #ifndef M_PI #define M_PI 3.141592653589793238462643383279 #endif // Give ourselves a nice way to force functions to be inline if we need. #define force_inline #if defined(__GNUG__) && !defined(DEBUG) #undef force_inline #define force_inline __attribute__((always_inline)) #elif defined(_MSC_VER) && !defined(DEBUG) #undef force_inline #define force_inline __forceinline #endif // We'll need the necessary boost::serialization features, as well as what we // use with mlpack. In Boost 1.59 and newer, the BOOST_PFTO code is no longer // defined, but we still need to define it (as nothing) so that the mlpack // serialization shim compiles. #include <boost/serialization/serialization.hpp> #ifndef BOOST_PFTO #define BOOST_PFTO #endif #include <mlpack/core/data/serialization_shim.hpp> // Now include Armadillo through the special mlpack extensions. #include <mlpack/core/arma_extend/arma_extend.hpp> // Ensure that the user isn't doing something stupid with their Armadillo // defines. #include <mlpack/core/util/arma_config_check.hpp> // On Visual Studio, disable C4519 (default arguments for function templates) // since it's by default an error, which doesn't even make any sense because // it's part of the C++11 standard. #ifdef _MSC_VER #pragma warning(disable : 4519) #endif #endif <commit_msg>Add serialization prerequisites.<commit_after>/** * @file prereqs.hpp * * The core includes that mlpack expects; standard C++ includes and Armadillo. */ #ifndef __MLPACK_PREREQS_HPP #define __MLPACK_PREREQS_HPP // First, check if Armadillo was included before, warning if so. #ifdef ARMA_INCLUDES #pragma message "Armadillo was included before mlpack; this can sometimes cause\ problems. It should only be necessary to include <mlpack/core.hpp> and not \ <armadillo>." #endif // Next, standard includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <float.h> #include <stdint.h> #include <iostream> #include <stdexcept> // Defining _USE_MATH_DEFINES should set M_PI. #define _USE_MATH_DEFINES #include <math.h> // For tgamma(). #include <boost/math/special_functions/gamma.hpp> // But if it's not defined, we'll do it. #ifndef M_PI #define M_PI 3.141592653589793238462643383279 #endif // Give ourselves a nice way to force functions to be inline if we need. #define force_inline #if defined(__GNUG__) && !defined(DEBUG) #undef force_inline #define force_inline __attribute__((always_inline)) #elif defined(_MSC_VER) && !defined(DEBUG) #undef force_inline #define force_inline __forceinline #endif // We'll need the necessary boost::serialization features, as well as what we // use with mlpack. In Boost 1.59 and newer, the BOOST_PFTO code is no longer // defined, but we still need to define it (as nothing) so that the mlpack // serialization shim compiles. #include <boost/serialization/serialization.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/unordered_map.hpp> #ifndef BOOST_PFTO #define BOOST_PFTO #endif #include <mlpack/core/data/serialization_shim.hpp> // Now include Armadillo through the special mlpack extensions. #include <mlpack/core/arma_extend/arma_extend.hpp> // Ensure that the user isn't doing something stupid with their Armadillo // defines. #include <mlpack/core/util/arma_config_check.hpp> // On Visual Studio, disable C4519 (default arguments for function templates) // since it's by default an error, which doesn't even make any sense because // it's part of the C++11 standard. #ifdef _MSC_VER #pragma warning(disable : 4519) #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2014, Nicolas Brown All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of dragonscript nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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. */ #pragma once #include "loris\loris.hpp" using namespace loris; template<> Value::operator double() { return AsNumber(); } template<> Value::operator long() { return AsNumber(); } template<> Value::operator std::string() { return AsString(); } Value box(int value) { return Value::CreateNumber(value); } Value box(long value) { return Value::CreateNumber(value); } Value box(float value) { return Value::CreateNumber(value); } Value box(double value) { return Value::CreateNumber(value); } Value box(const std::string& value) { return Value::CreateString(value.c_str()); } Value box(bool value) { return Value::CreateBool(value); } template<typename T> Value box(T value) { auto obj = new Object(); obj->managed = false; obj->data = (void*)value; return Value::CreateObject(obj); } template<typename Ret, typename ... Params, size_t ... I> Ret call_func(Ret(*sig)(Params...), std::index_sequence<I...>, VirtualMachine* vm) { return sig(vm->GetArg(I)...); } template<typename Ret, typename ... Params> std::function<Value(VirtualMachine* vm, Object* self)> Def(Ret(*sig)(Params...)) { if (std::is_same<Ret, void>::value) { return [=](VirtualMachine* vm, Object* self) { call_func(sig, std::index_sequence_for<Params...>{}, vm); return Value::CreateNull(); }; } else { return [=](VirtualMachine* vm, Object* self) { return box(call_func(sig, std::index_sequence_for<Params...>{}, vm)); }; } }<commit_msg>Added class for building loris classes<commit_after>/* Copyright (c) 2014, Nicolas Brown All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of dragonscript nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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. */ #pragma once #include "loris\loris.hpp" namespace loris { template<> Value::operator double() { return AsNumber(); } template<> Value::operator long() { return AsNumber(); } template<> Value::operator std::string() { return AsString(); } Value box(int value) { return Value::CreateNumber(value); } Value box(long value) { return Value::CreateNumber(value); } Value box(float value) { return Value::CreateNumber(value); } Value box(double value) { return Value::CreateNumber(value); } Value box(const std::string& value) { return Value::CreateString(value.c_str()); } Value box(bool value) { return Value::CreateBool(value); } template<typename T> Value box(T value) { auto obj = new Object(); obj->managed = false; obj->data = (void*)value; return Value::CreateObject(obj); } template<typename Ret, typename ... Params, size_t ... I> Ret call_func(Ret(*sig)(Params...), std::index_sequence<I...>, VirtualMachine* vm) { return sig(vm->GetArg(I)...); } template<typename Ret, typename ... Params> std::function<Value(VirtualMachine* vm, Object* self)> Def(Ret(*sig)(Params...)) { if (std::is_same<Ret, void>::value) { return [=](VirtualMachine* vm, Object* self) { call_func(sig, std::index_sequence_for<Params...>{}, vm); return Value::CreateNull(); }; } else { return [=](VirtualMachine* vm, Object* self) { return box(call_func(sig, std::index_sequence_for<Params...>{}, vm)); }; } } class ClassBuilder { public: Class * def; ClassBuilder() { def = NULL; } ClassBuilder Start(string className) { def = new Class(); def->name = className; return *this; } ClassBuilder Attrib(string name) { assert(def != NULL); ClassAttrib attr; attr.name = name; attr.isStatic = false; attr.init = NULL; def->attribs.push_back(attr); return *this; } ClassBuilder StaticAttrib(string name) { assert(def != NULL); ClassAttrib attr; attr.name = name; attr.isStatic = true; attr.init = NULL; def->attribs.push_back(attr); return *this; } ClassBuilder Constructor(NativeFunction native) { Function* func = new Function; func->name = def->name; func->isStatic = false; func->isNative = true; func->nativeFunction = native; def->methods[def->name] = func; return *this; } ClassBuilder Destructor(NativeFunction native) { Function* func = new Function; func->name = def->name; func->isStatic = false; func->isNative = true; func->nativeFunction = native; def->destructor = func; return *this; } ClassBuilder Method(string name, NativeFunction native) { Function* func = new Function; func->name = def->name; func->isStatic = false; func->isNative = true; func->nativeFunction = native; def->methods[name] = func; return *this; } ClassBuilder StaticMethod(string name, NativeFunction native) { Function* func = new Function; func->name = def->name; func->isStatic = true; func->isNative = true; func->nativeFunction = native; def->methods[name] = func; return *this; } Class* Build() { Class* c = def; def = NULL; return c; } }; ClassBuilder CreateClass(std::string name) { ClassBuilder builder; return builder.Start(name); } }<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef MAP_HPP #define MAP_HPP #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <mapnik/feature_type_style.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <boost/optional/optional.hpp> namespace mapnik { class MAPNIK_DECL Map { public: enum aspect_fix_mode { /* grow the width or height of the specified geo bbox to fill the map size. default behaviour. */ GROW_BBOX, /* grow the width or height of the map to accomodate the specified geo bbox. */ GROW_CANVAS, /* shrink the width or height of the specified geo bbox to fill the map size. */ SHRINK_BBOX, /* shrink the width or height of the map to accomodate the specified geo bbox. */ SHRINK_CANVAS, /* adjust the width of the specified geo bbox, leave height and map size unchanged */ ADJUST_BBOX_WIDTH, /* adjust the height of the specified geo bbox, leave width and map size unchanged */ ADJUST_BBOX_HEIGHT, /* adjust the width of the map, leave height and geo bbox unchanged */ ADJUST_CANVAS_WIDTH, /* adjust the height of the map, leave width and geo bbox unchanged */ ADJUST_CANVAS_HEIGHT }; private: static const unsigned MIN_MAPSIZE=16; static const unsigned MAX_MAPSIZE=MIN_MAPSIZE<<10; unsigned width_; unsigned height_; std::string srs_; boost::optional<Color> background_; std::map<std::string,feature_type_style> styles_; std::map<std::string,FontSet> fontsets_; std::vector<Layer> layers_; Envelope<double> currentExtent_; aspect_fix_mode aspectFixMode_; public: typedef std::map<std::string,feature_type_style>::const_iterator const_style_iterator; typedef std::map<std::string,feature_type_style>::iterator style_iterator; /*! \brief Default constructor. * * Creates a map with these parameters: * - width = 400 * - height = 400 * - projection = "+proj=latlong +datum=WGS84" */ Map(); /*! \brief Constructor * @param width Initial map width. * @param height Initial map height. * @param srs Initial map projection. */ Map(int width, int height, std::string const& srs="+proj=latlong +datum=WGS84"); /*! \brief Copy Constructur. * * @param rhs Map to copy from. */ Map(const Map& rhs); /*! \brief Assignment operator * * TODO: to be documented * */ Map& operator=(const Map& rhs); /*! \brief Get all styles * @return Const reference to styles */ std::map<std::string,feature_type_style> const& styles() const; /*! \brief Get all styles * @return Non-constant reference to styles */ std::map<std::string,feature_type_style> & styles(); /*! \brief Get first iterator in styles. * @return Constant style iterator. */ const_style_iterator begin_styles() const; /*! \brief Get last iterator in styles. * @return Constant style iterator. */ const_style_iterator end_styles() const; /*! \brief Get first iterator in styles. * @return Non-constant style iterator. */ style_iterator begin_styles(); /*! \brief Get last iterator in styles. * @return Non-constant style iterator. */ style_iterator end_styles(); /*! \brief Insert a style in the map. * @param name The name of the style. * @param style The style to insert. * @return true If success. * @return false If no success. */ bool insert_style(std::string const& name,feature_type_style const& style); /*! \brief Remove a style from the map. * @param name The name of the style. */ void remove_style(const std::string& name); /*! \brief Find a style. * @param name The name of the style. * @return The style if found. If not found return the default map style. */ feature_type_style const& find_style(std::string const& name) const; /*! \brief Insert a fontset into the map. * @param name The name of the fontset. * @param style The fontset to insert. * @return true If success. * @return false If failure. */ bool insert_fontset(std::string const& name, FontSet const& fontset); /*! \brief Find a fontset. * @param name The name of the fontset. * @return The fontset if found. If not found return the default map fontset. */ FontSet const& find_fontset(std::string const& name) const; /*! \brief Get number of all layers. */ size_t layerCount() const; /*! \brief Add a layer to the map. * @param l The layer to add. */ void addLayer(const Layer& l); /*! \brief Get a layer. * @param index Layer number. * @return Constant layer. */ const Layer& getLayer(size_t index) const; /*! \brief Get a layer. * @param index Layer number. * @return Non-constant layer. */ Layer& getLayer(size_t index); /*! \brief Remove a layer. * @param index Layer number. */ void removeLayer(size_t index); /*! \brief Get all layers. * @return Constant layers. */ std::vector<Layer> const& layers() const; /*! \brief Get all layers. * @return Non-constant layers. */ std::vector<Layer> & layers(); /*! \brief Remove all layers and styles from the map. */ void remove_all(); /*! \brief Get map width. */ unsigned getWidth() const; /*! \brief Get map height. */ unsigned getHeight() const; /*! \brief Set map width. */ void setWidth(unsigned width); /*! \brief Set map height. */ void setHeight(unsigned height); /*! \brief Resize the map. */ void resize(unsigned width,unsigned height); /*! \brief Get the map projection. * @return Map projection. */ std::string const& srs() const; /*! \brief Set the map projection. * @param srs Map projection. */ void set_srs(std::string const& srs); /*! \brief Set the map background color. * @param c Background color. */ void set_background(const Color& c); /*! \brief Get the map background color * @return Background color as boost::optional * object */ boost::optional<Color> const& background() const; /*! \brief Zoom the map at the current position. * @param factor The factor how much the map is zoomed in or out. */ void zoom(double factor); /*! \brief Zoom the map to a bounding box. * * Aspect is handled automatic if not fitting to width/height. * @param box The bounding box where to zoom. */ void zoomToBox(const Envelope<double>& box); /*! \brief Zoom the map to show all data. */ void zoom_all(); void pan(int x,int y); void pan_and_zoom(int x,int y,double zoom); /*! \brief Get current bounding box. * @return The current bounding box. */ const Envelope<double>& getCurrentExtent() const; double scale() const; CoordTransform view_transform() const; featureset_ptr query_point(unsigned index, double x, double y) const; featureset_ptr query_map_point(unsigned index, double x, double y) const; ~Map(); void setAspectFixMode(aspect_fix_mode afm) { aspectFixMode_ = afm; } bool getAspectFixMode() { return aspectFixMode_; } private: void fixAspectRatio(); }; } #endif //MAP_HPP <commit_msg>+fixed init order<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef MAP_HPP #define MAP_HPP #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <mapnik/feature_type_style.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <boost/optional/optional.hpp> namespace mapnik { class MAPNIK_DECL Map { public: enum aspect_fix_mode { /* grow the width or height of the specified geo bbox to fill the map size. default behaviour. */ GROW_BBOX, /* grow the width or height of the map to accomodate the specified geo bbox. */ GROW_CANVAS, /* shrink the width or height of the specified geo bbox to fill the map size. */ SHRINK_BBOX, /* shrink the width or height of the map to accomodate the specified geo bbox. */ SHRINK_CANVAS, /* adjust the width of the specified geo bbox, leave height and map size unchanged */ ADJUST_BBOX_WIDTH, /* adjust the height of the specified geo bbox, leave width and map size unchanged */ ADJUST_BBOX_HEIGHT, /* adjust the width of the map, leave height and geo bbox unchanged */ ADJUST_CANVAS_WIDTH, /* adjust the height of the map, leave width and geo bbox unchanged */ ADJUST_CANVAS_HEIGHT }; private: static const unsigned MIN_MAPSIZE=16; static const unsigned MAX_MAPSIZE=MIN_MAPSIZE<<10; unsigned width_; unsigned height_; std::string srs_; boost::optional<Color> background_; std::map<std::string,feature_type_style> styles_; std::map<std::string,FontSet> fontsets_; std::vector<Layer> layers_; aspect_fix_mode aspectFixMode_; Envelope<double> currentExtent_; public: typedef std::map<std::string,feature_type_style>::const_iterator const_style_iterator; typedef std::map<std::string,feature_type_style>::iterator style_iterator; /*! \brief Default constructor. * * Creates a map with these parameters: * - width = 400 * - height = 400 * - projection = "+proj=latlong +datum=WGS84" */ Map(); /*! \brief Constructor * @param width Initial map width. * @param height Initial map height. * @param srs Initial map projection. */ Map(int width, int height, std::string const& srs="+proj=latlong +datum=WGS84"); /*! \brief Copy Constructur. * * @param rhs Map to copy from. */ Map(const Map& rhs); /*! \brief Assignment operator * * TODO: to be documented * */ Map& operator=(const Map& rhs); /*! \brief Get all styles * @return Const reference to styles */ std::map<std::string,feature_type_style> const& styles() const; /*! \brief Get all styles * @return Non-constant reference to styles */ std::map<std::string,feature_type_style> & styles(); /*! \brief Get first iterator in styles. * @return Constant style iterator. */ const_style_iterator begin_styles() const; /*! \brief Get last iterator in styles. * @return Constant style iterator. */ const_style_iterator end_styles() const; /*! \brief Get first iterator in styles. * @return Non-constant style iterator. */ style_iterator begin_styles(); /*! \brief Get last iterator in styles. * @return Non-constant style iterator. */ style_iterator end_styles(); /*! \brief Insert a style in the map. * @param name The name of the style. * @param style The style to insert. * @return true If success. * @return false If no success. */ bool insert_style(std::string const& name,feature_type_style const& style); /*! \brief Remove a style from the map. * @param name The name of the style. */ void remove_style(const std::string& name); /*! \brief Find a style. * @param name The name of the style. * @return The style if found. If not found return the default map style. */ feature_type_style const& find_style(std::string const& name) const; /*! \brief Insert a fontset into the map. * @param name The name of the fontset. * @param style The fontset to insert. * @return true If success. * @return false If failure. */ bool insert_fontset(std::string const& name, FontSet const& fontset); /*! \brief Find a fontset. * @param name The name of the fontset. * @return The fontset if found. If not found return the default map fontset. */ FontSet const& find_fontset(std::string const& name) const; /*! \brief Get number of all layers. */ size_t layerCount() const; /*! \brief Add a layer to the map. * @param l The layer to add. */ void addLayer(const Layer& l); /*! \brief Get a layer. * @param index Layer number. * @return Constant layer. */ const Layer& getLayer(size_t index) const; /*! \brief Get a layer. * @param index Layer number. * @return Non-constant layer. */ Layer& getLayer(size_t index); /*! \brief Remove a layer. * @param index Layer number. */ void removeLayer(size_t index); /*! \brief Get all layers. * @return Constant layers. */ std::vector<Layer> const& layers() const; /*! \brief Get all layers. * @return Non-constant layers. */ std::vector<Layer> & layers(); /*! \brief Remove all layers and styles from the map. */ void remove_all(); /*! \brief Get map width. */ unsigned getWidth() const; /*! \brief Get map height. */ unsigned getHeight() const; /*! \brief Set map width. */ void setWidth(unsigned width); /*! \brief Set map height. */ void setHeight(unsigned height); /*! \brief Resize the map. */ void resize(unsigned width,unsigned height); /*! \brief Get the map projection. * @return Map projection. */ std::string const& srs() const; /*! \brief Set the map projection. * @param srs Map projection. */ void set_srs(std::string const& srs); /*! \brief Set the map background color. * @param c Background color. */ void set_background(const Color& c); /*! \brief Get the map background color * @return Background color as boost::optional * object */ boost::optional<Color> const& background() const; /*! \brief Zoom the map at the current position. * @param factor The factor how much the map is zoomed in or out. */ void zoom(double factor); /*! \brief Zoom the map to a bounding box. * * Aspect is handled automatic if not fitting to width/height. * @param box The bounding box where to zoom. */ void zoomToBox(const Envelope<double>& box); /*! \brief Zoom the map to show all data. */ void zoom_all(); void pan(int x,int y); void pan_and_zoom(int x,int y,double zoom); /*! \brief Get current bounding box. * @return The current bounding box. */ const Envelope<double>& getCurrentExtent() const; double scale() const; CoordTransform view_transform() const; featureset_ptr query_point(unsigned index, double x, double y) const; featureset_ptr query_map_point(unsigned index, double x, double y) const; ~Map(); void setAspectFixMode(aspect_fix_mode afm) { aspectFixMode_ = afm; } bool getAspectFixMode() { return aspectFixMode_; } private: void fixAspectRatio(); }; } #endif //MAP_HPP <|endoftext|>
<commit_before>#pragma once /* * Covariant Mozart Utility Library: Any * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2017 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee * Website: http://ldc.atd3.cn * * Version: 17.5.1 */ #include "./base.hpp" #include "./memory.hpp" #include <functional> #include <iostream> namespace std { template<typename T> std::string to_string(const T&) { throw cov::error("E000D"); } template<> std::string to_string<std::string>(const std::string& str) { return str; } template<> std::string to_string<bool>(const bool& v) { if(v) return "true"; else return "false"; } } #define COV_ANY_POOL_SIZE 128 namespace cov { template<typename _Tp> class compare_helper { template<typename T,typename X=bool>struct matcher; template<typename T> static constexpr bool match(T*) { return false; } template<typename T> static constexpr bool match(matcher < T, decltype(std::declval<T>()==std::declval<T>()) > *) { return true; } public: static constexpr bool value = match < _Tp > (nullptr); }; template<typename,bool> struct compare_if; template<typename T>struct compare_if<T,true> { static bool compare(const T& a,const T& b) { return a==b; } }; template<typename T>struct compare_if<T,false> { static bool compare(const T& a,const T& b) { return &a==&b; } }; template<typename T>bool compare(const T& a,const T& b) { return compare_if<T,compare_helper<T>::value>::compare(a,b); } template<typename _Tp> class hash_helper { template<typename T,decltype(&std::hash<T>::operator()) X>struct matcher; template<typename T> static constexpr bool match(T*) { return false; } template<typename T> static constexpr bool match(matcher<T,&std::hash<T>::operator()>*) { return true; } public: static constexpr bool value = match < _Tp > (nullptr); }; template<typename,bool> struct hash_if; template<typename T>struct hash_if<T,true> { static std::size_t hash(const T& val) { static std::hash<T> gen; return gen(val); } }; template<typename T>struct hash_if<T,false> { static std::size_t hash(const T& val) { throw cov::error("E000F"); } }; template<typename T>std::size_t hash(const T& val) { return hash_if<T,hash_helper<T>::value>::hash(val); } template<typename T>void detach(T& val) { // Do something if you want when data is copying. } class any final { class baseHolder { public: baseHolder() = default; virtual ~ baseHolder() = default; virtual const std::type_info& type() const = 0; virtual baseHolder* duplicate() = 0; virtual bool compare(const baseHolder *) const = 0; virtual std::string to_string() const = 0; virtual std::size_t hash() const = 0; virtual void detach() = 0; virtual void kill() = 0; }; template < typename T > class holder:public baseHolder { protected: T mDat; public: static cov::allocator<holder<T>,COV_ANY_POOL_SIZE> allocator; holder() = default; template<typename...ArgsT>holder(ArgsT&&...args):mDat(std::forward<ArgsT>(args)...) {} virtual ~ holder() = default; virtual const std::type_info& type() const override { return typeid(T); } virtual baseHolder* duplicate() override { return allocator.alloc(mDat); } virtual bool compare(const baseHolder* obj) const override { if (obj->type()==this->type()) { const holder<T>* ptr=dynamic_cast<const holder<T>*>(obj); return ptr!=nullptr?cov::compare(mDat,ptr->data()):false; } return false; } virtual std::string to_string() const override { return std::to_string(mDat); } virtual std::size_t hash() const override { return cov::hash<T>(mDat); } virtual void detach() override { cov::detach(mDat); } virtual void kill() override { allocator.free(this); } T& data() { return mDat; } const T& data() const { return mDat; } void data(const T& dat) { mDat = dat; } }; using size_t=unsigned long; struct proxy { size_t refcount=1; baseHolder* data=nullptr; proxy()=default; proxy(size_t rc,baseHolder* d):refcount(rc),data(d) {} ~proxy() { if(data!=nullptr) data->kill(); } }; static cov::allocator<proxy,COV_ANY_POOL_SIZE> allocator; proxy* mDat=nullptr; proxy* duplicate() const noexcept { if(mDat!=nullptr) { ++mDat->refcount; } return mDat; } void recycle() noexcept { if(mDat!=nullptr) { --mDat->refcount; if(mDat->refcount==0) { allocator.free(mDat); mDat=nullptr; } } } any(proxy* dat):mDat(dat) {} public: void swap(any& obj,bool raw=false) noexcept { if(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) { baseHolder* tmp=this->mDat->data; this->mDat->data=obj.mDat->data; obj.mDat->data=tmp; } else { proxy* tmp=this->mDat; this->mDat=obj.mDat; obj.mDat=tmp; } } void swap(any&& obj,bool raw=false) noexcept { if(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) { baseHolder* tmp=this->mDat->data; this->mDat->data=obj.mDat->data; obj.mDat->data=tmp; } else { proxy* tmp=this->mDat; this->mDat=obj.mDat; obj.mDat=tmp; } } void clone() noexcept { if(mDat!=nullptr) { proxy* dat=allocator.alloc(1,mDat->data->duplicate()); recycle(); mDat=dat; } } bool usable() const noexcept { return mDat!=nullptr; } template<typename T,typename...ArgsT>static any make(ArgsT&&...args) { return any(allocator.alloc(1,holder<T>::allocator.alloc(std::forward<ArgsT>(args)...))); } any()=default; template<typename T> any(const T & dat):mDat(allocator.alloc(1,holder<T>::allocator.alloc(dat))) {} any(const any & v):mDat(v.duplicate()) {} any(any&& v) noexcept { swap(std::forward<any>(v)); } ~any() { recycle(); } const std::type_info& type() const { return this->mDat!=nullptr?this->mDat->data->type():typeid(void); } std::string to_string() const { if(this->mDat==nullptr) return "Null"; return this->mDat->data->to_string(); } std::size_t hash() const { if(this->mDat==nullptr) return cov::hash<void*>(nullptr); return this->mDat->data->hash(); } void detach() { if(this->mDat!=nullptr) this->mDat->data->detach(); } bool is_same(const any& obj) const { return this->mDat==obj.mDat; } any& operator=(const any& var) { if(&var!=this) { recycle(); mDat=var.duplicate(); } return *this; } any& operator=(any&& var) noexcept { if(&var!=this) swap(std::forward<any>(var)); return *this; } bool operator==(const any& var) const { return usable()?this->mDat->data->compare(var.mDat->data):!var.usable(); } bool operator!=(const any& var)const { return usable()?!this->mDat->data->compare(var.mDat->data):var.usable(); } template<typename T> T& val(bool raw=false) { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); if(!raw) clone(); return dynamic_cast<holder<T>*>(this->mDat->data)->data(); } template<typename T> const T& val(bool raw=false) const { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); return dynamic_cast<const holder<T>*>(this->mDat->data)->data(); } template<typename T> const T& const_val() const { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); return dynamic_cast<const holder<T>*>(this->mDat->data)->data(); } template<typename T> operator const T&() const { return this->const_val<T>(); } void assign(const any& obj,bool raw=false) { if(&obj!=this&&obj.mDat!=mDat) { if(mDat!=nullptr&&obj.mDat!=nullptr&&raw) { mDat->data->kill(); mDat->data=obj.mDat->data->duplicate(); } else { recycle(); if(obj.mDat!=nullptr) mDat=allocator.alloc(1,obj.mDat->data->duplicate()); else mDat=nullptr; } } } template<typename T> void assign(const T& dat,bool raw=false) { if(raw) { mDat->data->kill(); mDat->data=holder<T>::allocator.alloc(dat); } else { recycle(); mDat=allocator.alloc(1,holder<T>::allocator.alloc(dat)); } } template<typename T> any & operator=(const T& dat) { assign(dat); return *this; } }; template<typename T> cov::allocator<any::holder<T>,COV_ANY_POOL_SIZE> any::holder<T>::allocator; cov::allocator<any::proxy,COV_ANY_POOL_SIZE> any::allocator; template<int N> class any::holder<char[N]>:public any::holder<std::string> { public: using holder<std::string>::holder; }; template<> class any::holder<std::type_info>:public any::holder<std::type_index> { public: using holder<std::type_index>::holder; }; } std::ostream& operator<<(std::ostream& out,const cov::any& val) { out<<val.to_string(); return out; } namespace std { template<> struct hash<cov::any> { std::size_t operator()(const cov::any& val) const { return val.hash(); } }; } <commit_msg>适当调整缓冲池的大小<commit_after>#pragma once /* * Covariant Mozart Utility Library: Any * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2017 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee * Website: http://ldc.atd3.cn * * Version: 17.5.1 */ #include "./base.hpp" #include "./memory.hpp" #include <functional> #include <iostream> namespace std { template<typename T> std::string to_string(const T&) { throw cov::error("E000D"); } template<> std::string to_string<std::string>(const std::string& str) { return str; } template<> std::string to_string<bool>(const bool& v) { if(v) return "true"; else return "false"; } } #define COV_ANY_POOL_SIZE 96 namespace cov { template<typename _Tp> class compare_helper { template<typename T,typename X=bool>struct matcher; template<typename T> static constexpr bool match(T*) { return false; } template<typename T> static constexpr bool match(matcher < T, decltype(std::declval<T>()==std::declval<T>()) > *) { return true; } public: static constexpr bool value = match < _Tp > (nullptr); }; template<typename,bool> struct compare_if; template<typename T>struct compare_if<T,true> { static bool compare(const T& a,const T& b) { return a==b; } }; template<typename T>struct compare_if<T,false> { static bool compare(const T& a,const T& b) { return &a==&b; } }; template<typename T>bool compare(const T& a,const T& b) { return compare_if<T,compare_helper<T>::value>::compare(a,b); } template<typename _Tp> class hash_helper { template<typename T,decltype(&std::hash<T>::operator()) X>struct matcher; template<typename T> static constexpr bool match(T*) { return false; } template<typename T> static constexpr bool match(matcher<T,&std::hash<T>::operator()>*) { return true; } public: static constexpr bool value = match < _Tp > (nullptr); }; template<typename,bool> struct hash_if; template<typename T>struct hash_if<T,true> { static std::size_t hash(const T& val) { static std::hash<T> gen; return gen(val); } }; template<typename T>struct hash_if<T,false> { static std::size_t hash(const T& val) { throw cov::error("E000F"); } }; template<typename T>std::size_t hash(const T& val) { return hash_if<T,hash_helper<T>::value>::hash(val); } template<typename T>void detach(T& val) { // Do something if you want when data is copying. } class any final { class baseHolder { public: baseHolder() = default; virtual ~ baseHolder() = default; virtual const std::type_info& type() const = 0; virtual baseHolder* duplicate() = 0; virtual bool compare(const baseHolder *) const = 0; virtual std::string to_string() const = 0; virtual std::size_t hash() const = 0; virtual void detach() = 0; virtual void kill() = 0; }; template < typename T > class holder:public baseHolder { protected: T mDat; public: static cov::allocator<holder<T>,COV_ANY_POOL_SIZE> allocator; holder() = default; template<typename...ArgsT>holder(ArgsT&&...args):mDat(std::forward<ArgsT>(args)...) {} virtual ~ holder() = default; virtual const std::type_info& type() const override { return typeid(T); } virtual baseHolder* duplicate() override { return allocator.alloc(mDat); } virtual bool compare(const baseHolder* obj) const override { if (obj->type()==this->type()) { const holder<T>* ptr=dynamic_cast<const holder<T>*>(obj); return ptr!=nullptr?cov::compare(mDat,ptr->data()):false; } return false; } virtual std::string to_string() const override { return std::to_string(mDat); } virtual std::size_t hash() const override { return cov::hash<T>(mDat); } virtual void detach() override { cov::detach(mDat); } virtual void kill() override { allocator.free(this); } T& data() { return mDat; } const T& data() const { return mDat; } void data(const T& dat) { mDat = dat; } }; using size_t=unsigned long; struct proxy { size_t refcount=1; baseHolder* data=nullptr; proxy()=default; proxy(size_t rc,baseHolder* d):refcount(rc),data(d) {} ~proxy() { if(data!=nullptr) data->kill(); } }; static cov::allocator<proxy,COV_ANY_POOL_SIZE> allocator; proxy* mDat=nullptr; proxy* duplicate() const noexcept { if(mDat!=nullptr) { ++mDat->refcount; } return mDat; } void recycle() noexcept { if(mDat!=nullptr) { --mDat->refcount; if(mDat->refcount==0) { allocator.free(mDat); mDat=nullptr; } } } any(proxy* dat):mDat(dat) {} public: void swap(any& obj,bool raw=false) noexcept { if(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) { baseHolder* tmp=this->mDat->data; this->mDat->data=obj.mDat->data; obj.mDat->data=tmp; } else { proxy* tmp=this->mDat; this->mDat=obj.mDat; obj.mDat=tmp; } } void swap(any&& obj,bool raw=false) noexcept { if(this->mDat!=nullptr&&obj.mDat!=nullptr&&raw) { baseHolder* tmp=this->mDat->data; this->mDat->data=obj.mDat->data; obj.mDat->data=tmp; } else { proxy* tmp=this->mDat; this->mDat=obj.mDat; obj.mDat=tmp; } } void clone() noexcept { if(mDat!=nullptr) { proxy* dat=allocator.alloc(1,mDat->data->duplicate()); recycle(); mDat=dat; } } bool usable() const noexcept { return mDat!=nullptr; } template<typename T,typename...ArgsT>static any make(ArgsT&&...args) { return any(allocator.alloc(1,holder<T>::allocator.alloc(std::forward<ArgsT>(args)...))); } any()=default; template<typename T> any(const T & dat):mDat(allocator.alloc(1,holder<T>::allocator.alloc(dat))) {} any(const any & v):mDat(v.duplicate()) {} any(any&& v) noexcept { swap(std::forward<any>(v)); } ~any() { recycle(); } const std::type_info& type() const { return this->mDat!=nullptr?this->mDat->data->type():typeid(void); } std::string to_string() const { if(this->mDat==nullptr) return "Null"; return this->mDat->data->to_string(); } std::size_t hash() const { if(this->mDat==nullptr) return cov::hash<void*>(nullptr); return this->mDat->data->hash(); } void detach() { if(this->mDat!=nullptr) this->mDat->data->detach(); } bool is_same(const any& obj) const { return this->mDat==obj.mDat; } any& operator=(const any& var) { if(&var!=this) { recycle(); mDat=var.duplicate(); } return *this; } any& operator=(any&& var) noexcept { if(&var!=this) swap(std::forward<any>(var)); return *this; } bool operator==(const any& var) const { return usable()?this->mDat->data->compare(var.mDat->data):!var.usable(); } bool operator!=(const any& var)const { return usable()?!this->mDat->data->compare(var.mDat->data):var.usable(); } template<typename T> T& val(bool raw=false) { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); if(!raw) clone(); return dynamic_cast<holder<T>*>(this->mDat->data)->data(); } template<typename T> const T& val(bool raw=false) const { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); return dynamic_cast<const holder<T>*>(this->mDat->data)->data(); } template<typename T> const T& const_val() const { if(typeid(T)!=this->type()) throw cov::error("E0006"); if(this->mDat==nullptr) throw cov::error("E0005"); return dynamic_cast<const holder<T>*>(this->mDat->data)->data(); } template<typename T> operator const T&() const { return this->const_val<T>(); } void assign(const any& obj,bool raw=false) { if(&obj!=this&&obj.mDat!=mDat) { if(mDat!=nullptr&&obj.mDat!=nullptr&&raw) { mDat->data->kill(); mDat->data=obj.mDat->data->duplicate(); } else { recycle(); if(obj.mDat!=nullptr) mDat=allocator.alloc(1,obj.mDat->data->duplicate()); else mDat=nullptr; } } } template<typename T> void assign(const T& dat,bool raw=false) { if(raw) { mDat->data->kill(); mDat->data=holder<T>::allocator.alloc(dat); } else { recycle(); mDat=allocator.alloc(1,holder<T>::allocator.alloc(dat)); } } template<typename T> any & operator=(const T& dat) { assign(dat); return *this; } }; template<typename T> cov::allocator<any::holder<T>,COV_ANY_POOL_SIZE> any::holder<T>::allocator; cov::allocator<any::proxy,COV_ANY_POOL_SIZE> any::allocator; template<int N> class any::holder<char[N]>:public any::holder<std::string> { public: using holder<std::string>::holder; }; template<> class any::holder<std::type_info>:public any::holder<std::type_index> { public: using holder<std::type_index>::holder; }; } std::ostream& operator<<(std::ostream& out,const cov::any& val) { out<<val.to_string(); return out; } namespace std { template<> struct hash<cov::any> { std::size_t operator()(const cov::any& val) const { return val.hash(); } }; } <|endoftext|>
<commit_before>/****************************************************************************** * Main script for the 2017 RoboFishy Scripps AUV ******************************************************************************/ #include "Mapper.h" // Multithreading #include <pthread.h> #include <sched.h> #include <unistd.h> // Sampling Values #define SAMPLE_RATE 200 // sample rate of main control loop (Hz) #define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE! // Conversion Factors #define UNITS_KPA 0.1 // converts pressure from mbar to kPa /****************************************************************************** * Controller Gains ******************************************************************************/ // Yaw Controller #define KP_YAW 0.01 #define KI_YAW 0 #define KD_YAW 1 // Depth Controller #define KP_DEPTH 0 #define KI_DEPTH 0 #define KD_DEPTH 0 // Saturation Constants #define YAW_SAT 1 // upper limit of yaw controller #define DEPTH_SAT 1 // upper limit of depth controller #define INT_SAT 10 // upper limit of integral windup #define DINT_SAT 10 // upper limit of depth integral windup // Fluid Densities in kg/m^3 #define DENSITY_FRESHWATER 997 #define DENSITY_SALTWATER 1029 // Acceleration Due to Gravity in m/s^2 #define GRAVITY 9.81 // Depth Start Value #define DEPTH_START 50 // starting depth (mm) // Stop Timer #define STOP_TIME 10 // seconds // Leak Sensor Inpu and Power Pin #define LEAKPIN 27 // connected to GPIO 27 #define LEAKPOWERPIN 17 // providing Vcc to leak board /****************************************************************************** * Declare Threads ******************************************************************************/ void *navigation_thread(void* arg); void *depth_thread(void* arg); void *safety_thread(void* arg); void *userInterface(void* arg); /****************************************************************************** * Global Variables ******************************************************************************/ // Holds the setpoint data structure with current setpoints //setpoint_t setpoint; // Holds the latest pressure value from the MS5837 pressure sensor ms5837_t ms5837; // Holds the latest temperature value from the temperature temperature sensor float temperature; // Holds the constants and latest errors of the yaw pid controller pid_data_t yaw_pid; // Holds the constants and latest errors of the depth pid controller pid_data_t depth_pid; // Motor channels int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3}; // Ignoring sstate float depth = 0; // setmotor intialization float portmotorspeed = 0; float starmotorspeed = 0; // Start time for stop timer time_t start; /****************************************************************************** * Main Function ******************************************************************************/ int main() { // capture ctrl+c and exit signal(SIGINT, ctrl_c); // Set up RasPi GPIO pins through wiringPi wiringPiSetupGpio(); // Check if AUV is initialized correctly if( initialize_sensors() < 0 ) { return -1; } printf("\nAll components are initialized\n"); substate.mode = INITIALIZING; substate.laserarmed = ARMED; printf("Starting Threads\n"); initializeTAttr(); // Thread handles pthread_t navigationThread; pthread_t depthThread; //pthread_t safetyThread; //pthread_t disarmlaserThread; pthread_t uiThread; // Create threads using modified attributes //pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL); //pthread_create (&safetyThread, &tattrlow, safety_thread, NULL); pthread_create (&depthThread, &tattrmed, depth_thread, NULL); pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL); pthread_create (&uiThread, &tattrmed, userInterface, NULL); // Destroy the thread attributes destroyTAttr(); printf("Threads started\n"); // Start timer! start = time(0); // Run main while loop, wait until it's time to stop while(substate.mode != STOPPED) { // Check if we've passed the stop time if(difftime(time(0),start) > STOP_TIME) substate.mode = PAUSED; // Sleep a little auv_usleep(100000); } // Exit cleanly cleanup_auv(); return 0; } /****************************************************************************** * Depth Thread * * For Recording Depth & Determining If AUV is in Water or not ******************************************************************************/ void *depth_thread(void* arg) { printf("Depth Thread Started\n"); while(substate.mode!=STOPPED) { // Read pressure values ms5837 = read_pressure_fifo(); // read IMU values from fifo file substate.imu = read_imu_fifo(); // Only print while RUNNING if(substate.mode == RUNNING) { printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp); printf("Current battery temp:\t %.2f\n", read_temp_fifo()); // Write IMU data printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: " "%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ", substate.imu.yaw, substate.imu.roll, substate.imu.pitch, substate.imu.p, substate.imu.q, substate.imu.r, substate.imu.sys, substate.imu.gyro, substate.imu.accel, substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc); } auv_usleep(1000000); } pthread_exit(NULL); }//*/ /****************************************************************************** * Navigation Thread * * For yaw control *****************************************************************************/ void *navigation_thread(void* arg) { printf("Nav Thread Started\n"); initialize_motors(motor_channels, HERTZ); float yaw = 0; //Local variable for if statements float motorpercent; float basespeed = 0.2; //////////////////////////////// // Yaw Control Initialization // //////////////////////////////// yaw_pid.old = 0; // Initialize old imu data yaw_pid.setpoint = 0; // Initialize setpoint yaw_pid.derr = 0; yaw_pid.ierr = 0; // Initialize error values yaw_pid.perr = 0; yaw_pid.kp = KP_YAW; yaw_pid.kd = KD_YAW; // Initialize gain values yaw_pid.ki = KI_YAW; yaw_pid.isat = INT_SAT; // Initialize saturation values yaw_pid.sat = YAW_SAT; yaw_pid.dt = DT; // initialize time step ////////////////////////////////// // Depth Control Initialization // ////////////////////////////////// depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters) depth_pid.old = 0; // Initialize old depth depth_pid.dt = DT; // Initialize depth controller time step depth_pid.kp = KP_DEPTH; depth_pid.kd = KD_DEPTH; // Depth controller gain initialization depth_pid.ki = KI_DEPTH; depth_pid.perr = 0; depth_pid.ierr = 0; // Initialize depth controller error values depth_pid.derr = 0; depth_pid.isat = INT_SAT; // Depth controller saturation values depth_pid.sat = DEPTH_SAT; while(substate.mode!=STOPPED) { // read IMU values from fifo file substate.imu = read_imu_fifo(); if (substate.imu.yaw < 180) // AUV pointed right { yaw = substate.imu.yaw; } else // AUV pointed left { yaw =(substate.imu.yaw-360); } // Only tell motors to run if we are RUNNING if( substate.mode == RUNNING) { //calculate yaw controller output motorpercent = marchPID(yaw_pid, yaw); // Set port and starboard portmotorspeed = basespeed + motorpercent; starmotorspeed = basespeed - motorpercent; // Set port motor set_motor(0, portmotorspeed); // Set starboard motor set_motor(1, starmotorspeed); } // end if RUNNING else if( substate.mode == PAUSED) { // Stop horizontal motors set_motor(0, 0); set_motor(1, 0); // Wipe integral error yaw_pid.ierr = 0; // Sleep a while (we're not doing anything anyways) auv_usleep(100000); } // end if PAUSED // Sleep for 5 ms auv_usleep(DT); } // Turn motors off set_motor(0, 0); set_motor(1, 0); set_motor(2, 0); pthread_exit(NULL); }//*/ /****************************************************************************** * Safety Thread * * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or * water intrusion is detected *****************************************************************************/ /*void *safety_thread(void* arg) { printf("Safety Thread Started\n"); // Set up WiringPi for use // (not sure if actually needed) wiringPiSetup(); // Leak detection pins pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc // Leak checking variables int leakState; // holds the state (HIGH or LOW) of the LEAKPIN // Test if temp sensor reads anything temperature = read_temp_fifo(); printf("Temperature: %f degC\n", temperature); while( substate.mode != STOPPED ) { // Check if depth threshold has been exceeded if( substate.fdepth > DEPTH_STOP ) { substate.mode = STOPPED; printf("We're too deep! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check temperature // Shut down AUV if housing temperature gets too high if( temperature > TEMP_STOP ) { substate.mode = STOPPED; printf("It's too hot! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check for leak leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN if( leakState == HIGH ) { substate.mode = STOPPED; printf("LEAK DETECTED! Shutting down...\n"); continue; } else if (leakState == LOW) { // We're still good substate.mode = RUNNING; } // Check IMU accelerometer for collision (1+ g detected) if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY ) { substate.mode = STOPPED; printf("Collision detected. Shutting down..."); continue; } else { // We're still good substate.mode = RUNNING; } } pthread_exit(NULL); }//*/ /****************************************************************************** * Logging Thread * * Logs the sensor output data into a file *****************************************************************************/ /* PI_THREAD (logging_thread) { while(substate.mode!=STOPPED){ FILE *fd = fopen("log.txt", "a"); char buffer[100] = {0}; // add logging values to the next line sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0], sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]); fputs(buffer, fd); fclose(fd); //sleep for 100 ms usleep(100000); } return 0; } */ /****************************************************************************** * User Interface Thread * void* userInterface(void* arg) * * Interfaces with the user, asks for input *****************************************************************************/ void* userInterface(void* arg) { // Declare local constant variables float _kp, _ki, _kd; // Wait a until everything is initialized before starting while(substate.mode == INITIALIZING) { // Waiting... auv_usleep(100000); } // Prompt user for values continuously until the program exits while(substate.mode != STOPPED) { // Prompt for kp std::cout << "Kp: "; std::cin >> _kp; // Prompt for ki std::cout << "Ki: "; std::cin >> _ki; // Prompt for kd std::cout << "Kd: "; std::cin >> _kd; // Give a newline std::cout << std::endl; // Reset gain values yaw_pid.kp = _kp; yaw_pid.ki = _ki; yaw_pid.kd = _kd; // Clear errors yaw_pid.perr = 0; yaw_pid.ierr = 0; yaw_pid.derr = 0; // Start RUNNING again substate.mode = RUNNING; // Restart timer! start = time(0); } // Exit thread pthread_exit(NULL); } <commit_msg>Prettied some comments<commit_after>/****************************************************************************** * Main script for the 2017 RoboFishy Scripps AUV ******************************************************************************/ #include "Mapper.h" // Multithreading #include <pthread.h> #include <sched.h> #include <unistd.h> // Sampling Values #define SAMPLE_RATE 200 // sample rate of main control loop (Hz) #define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE! // Conversion Factors #define UNITS_KPA 0.1 // converts pressure from mbar to kPa /****************************************************************************** * Controller Gains ******************************************************************************/ // Yaw Controller #define KP_YAW 0.01 #define KI_YAW 0 #define KD_YAW 1 // Depth Controller #define KP_DEPTH 0 #define KI_DEPTH 0 #define KD_DEPTH 0 // Saturation Constants #define YAW_SAT 1 // upper limit of yaw controller #define DEPTH_SAT 1 // upper limit of depth controller #define INT_SAT 10 // upper limit of integral windup #define DINT_SAT 10 // upper limit of depth integral windup // Fluid Densities in kg/m^3 #define DENSITY_FRESHWATER 997 #define DENSITY_SALTWATER 1029 // Acceleration Due to Gravity in m/s^2 #define GRAVITY 9.81 // Depth Start Value #define DEPTH_START 50 // starting depth (mm) // Stop Timer #define STOP_TIME 10 // seconds // Leak Sensor Inpu and Power Pin #define LEAKPIN 27 // connected to GPIO 27 #define LEAKPOWERPIN 17 // providing Vcc to leak board /****************************************************************************** * Declare Threads ******************************************************************************/ void *navigation_thread(void* arg); void *depth_thread(void* arg); void *safety_thread(void* arg); void *userInterface(void* arg); /****************************************************************************** * Global Variables ******************************************************************************/ // Holds the setpoint data structure with current setpoints //setpoint_t setpoint; // Holds the latest pressure value from the MS5837 pressure sensor ms5837_t ms5837; // Holds the latest temperature value from the temperature temperature sensor float temperature; // Holds the constants and latest errors of the yaw pid controller pid_data_t yaw_pid; // Holds the constants and latest errors of the depth pid controller pid_data_t depth_pid; // Motor channels int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3}; // Ignoring sstate float depth = 0; // setmotor intialization float portmotorspeed = 0; float starmotorspeed = 0; // Start time for stop timer time_t start; /****************************************************************************** * Main Function ******************************************************************************/ int main() { // capture ctrl+c and exit signal(SIGINT, ctrl_c); // Set up RasPi GPIO pins through wiringPi wiringPiSetupGpio(); // Check if AUV is initialized correctly if( initialize_sensors() < 0 ) { return -1; } printf("\nAll components are initialized\n"); substate.mode = INITIALIZING; substate.laserarmed = ARMED; printf("Starting Threads\n"); initializeTAttr(); // Thread handles pthread_t navigationThread; pthread_t depthThread; //pthread_t safetyThread; //pthread_t disarmlaserThread; pthread_t uiThread; // Create threads using modified attributes //pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL); //pthread_create (&safetyThread, &tattrlow, safety_thread, NULL); pthread_create (&depthThread, &tattrmed, depth_thread, NULL); pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL); pthread_create (&uiThread, &tattrmed, userInterface, NULL); // Destroy the thread attributes destroyTAttr(); printf("Threads started\n"); // Start timer! start = time(0); // Run main while loop, wait until it's time to stop while(substate.mode != STOPPED) { // Check if we've passed the stop time if(difftime(time(0),start) > STOP_TIME) substate.mode = PAUSED; // Sleep a little auv_usleep(100000); } // Exit cleanly cleanup_auv(); return 0; } /****************************************************************************** * Depth Thread * * For Recording Depth & Determining If AUV is in Water or not ******************************************************************************/ void *depth_thread(void* arg) { printf("Depth Thread Started\n"); while(substate.mode!=STOPPED) { // Read pressure values ms5837 = read_pressure_fifo(); // read IMU values from fifo file substate.imu = read_imu_fifo(); // Only print while RUNNING if(substate.mode == RUNNING) { printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp); printf("Current battery temp:\t %.2f\n", read_temp_fifo()); // Write IMU data printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: " "%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ", substate.imu.yaw, substate.imu.roll, substate.imu.pitch, substate.imu.p, substate.imu.q, substate.imu.r, substate.imu.sys, substate.imu.gyro, substate.imu.accel, substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc); } auv_usleep(1000000); } pthread_exit(NULL); }//*/ /****************************************************************************** * Navigation Thread * * For yaw control *****************************************************************************/ void *navigation_thread(void* arg) { printf("Nav Thread Started\n"); initialize_motors(motor_channels, HERTZ); float yaw = 0; //Local variable for if statements float motorpercent; float basespeed = 0.2; //////////////////////////////// // Yaw Control Initialization // //////////////////////////////// yaw_pid.old = 0; // Initialize old imu data yaw_pid.setpoint = 0; // Initialize setpoint yaw_pid.derr = 0; yaw_pid.ierr = 0; // Initialize error values yaw_pid.perr = 0; yaw_pid.kp = KP_YAW; yaw_pid.kd = KD_YAW; // Initialize gain values yaw_pid.ki = KI_YAW; yaw_pid.isat = INT_SAT; // Initialize saturation values yaw_pid.sat = YAW_SAT; yaw_pid.dt = DT; // initialize time step ////////////////////////////////// // Depth Control Initialization // ////////////////////////////////// depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters) depth_pid.old = 0; // Initialize old depth depth_pid.dt = DT; // Initialize depth controller time step depth_pid.kp = KP_DEPTH; depth_pid.kd = KD_DEPTH; // Depth controller gain initialization depth_pid.ki = KI_DEPTH; depth_pid.perr = 0; depth_pid.ierr = 0; // Initialize depth controller error values depth_pid.derr = 0; depth_pid.isat = INT_SAT; // Depth controller saturation values depth_pid.sat = DEPTH_SAT; while(substate.mode!=STOPPED) { // read IMU values from fifo file substate.imu = read_imu_fifo(); if (substate.imu.yaw < 180) // AUV pointed right { yaw = substate.imu.yaw; } else // AUV pointed left { yaw =(substate.imu.yaw-360); } // Only tell motors to run if we are RUNNING if( substate.mode == RUNNING) { //calculate yaw controller output motorpercent = marchPID(yaw_pid, yaw); // Set port and starboard portmotorspeed = basespeed + motorpercent; starmotorspeed = basespeed - motorpercent; // Set port motor set_motor(0, portmotorspeed); // Set starboard motor set_motor(1, starmotorspeed); } // end if RUNNING else if( substate.mode == PAUSED) { // Stop horizontal motors set_motor(0, 0); set_motor(1, 0); // Wipe integral error yaw_pid.ierr = 0; // Sleep a while (we're not doing anything anyways) auv_usleep(100000); } // end if PAUSED // Sleep for 5 ms auv_usleep(DT); } // Turn motors off set_motor(0, 0); set_motor(1, 0); set_motor(2, 0); pthread_exit(NULL); }//*/ /****************************************************************************** * Safety Thread * * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or * water intrusion is detected *****************************************************************************/ /*void *safety_thread(void* arg) { printf("Safety Thread Started\n"); // Set up WiringPi for use // (not sure if actually needed) wiringPiSetup(); // Leak detection pins pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc // Leak checking variables int leakState; // holds the state (HIGH or LOW) of the LEAKPIN // Test if temp sensor reads anything temperature = read_temp_fifo(); printf("Temperature: %f degC\n", temperature); while( substate.mode != STOPPED ) { // Check if depth threshold has been exceeded if( substate.fdepth > DEPTH_STOP ) { substate.mode = STOPPED; printf("We're too deep! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check temperature // Shut down AUV if housing temperature gets too high if( temperature > TEMP_STOP ) { substate.mode = STOPPED; printf("It's too hot! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check for leak leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN if( leakState == HIGH ) { substate.mode = STOPPED; printf("LEAK DETECTED! Shutting down...\n"); continue; } else if (leakState == LOW) { // We're still good substate.mode = RUNNING; } // Check IMU accelerometer for collision (1+ g detected) if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY ) { substate.mode = STOPPED; printf("Collision detected. Shutting down..."); continue; } else { // We're still good substate.mode = RUNNING; } } pthread_exit(NULL); }//*/ /****************************************************************************** * Logging Thread * * Logs the sensor output data into a file *****************************************************************************/ /* PI_THREAD (logging_thread) { while(substate.mode!=STOPPED){ FILE *fd = fopen("log.txt", "a"); char buffer[100] = {0}; // add logging values to the next line sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0], sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]); fputs(buffer, fd); fclose(fd); //sleep for 100 ms usleep(100000); } return 0; } */ /****************************************************************************** * User Interface Thread * void* userInterface(void* arg) * * Interfaces with the user, asks for input *****************************************************************************/ void* userInterface(void* arg) { // Declare local constant variables float _kp, _ki, _kd; // Wait a until everything is initialized before starting while(substate.mode == INITIALIZING) { // Waiting... auv_usleep(100000); } // Prompt user for values continuously until the program exits while(substate.mode != STOPPED) { // Prompt for kp std::cout << "Kp: "; std::cin >> _kp; // Prompt for ki std::cout << "Ki: "; std::cin >> _ki; // Prompt for kd std::cout << "Kd: "; std::cin >> _kd; // Give a newline std::cout << std::endl; // Reset gain values yaw_pid.kp = _kp; yaw_pid.ki = _ki; yaw_pid.kd = _kd; // Clear errors yaw_pid.perr = 0; yaw_pid.ierr = 0; yaw_pid.derr = 0; // Start RUNNING again substate.mode = RUNNING; // Restart timer! start = time(0); } // Exit thread pthread_exit(NULL); } <|endoftext|>
<commit_before>#pragma once namespace stx { struct handle_socket { virtual void on_handle_destroyed() noexcept = 0; }; class handle { handle_socket* m_socket; public: handle() : m_socket(nullptr) {} handle(handle_socket* s) : m_socket(s) {} handle(handle&& h) : m_socket(h.m_socket) { h.m_socket = nullptr; } ~handle() { if(m_socket) { m_socket->on_handle_destroyed(); } } handle& reset(handle_socket* new_sock = nullptr) { if(m_socket) { m_socket->on_handle_destroyed(); } m_socket = new_sock; return *this; } handle& operator=(handle_socket* s) { return reset(s); } handle& operator=(handle&& s) { reset(s.m_socket); s.m_socket = nullptr; return *this; } }; class handles { std::vector<handle> m_handles; public: handles& operator<<(handle&& h) { m_handles.emplace_back(std::move(h)); return *this; } }; } // namespace stx <commit_msg>Added handles.clear()<commit_after>#pragma once namespace stx { struct handle_socket { virtual void on_handle_destroyed() noexcept = 0; }; class handle { handle_socket* m_socket; public: handle() : m_socket(nullptr) {} handle(handle_socket* s) : m_socket(s) {} handle(handle&& h) : m_socket(h.m_socket) { h.m_socket = nullptr; } ~handle() { if(m_socket) { m_socket->on_handle_destroyed(); } } handle& reset(handle_socket* new_sock = nullptr) { if(m_socket) { m_socket->on_handle_destroyed(); } m_socket = new_sock; return *this; } handle& operator=(handle_socket* s) { return reset(s); } handle& operator=(handle&& s) { reset(s.m_socket); s.m_socket = nullptr; return *this; } }; class handles { std::vector<handle> m_handles; public: handles& operator<<(handle&& h) { m_handles.emplace_back(std::move(h)); return *this; } void clear() { m_handles.clear(); } }; } // namespace stx <|endoftext|>
<commit_before><commit_msg>bool improvements<commit_after><|endoftext|>
<commit_before>// // Created by cheyulin on 5/9/16. // #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <iostream> #include <unistd.h> #include <semaphore.h> #include <vector> int thread_count; pthread_mutex_t mutex; pthread_cond_t cond_var; int idle_count = 0; using namespace std; vector<int> global_vec; bool is_end = false; void *ThreadFunction(void *thread_label) { long thread_id = (long) thread_label; pthread_mutex_lock(&mutex); long local_result = 1; while (!is_end) { global_vec.push_back(local_result); if (global_vec.size() >= 2) { local_result = 0; for (auto i = 0; i < 2; i++) { local_result += global_vec.back(); global_vec.erase(global_vec.end() - 1); } } else { if (idle_count == thread_count - 1) { is_end = true; pthread_cond_broadcast(&cond_var); } else { idle_count++; while (pthread_cond_wait(&cond_var, &mutex) != 0); } } } cout << "Thread " << thread_id << " ready to exit" << endl; pthread_mutex_unlock(&mutex); return NULL; } int main(int argc, char *argv[]) { thread_count = strtol(argv[1], NULL, 10); long thread; pthread_t *thread_handles; /* Get number of threads from command line*/ thread_handles = (pthread_t *) malloc(thread_count * sizeof(pthread_t)); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond_var, NULL); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], NULL, ThreadFunction, (void *) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_var); free(thread_handles); cout << "Global sum:" << global_vec[0] << endl; getchar(); return 0; }<commit_msg>fix bug in reduce impl<commit_after>// // Created by cheyulin on 5/9/16. // #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <iostream> #include <unistd.h> #include <semaphore.h> #include <vector> int thread_count; pthread_mutex_t mutex; pthread_cond_t cond_var; int idle_count = 0; using namespace std; vector<int> global_vec; bool is_end = false; void *ThreadFunction(void *thread_label) { long thread_id = (long) thread_label; long local_result = 1; while (!is_end) { pthread_mutex_lock(&mutex); global_vec.push_back(local_result); if (global_vec.size() >= 2) { vector<int> local_vec; for (auto i = 0; i < 2; i++) { local_vec.push_back(global_vec.back()); global_vec.erase(global_vec.end() - 1); } pthread_mutex_unlock(&mutex); //Do the computation After release the lock local_result = 0; for (auto integer:local_vec) { local_result += integer; } } else { if (idle_count == thread_count - 1) { is_end = true; pthread_cond_broadcast(&cond_var); } else { idle_count++; while (pthread_cond_wait(&cond_var, &mutex) != 0); } pthread_mutex_unlock(&mutex); } } #pragma omp critical cout << "Thread " << thread_id << " ready to exit" << endl; return NULL; } int main(int argc, char *argv[]) { thread_count = strtol(argv[1], NULL, 10); long thread; pthread_t *thread_handles; /* Get number of threads from command line*/ thread_handles = (pthread_t *) malloc(thread_count * sizeof(pthread_t)); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond_var, NULL); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], NULL, ThreadFunction, (void *) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_var); free(thread_handles); cout << "Global sum:" << global_vec[0] << endl; getchar(); return 0; }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDecimate.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkDecimate - reduce the number of triangles in a mesh // .SECTION Description // vtkDecimate is a filter to reduce the number of triangles in a triangle // mesh, while preserving the original topology and a forming good // approximation to the original geometry. The input to vtkDecimate is a // vtkPolyData object, and only triangles are treated. If you desire to // decimate polygonal meshes, first triangulate the polygons with the // vtkTriangleFilter object. // // The algorithm proceeds as follows. Each vertex in the triangle // list is evaluated for local planarity (i.e., the triangles using // the vertex are gathered and compared to an "average" plane). If the // region is locally planar, that is if the target vertex is within a // certain distance of the average plane (i.e., the error), and // there are no edges radiating from the vertex that have a dihedral angle // greater than a user-specified edge angle (i.e., feature angle), and // topology is not altered, then that vertex is deleted. The resulting // hole is then patched by re-triangulation. The process creates over // the entire vertex list (this constitutes an iteration). Iterations // proceed until a target reduction is reached or a maximum iteration // count is exceeded. // // There are a number of additional parameters you can set to control the // decimation algorithm. The error may be increased over each iteration // with the error increment. Edge preservation may be disabled or enabled. // You can turn on/off edge vertex deletion. (Edge vertices are vertices that // lie along boundaries of meshes.) Sub iterations are iterations that are // performed without changing the decimation criterion. The aspect ratio // controls the shape of the triangles that are created, and is the ratio // of maximum edge length to minimum edge length. The degree is the number // of triangles using a single vertex. Vertices of high degree are considered // "complex" and are never deleted. // // This implementation has been adapted for a global error bound decimation // criterion. That is, the error is a global bound on distance to original // surface. #ifndef __vtkDecimate_h #define __vtkDecimate_h #include "vtkPolyToPolyFilter.hh" #include "vtkMath.hh" #include "vtkTriangle.hh" #include "vtkPlane.hh" #include "vtkPolygon.hh" #include "vtkLine.hh" #define VTK_NUMBER_STATISTICS 12 // Special structures for building loops typedef struct _vtkLocalVertex { int id; float x[3]; float FAngle; int deRefs; //monitor memory requirements; new only when necessary int newRefs; } vtkLocalVertex, *vtkLocalVertexPtr; typedef struct _vtkLocalTri { int id; float area; float n[3]; int verts[3]; } vtkLocalTri, *vtkLocalTriPtr; // // Special classes for manipulating data // //BTX - begin tcl exclude // class vtkVertexArray { //;prevent man page generation public: vtkVertexArray(const int sz) {this->MaxId = -1; this->Array = new vtkLocalVertex[sz];}; ~vtkVertexArray() {if (this->Array) delete [] this->Array;}; int GetNumberOfVertices() {return this->MaxId + 1;}; void InsertNextVertex(vtkLocalVertex& v) {this->MaxId++; this->Array[this->MaxId] = v;}; vtkLocalVertex& GetVertex(int i) {return this->Array[i];}; void Reset() {this->MaxId = -1;}; vtkLocalVertex *Array; // pointer to data int MaxId; // maximum index inserted thus far }; class vtkTriArray { //;prevent man page generation public: vtkTriArray(const int sz) {this->MaxId = -1; this->Array = new vtkLocalTri[sz];}; ~vtkTriArray() {if (this->Array) delete [] this->Array;}; int GetNumberOfTriangles() {return this->MaxId + 1;}; void InsertNextTriangle(vtkLocalTri& t) {this->MaxId++; this->Array[this->MaxId] = t;}; vtkLocalTri& GetTriangle(int i) {return this->Array[i];}; void Reset() {this->MaxId = -1;}; vtkLocalTri *Array; // pointer to data int MaxId; // maximum index inserted thus far }; //ETX - end tcl exclude // class vtkDecimate : public vtkPolyToPolyFilter { public: vtkDecimate(); char *GetClassName() {return "vtkDecimate";}; void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the decimation error bounds. Expressed as a fraction of the longest // side of the input data's bounding box. vtkSetClampMacro(InitialError,float,0.0,1.0); vtkGetMacro(InitialError,float); // Description: // Set the value of the increment by which to increase the decimation // error after each iteration. vtkSetClampMacro(ErrorIncrement,float,0.0,1.0); vtkGetMacro(ErrorIncrement,float); // Description: // Set the largest decimation error that can be achieved // by incrementing the error. vtkSetClampMacro(MaximumError,float,0.0,1.0); vtkGetMacro(MaximumError,float); // Description: // Specify the desired reduction in the total number of polygons. Because // of various constraints, this level of reduction may not be realizable. vtkSetClampMacro(TargetReduction,float,0.0,1.0); vtkGetMacro(TargetReduction,float); // Description: // Specify the maximum number of iterations to attempt. If decimation target // is reached first, this value will not be reached. vtkSetClampMacro(MaximumIterations,int,1,VTK_LARGE_INTEGER); vtkGetMacro(MaximumIterations,int); // Description: // Specify the maximum sub-iterations to perform. If no triangles are deleted // in a sub-iteration, the sub-iteration process is stopped. vtkSetClampMacro(MaximumSubIterations,int,1,VTK_LARGE_INTEGER); vtkGetMacro(MaximumSubIterations,int); // Description: // Specify the mesh feature angles. vtkSetClampMacro(InitialFeatureAngle,float,0.0,180.0); vtkGetMacro(InitialFeatureAngle,float); // Description: // Set/Get the angle by which to increase feature angle over each iteration. vtkSetClampMacro(FeatureAngleIncrement,float,0.0,180.0); vtkGetMacro(FeatureAngleIncrement,float); // Description: // Set the largest permissible feature angle. vtkSetClampMacro(MaximumFeatureAngle,float,0.0,180.0); vtkGetMacro(MaximumFeatureAngle,float); // Description: // Turn on/off the preservation of feature edges. vtkSetMacro(PreserveEdges,int); vtkGetMacro(PreserveEdges,int); vtkBooleanMacro(PreserveEdges,int); // Description: // Turn on/off the deletion of vertices on the boundary of a mesh. vtkSetMacro(BoundaryVertexDeletion,int); vtkGetMacro(BoundaryVertexDeletion,int); vtkBooleanMacro(BoundaryVertexDeletion,int); // Description: // Specify the maximum allowable aspect ratio during triangulation. vtkSetClampMacro(AspectRatio,float,1.0,1000.0); vtkGetMacro(AspectRatio,float); // Description: // If the number of triangles connected to a vertex exceeds "Degree", then // the vertex is considered complex and is never deleted. (NOTE: the // complexity of the triangulation algorithm is proportional to Degree^2.) vtkSetClampMacro(Degree,int,25,VTK_CELL_SIZE); vtkGetMacro(Degree,int); protected: void Execute(); float InitialFeatureAngle; // dihedral angle constraint float FeatureAngleIncrement; float MaximumFeatureAngle; int PreserveEdges; // do/don't worry about feature edges int BoundaryVertexDeletion; float InitialError; // decimation error in fraction of bounding box float ErrorIncrement; // each iteration will bump error this amount float MaximumError; // maximum error float TargetReduction; //target reduction of mesh (fraction) int MaximumIterations; // maximum number of passes over data int MaximumSubIterations; // maximum non-incrementing passes float AspectRatio; // control triangle shape during triangulation int Degree; // maximum number of triangles incident on vertex int Stats[VTK_NUMBER_STATISTICS]; // keep track of interesting statistics int GenerateErrorScalars; // turn on/off vertex error scalar generation void CreateOutput(int numPts, int numTris, int numEliminated, vtkPointData *pd, vtkPoints *inPts); int BuildLoop(int ptId, unsigned short int nTris, int* tris); void EvaluateLoop(int& vtype, int& numFEdges, vtkLocalVertexPtr fedges[]); int CanSplitLoop(vtkLocalVertexPtr fedges[2], int numVerts, vtkLocalVertexPtr verts[], int& n1, vtkLocalVertexPtr l1[], int& n2, vtkLocalVertexPtr l2[], float& ar); void SplitLoop(vtkLocalVertexPtr fedges[2], int numVerts, vtkLocalVertexPtr *verts, int& n1, vtkLocalVertexPtr *l1, int& n2, vtkLocalVertexPtr *l2); void Triangulate(int numVerts, vtkLocalVertexPtr verts[]); int CheckError(); }; #endif <commit_msg>ERR: Added error control to limit number of warnings.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDecimate.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkDecimate - reduce the number of triangles in a mesh // .SECTION Description // vtkDecimate is a filter to reduce the number of triangles in a triangle // mesh, while preserving the original topology and a forming good // approximation to the original geometry. The input to vtkDecimate is a // vtkPolyData object, and only triangles are treated. If you desire to // decimate polygonal meshes, first triangulate the polygons with the // vtkTriangleFilter object. // // The algorithm proceeds as follows. Each vertex in the triangle // list is evaluated for local planarity (i.e., the triangles using // the vertex are gathered and compared to an "average" plane). If the // region is locally planar, that is if the target vertex is within a // certain distance of the average plane (i.e., the error), and // there are no edges radiating from the vertex that have a dihedral angle // greater than a user-specified edge angle (i.e., feature angle), and // topology is not altered, then that vertex is deleted. The resulting // hole is then patched by re-triangulation. The process continues over // the entire vertex list (this constitutes an iteration). Iterations // proceed until a target reduction is reached or a maximum iteration // count is exceeded. // // There are a number of additional parameters you can set to control // the decimation algorithm. The Error ivar may be increased over each // iteration with the ErrorIncrement. (These two variables have the // largest effect.) Edge preservation (i.e., PreserveEdges ivar) may // be disabled or enabled. You can turn on/off edge vertex deletion // (i.e., BoundaryVertexDeletion ivar). (Edge vertices are vertices // that lie along boundaries of meshes.) Sub iterations are iterations // that are performed without changing the decimation criterion. The // AspectRatio ivar controls the shape of the triangles that are // created, and is the ratio of maximum edge length to minimum edge // length. The Degree is the number of triangles using a single // vertex. Vertices of high degree are considered "complex" and are // never deleted. // // This implementation has been adapted for a global error bound decimation // criterion. That is, the error is a global bound on distance to original // surface. This is an improvement over the original Siggraph paper ("Decimation // of Triangle Meshes", Proc Siggraph `92.) #ifndef __vtkDecimate_h #define __vtkDecimate_h #include "vtkPolyToPolyFilter.hh" #include "vtkMath.hh" #include "vtkTriangle.hh" #include "vtkPlane.hh" #include "vtkPolygon.hh" #include "vtkLine.hh" #define VTK_NUMBER_STATISTICS 12 // Special structures for building loops typedef struct _vtkLocalVertex { int id; float x[3]; float FAngle; int deRefs; //monitor memory requirements; new only when necessary int newRefs; } vtkLocalVertex, *vtkLocalVertexPtr; typedef struct _vtkLocalTri { int id; float area; float n[3]; int verts[3]; } vtkLocalTri, *vtkLocalTriPtr; // // Special classes for manipulating data // //BTX - begin tcl exclude // class vtkVertexArray { //;prevent man page generation public: vtkVertexArray(const int sz) {this->MaxId = -1; this->Array = new vtkLocalVertex[sz];}; ~vtkVertexArray() {if (this->Array) delete [] this->Array;}; int GetNumberOfVertices() {return this->MaxId + 1;}; void InsertNextVertex(vtkLocalVertex& v) {this->MaxId++; this->Array[this->MaxId] = v;}; vtkLocalVertex& GetVertex(int i) {return this->Array[i];}; void Reset() {this->MaxId = -1;}; vtkLocalVertex *Array; // pointer to data int MaxId; // maximum index inserted thus far }; class vtkTriArray { //;prevent man page generation public: vtkTriArray(const int sz) {this->MaxId = -1; this->Array = new vtkLocalTri[sz];}; ~vtkTriArray() {if (this->Array) delete [] this->Array;}; int GetNumberOfTriangles() {return this->MaxId + 1;}; void InsertNextTriangle(vtkLocalTri& t) {this->MaxId++; this->Array[this->MaxId] = t;}; vtkLocalTri& GetTriangle(int i) {return this->Array[i];}; void Reset() {this->MaxId = -1;}; vtkLocalTri *Array; // pointer to data int MaxId; // maximum index inserted thus far }; //ETX - end tcl exclude // class vtkDecimate : public vtkPolyToPolyFilter { public: vtkDecimate(); char *GetClassName() {return "vtkDecimate";}; void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the decimation error bounds. Expressed as a fraction of the longest // side of the input data's bounding box. vtkSetClampMacro(InitialError,float,0.0,1.0); vtkGetMacro(InitialError,float); // Description: // Set the value of the increment by which to increase the decimation // error after each iteration. vtkSetClampMacro(ErrorIncrement,float,0.0,1.0); vtkGetMacro(ErrorIncrement,float); // Description: // Set the largest decimation error that can be achieved // by incrementing the error. vtkSetClampMacro(MaximumError,float,0.0,1.0); vtkGetMacro(MaximumError,float); // Description: // Specify the desired reduction in the total number of polygons. Because // of various constraints, this level of reduction may not be realizable. vtkSetClampMacro(TargetReduction,float,0.0,1.0); vtkGetMacro(TargetReduction,float); // Description: // Specify the maximum number of iterations to attempt. If decimation target // is reached first, this value will not be reached. vtkSetClampMacro(MaximumIterations,int,1,VTK_LARGE_INTEGER); vtkGetMacro(MaximumIterations,int); // Description: // Specify the maximum sub-iterations to perform. If no triangles are deleted // in a sub-iteration, the sub-iteration process is stopped. vtkSetClampMacro(MaximumSubIterations,int,1,VTK_LARGE_INTEGER); vtkGetMacro(MaximumSubIterations,int); // Description: // Specify the mesh feature angles. vtkSetClampMacro(InitialFeatureAngle,float,0.0,180.0); vtkGetMacro(InitialFeatureAngle,float); // Description: // Set/Get the angle by which to increase feature angle over each iteration. vtkSetClampMacro(FeatureAngleIncrement,float,0.0,180.0); vtkGetMacro(FeatureAngleIncrement,float); // Description: // Set the largest permissible feature angle. vtkSetClampMacro(MaximumFeatureAngle,float,0.0,180.0); vtkGetMacro(MaximumFeatureAngle,float); // Description: // Turn on/off the preservation of feature edges. vtkSetMacro(PreserveEdges,int); vtkGetMacro(PreserveEdges,int); vtkBooleanMacro(PreserveEdges,int); // Description: // Turn on/off the deletion of vertices on the boundary of a mesh. vtkSetMacro(BoundaryVertexDeletion,int); vtkGetMacro(BoundaryVertexDeletion,int); vtkBooleanMacro(BoundaryVertexDeletion,int); // Description: // Specify the maximum allowable aspect ratio during triangulation. vtkSetClampMacro(AspectRatio,float,1.0,1000.0); vtkGetMacro(AspectRatio,float); // Description: // If the number of triangles connected to a vertex exceeds "Degree", then // the vertex is considered complex and is never deleted. (NOTE: the // complexity of the triangulation algorithm is proportional to Degree^2.) vtkSetClampMacro(Degree,int,25,VTK_CELL_SIZE); vtkGetMacro(Degree,int); // Description: // Control the printout of warnings. This flag limits the number of warnings // regarding non-manifold geometry and complex vertices. If set to zero, no // warnings will appear. vtkSetClampMacro(MaximumNumberOfSquawks,int,0,VTK_LARGE_INTEGER); vtkGetMacro(MaximumNumberOfSquawks,int); protected: void Execute(); float InitialFeatureAngle; // dihedral angle constraint float FeatureAngleIncrement; float MaximumFeatureAngle; int PreserveEdges; // do/don't worry about feature edges int BoundaryVertexDeletion; float InitialError; // decimation error in fraction of bounding box float ErrorIncrement; // each iteration will bump error this amount float MaximumError; // maximum error float TargetReduction; //target reduction of mesh (fraction) int MaximumIterations; // maximum number of passes over data int MaximumSubIterations; // maximum non-incrementing passes float AspectRatio; // control triangle shape during triangulation int Degree; // maximum number of triangles incident on vertex int Stats[VTK_NUMBER_STATISTICS]; // keep track of interesting statistics int GenerateErrorScalars; // turn on/off vertex error scalar generation int MaximumNumberOfSquawks; //control number of error messages void CreateOutput(int numPts, int numTris, int numEliminated, vtkPointData *pd, vtkPoints *inPts); int BuildLoop(int ptId, unsigned short int nTris, int* tris); void EvaluateLoop(int& vtype, int& numFEdges, vtkLocalVertexPtr fedges[]); int CanSplitLoop(vtkLocalVertexPtr fedges[2], int numVerts, vtkLocalVertexPtr verts[], int& n1, vtkLocalVertexPtr l1[], int& n2, vtkLocalVertexPtr l2[], float& ar); void SplitLoop(vtkLocalVertexPtr fedges[2], int numVerts, vtkLocalVertexPtr *verts, int& n1, vtkLocalVertexPtr *l1, int& n2, vtkLocalVertexPtr *l2); void Triangulate(int numVerts, vtkLocalVertexPtr verts[]); int CheckError(); }; #endif <|endoftext|>
<commit_before>#include "stdsneezy.h" #include "database.h" #include "session.cgi.h" #include <cgicc/Cgicc.h> #include <cgicc/HTTPCookie.h> #include <cgicc/CgiEnvironment.h> #include <sys/types.h> #include <md5.h> cgicc::HTTPCookie TSession::getCookie() { cgicc::HTTPCookie cookie(cookiename, getSessionID()); if(cookieduration>=0) cookie.setMaxAge(cookieduration); return cookie; } bool TSession::checkPasswd(sstring name, sstring passwd) { TDatabase db(DB_SNEEZY); db.query("select account_id, passwd from account where name='%s'", name.c_str()); // account not found. I debated whether or not we should let users know // about this and decided it's bad to let them figure out what account // names exist. if(!db.fetchRow()) return false; // get the encrypted form. sstring crypted=crypt(passwd.c_str(), name.c_str()); // sneezy truncates the encrypted password for some reason crypted=crypted.substr(0,10); // bad password if(crypted != db["passwd"]) return false; account_id=convertTo<int>(db["account_id"]); if(!account_id){ account_id=-1; return -1; } return true; } void TSession::logout() { TDatabase db(DB_SNEEZY); db.query("delete from cgisession where session_id='%s'", session_id.c_str()); cookieduration=0; } bool TSession::isValid() { if(session_id.empty() || account_id < 0){ return false; } return true; } TSession::TSession(cgicc::Cgicc c, sstring cn) { session_id=""; account_id=-1; cookiename=cn; cookieduration=0; cgi=&c; session_id=getSessionCookie(); if(!session_id.empty()){ account_id=validateSessionID(); } } int TSession::validateSessionID() { TDatabase db(DB_SNEEZY); db.query("select account_id from cgisession where session_id='%s' and (timeset+duration) > %i", session_id.c_str(), time(NULL)); if(!db.fetchRow()) return -1; int a=convertTo<int>(db["account_id"]); return (a ? a : -1); } // gets the value of the "mudmail" cookie and returns it sstring TSession::getSessionCookie() { cgicc::CgiEnvironment env = cgi->getEnvironment(); vector<cgicc::HTTPCookie> cookies = env.getCookieList(); if(!cookies.size()) return ""; for(unsigned int i=0;i<cookies.size();++i){ if(cookies[i].getName() == cookiename) return cookies[i].getValue(); } return ""; } void TSession::createSession() { createSession(60*60); cookieduration=-1; } void TSession::createSession(int duration) { cookieduration=duration; TDatabase db(DB_SNEEZY); do { session_id=generateSessionID(); db.query("select 1 from cgisession where session_id='%s'", session_id.c_str()); } while(db.fetchRow()); db.query("delete from cgisession where account_id=%i", account_id); db.query("insert into cgisession values ('%s', %i, %i, %i)", session_id.c_str(), account_id, duration, time(NULL)); } sstring TSession::generateSessionID() { unsigned char data[16]; int length=16; int seed[4]; srandomdev(); seed[0]=time(NULL); seed[1]=random(); seed[2]=getpid(); seed[3]=(int)&seed; int c=0; for(int i=0;i<4;++i){ for(int j=0;j<4;++j){ data[c++]=(&seed[i])[j]; } } return MD5Data(data, length, NULL); } <commit_msg>added a name field to cgisession to identify which app set that session this is just for convenience in debugging and so on.<commit_after>#include "stdsneezy.h" #include "database.h" #include "session.cgi.h" #include <cgicc/Cgicc.h> #include <cgicc/HTTPCookie.h> #include <cgicc/CgiEnvironment.h> #include <sys/types.h> #include <md5.h> cgicc::HTTPCookie TSession::getCookie() { cgicc::HTTPCookie cookie(cookiename, getSessionID()); if(cookieduration>=0) cookie.setMaxAge(cookieduration); return cookie; } bool TSession::checkPasswd(sstring name, sstring passwd) { TDatabase db(DB_SNEEZY); db.query("select account_id, passwd from account where name='%s'", name.c_str()); // account not found. I debated whether or not we should let users know // about this and decided it's bad to let them figure out what account // names exist. if(!db.fetchRow()) return false; // get the encrypted form. sstring crypted=crypt(passwd.c_str(), name.c_str()); // sneezy truncates the encrypted password for some reason crypted=crypted.substr(0,10); // bad password if(crypted != db["passwd"]) return false; account_id=convertTo<int>(db["account_id"]); if(!account_id){ account_id=-1; return -1; } return true; } void TSession::logout() { TDatabase db(DB_SNEEZY); db.query("delete from cgisession where session_id='%s'", session_id.c_str()); cookieduration=0; } bool TSession::isValid() { if(session_id.empty() || account_id < 0){ return false; } return true; } TSession::TSession(cgicc::Cgicc c, sstring cn) { session_id=""; account_id=-1; cookiename=cn; cookieduration=0; cgi=&c; session_id=getSessionCookie(); if(!session_id.empty()){ account_id=validateSessionID(); } } int TSession::validateSessionID() { TDatabase db(DB_SNEEZY); db.query("select account_id from cgisession where session_id='%s' and (timeset+duration) > %i", session_id.c_str(), time(NULL)); if(!db.fetchRow()) return -1; int a=convertTo<int>(db["account_id"]); return (a ? a : -1); } // gets the value of the "mudmail" cookie and returns it sstring TSession::getSessionCookie() { cgicc::CgiEnvironment env = cgi->getEnvironment(); vector<cgicc::HTTPCookie> cookies = env.getCookieList(); if(!cookies.size()) return ""; for(unsigned int i=0;i<cookies.size();++i){ if(cookies[i].getName() == cookiename) return cookies[i].getValue(); } return ""; } void TSession::createSession() { createSession(60*60); cookieduration=-1; } void TSession::createSession(int duration) { cookieduration=duration; TDatabase db(DB_SNEEZY); do { session_id=generateSessionID(); db.query("select 1 from cgisession where session_id='%s'", session_id.c_str()); } while(db.fetchRow()); db.query("delete from cgisession where account_id=%i", account_id); db.query("insert into cgisession values ('%s', %i, %i, %i, '%s')", session_id.c_str(), account_id, duration, time(NULL), cookiename.c_str()); } sstring TSession::generateSessionID() { unsigned char data[16]; int length=16; int seed[4]; srandomdev(); seed[0]=time(NULL); seed[1]=random(); seed[2]=getpid(); seed[3]=(int)&seed; int c=0; for(int i=0;i<4;++i){ for(int j=0;j<4;++j){ data[c++]=(&seed[i])[j]; } } return MD5Data(data, length, NULL); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkStructuredPointsGeometryFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkStructuredPointsGeometryFilter.h" // Construct with initial extent of all the data vtkStructuredPointsGeometryFilter::vtkStructuredPointsGeometryFilter() { this->Extent[0] = 0; this->Extent[1] = VTK_LARGE_INTEGER; this->Extent[2] = 0; this->Extent[3] = VTK_LARGE_INTEGER; this->Extent[4] = 0; this->Extent[5] = VTK_LARGE_INTEGER; } void vtkStructuredPointsGeometryFilter::Execute() { int *dims, dimension, dir[3], diff[3]; int i, j, k, extent[6]; int ptIds[4], idx, startIdx; int cellId; vtkPoints *newPts=0; vtkCellArray *newVerts=0; vtkCellArray *newLines=0; vtkCellArray *newPolys=0; int totPoints, numPolys; int offset[3], pos; float *x; vtkPointData *pd, *outPD; vtkCellData *cd, *outCD; vtkStructuredPoints *input=(vtkStructuredPoints *)this->Input; vtkPolyData *output=(vtkPolyData *)this->Output; vtkDebugMacro(<< "Extracting structured points geometry"); pd = input->GetPointData(); outPD = output->GetPointData(); cd = input->GetCellData(); outCD = output->GetCellData(); // this->PointData.CopyNormalsOff(); dims = input->GetDimensions(); // // Based on the dimensions of the structured data, and the extent of the geometry, // compute the combined extent plus the dimensionality of the data // for (dimension=3, i=0; i<3; i++) { extent[2*i] = this->Extent[2*i] < 0 ? 0 : this->Extent[2*i]; extent[2*i] = this->Extent[2*i] >= dims[i] ? dims[i]-1 : this->Extent[2*i]; extent[2*i+1] = this->Extent[2*i+1] >= dims[i] ? dims[i]-1 : this->Extent[2*i+1]; if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i]; if ( (extent[2*i+1] - extent[2*i]) == 0 ) dimension--; } // // Now create polygonal data based on dimension of data // startIdx = extent[0] + extent[2]*dims[0] + extent[4]*dims[0]*dims[1]; switch (dimension) { default: break; case 0: // --------------------- build point ----------------------- newPts = vtkPoints::New(); newPts->Allocate(1); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(1,1)); outPD->CopyAllocate(pd,1); outCD->CopyAllocate(cd,1); ptIds[0] = newPts->InsertNextPoint(input->GetPoint(startIdx)); outPD->CopyData(pd,startIdx,ptIds[0]); cellId = newVerts->InsertNextCell(1,ptIds); outCD->CopyData(cd,startIdx,ptIds[0]); break; case 1: // --------------------- build line ----------------------- for (dir[0]=dir[1]=dir[2]=totPoints=0, i=0; i<3; i++) { if ( (diff[i] = extent[2*i+1] - extent[2*i]) > 0 ) { dir[0] = i; totPoints = diff[i] + 1; break; } } newPts = vtkPoints::New(); newPts->Allocate(totPoints); newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(totPoints-1,2)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,totPoints - 1); // // Load data // if ( dir[0] == 0 ) offset[0] = 1; else if (dir[0] == 1) offset[0] = dims[0]; else offset[0] = dims[0]*dims[1]; for (i=0; i<totPoints; i++) { idx = startIdx + i*offset[0]; x = input->GetPoint(idx); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,idx,ptIds[0]); } if ( dir[0] == 0 ) offset[0] = 1; else if (dir[0] == 1) offset[0] = dims[0] - 1; else offset[0] = (dims[0] - 1) * (dims[1] - 1); for (i=0; i<(totPoints-1); i++) { idx = startIdx + i*offset[0]; ptIds[0] = i; ptIds[1] = i + 1; cellId = newLines->InsertNextCell(2,ptIds); outCD->CopyData(cd,idx,cellId); } break; case 2: // --------------------- build plane ----------------------- // // Create the data objects // for (dir[0]=dir[1]=dir[2]=idx=0,i=0; i<3; i++) { if ( (diff[i] = extent[2*i+1] - extent[2*i]) != 0 ) dir[idx++] = i; else dir[2] = i; } totPoints = (diff[dir[0]]+1) * (diff[dir[1]]+1); numPolys = diff[dir[0]] * diff[dir[1]]; newPts = vtkPoints::New(); newPts->Allocate(totPoints); newPolys = vtkCellArray::New(); newPolys->Allocate(newLines->EstimateSize(numPolys,4)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,numPolys); // // Create vertices // for (i=0; i<2; i++) { if ( dir[i] == 0 ) offset[i] = 1; else if ( dir[i] == 1 ) offset[i] = dims[0]; else if ( dir[i] == 2 ) offset[i] = dims[0]*dims[1]; } for (pos=startIdx, j=0; j < (diff[dir[1]]+1); j++) { for (i=0; i < (diff[dir[0]]+1); i++) { idx = pos + i*offset[0]; x = input->GetPoint(idx); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,idx,ptIds[0]); } pos += offset[1]; } // // Create cells // for (i=0; i<2; i++) { if ( dir[i] == 0 ) offset[i] = 1; else if ( dir[i] == 1 ) offset[i] = (dims[0] - 1); else if ( dir[i] == 2 ) offset[i] = (dims[0] - 1) * (dims[1] - 1); } for (pos=startIdx, j=0; j < diff[dir[1]]; j++) { for (i=0; i < diff[dir[0]]; i++) { idx = pos + i*offset[0]; ptIds[0] = i + j*(diff[dir[0]]+1); ptIds[1] = ptIds[0] + 1; ptIds[2] = ptIds[1] + diff[dir[0]] + 1; ptIds[3] = ptIds[2] - 1; cellId = newPolys->InsertNextCell(4,ptIds); outCD->CopyData(cd,idx,cellId); } pos += offset[1]; } break; case 3: // ------------------- grab points in volume -------------- // // Create data objects // for (i=0; i<3; i++) diff[i] = extent[2*i+1] - extent[2*i]; totPoints = (diff[0]+1) * (diff[1]+1) * (diff[2]+1); newPts = vtkPoints::New(); newPts->Allocate(totPoints); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(totPoints,1)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,totPoints); // // Create vertices and cells // offset[0] = dims[0]; offset[1] = dims[0]*dims[1]; for (pos=startIdx, k=0; k < (diff[2]+1); k++) { for (j=0; j < (diff[1]+1); j++) { pos = startIdx + j*offset[0] + k*offset[1]; for (i=0; i < (diff[0]+1); i++) { x = input->GetPoint(pos+i); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,pos+i,ptIds[0]); cellId = newVerts->InsertNextCell(1,ptIds); outCD->CopyData(cd,pos+i,cellId); } } } break; /* end this case */ } // switch // // Update self and release memory // if (newPts) { output->SetPoints(newPts); newPts->Delete(); } if (newVerts) { output->SetVerts(newVerts); newVerts->Delete(); } if (newLines) { output->SetLines(newLines); newLines->Delete(); } if (newPolys) { output->SetPolys(newPolys); newPolys->Delete(); } } void vtkStructuredPointsGeometryFilter::SetExtent(int iMin, int iMax, int jMin, int jMax, int kMin, int kMax) { int extent[6]; extent[0] = iMin; extent[1] = iMax; extent[2] = jMin; extent[3] = jMax; extent[4] = kMin; extent[5] = kMax; this->SetExtent(extent); } // Specify (imin,imax, jmin,jmax, kmin,kmax) indices. void vtkStructuredPointsGeometryFilter::SetExtent(int *extent) { int i; if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] || extent[2] != this->Extent[2] || extent[3] != this->Extent[3] || extent[4] != this->Extent[4] || extent[5] != this->Extent[5] ) { this->Modified(); for (i=0; i<3; i++) { if ( extent[2*i] < 0 ) extent[2*i] = 0; if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i]; this->Extent[2*i] = extent[2*i]; this->Extent[2*i+1] = extent[2*i+1]; } } } void vtkStructuredPointsGeometryFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredPointsToPolyDataFilter::PrintSelf(os,indent); os << indent << "Extent: \n"; os << indent << " Imin,Imax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n"; os << indent << " Jmin,Jmax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n"; os << indent << " Kmin,Kmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n"; } <commit_msg>ERR: Was not passing cell data.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkStructuredPointsGeometryFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkStructuredPointsGeometryFilter.h" // Construct with initial extent of all the data vtkStructuredPointsGeometryFilter::vtkStructuredPointsGeometryFilter() { this->Extent[0] = 0; this->Extent[1] = VTK_LARGE_INTEGER; this->Extent[2] = 0; this->Extent[3] = VTK_LARGE_INTEGER; this->Extent[4] = 0; this->Extent[5] = VTK_LARGE_INTEGER; } void vtkStructuredPointsGeometryFilter::Execute() { int *dims, dimension, dir[3], diff[3]; int i, j, k, extent[6]; int ptIds[4], idx, startIdx; int cellId; vtkPoints *newPts=0; vtkCellArray *newVerts=0; vtkCellArray *newLines=0; vtkCellArray *newPolys=0; int totPoints, numPolys; int offset[3], pos; float *x; vtkPointData *pd, *outPD; vtkCellData *cd, *outCD; vtkStructuredPoints *input=(vtkStructuredPoints *)this->Input; vtkPolyData *output=(vtkPolyData *)this->Output; vtkDebugMacro(<< "Extracting structured points geometry"); pd = input->GetPointData(); outPD = output->GetPointData(); cd = input->GetCellData(); outCD = output->GetCellData(); // this->PointData.CopyNormalsOff(); dims = input->GetDimensions(); // // Based on the dimensions of the structured data, and the extent of the geometry, // compute the combined extent plus the dimensionality of the data // for (dimension=3, i=0; i<3; i++) { extent[2*i] = this->Extent[2*i] < 0 ? 0 : this->Extent[2*i]; extent[2*i] = this->Extent[2*i] >= dims[i] ? dims[i]-1 : this->Extent[2*i]; extent[2*i+1] = this->Extent[2*i+1] >= dims[i] ? dims[i]-1 : this->Extent[2*i+1]; if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i]; if ( (extent[2*i+1] - extent[2*i]) == 0 ) dimension--; } // // Now create polygonal data based on dimension of data // startIdx = extent[0] + extent[2]*dims[0] + extent[4]*dims[0]*dims[1]; switch (dimension) { default: break; case 0: // --------------------- build point ----------------------- newPts = vtkPoints::New(); newPts->Allocate(1); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(1,1)); outPD->CopyAllocate(pd,1); outCD->CopyAllocate(cd,1); ptIds[0] = newPts->InsertNextPoint(input->GetPoint(startIdx)); outPD->CopyData(pd,startIdx,ptIds[0]); cellId = newVerts->InsertNextCell(1,ptIds); outCD->CopyData(cd,startIdx,cellId); break; case 1: // --------------------- build line ----------------------- for (dir[0]=dir[1]=dir[2]=totPoints=0, i=0; i<3; i++) { if ( (diff[i] = extent[2*i+1] - extent[2*i]) > 0 ) { dir[0] = i; totPoints = diff[i] + 1; break; } } newPts = vtkPoints::New(); newPts->Allocate(totPoints); newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(totPoints-1,2)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,totPoints - 1); // // Load data // if ( dir[0] == 0 ) offset[0] = 1; else if (dir[0] == 1) offset[0] = dims[0]; else offset[0] = dims[0]*dims[1]; for (i=0; i<totPoints; i++) { idx = startIdx + i*offset[0]; x = input->GetPoint(idx); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,idx,ptIds[0]); } if ( dir[0] == 0 ) offset[0] = 1; else if (dir[0] == 1) offset[0] = dims[0] - 1; else offset[0] = (dims[0] - 1) * (dims[1] - 1); for (i=0; i<(totPoints-1); i++) { idx = startIdx + i*offset[0]; ptIds[0] = i; ptIds[1] = i + 1; cellId = newLines->InsertNextCell(2,ptIds); outCD->CopyData(cd,idx,cellId); } break; case 2: // --------------------- build plane ----------------------- // // Create the data objects // for (dir[0]=dir[1]=dir[2]=idx=0,i=0; i<3; i++) { if ( (diff[i] = extent[2*i+1] - extent[2*i]) != 0 ) dir[idx++] = i; else dir[2] = i; } totPoints = (diff[dir[0]]+1) * (diff[dir[1]]+1); numPolys = diff[dir[0]] * diff[dir[1]]; newPts = vtkPoints::New(); newPts->Allocate(totPoints); newPolys = vtkCellArray::New(); newPolys->Allocate(newLines->EstimateSize(numPolys,4)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,numPolys); // // Create vertices // for (i=0; i<2; i++) { if ( dir[i] == 0 ) offset[i] = 1; else if ( dir[i] == 1 ) offset[i] = dims[0]; else if ( dir[i] == 2 ) offset[i] = dims[0]*dims[1]; } for (pos=startIdx, j=0; j < (diff[dir[1]]+1); j++) { for (i=0; i < (diff[dir[0]]+1); i++) { idx = pos + i*offset[0]; x = input->GetPoint(idx); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,idx,ptIds[0]); } pos += offset[1]; } // // Create cells // for (i=0; i<2; i++) { if ( dir[i] == 0 ) offset[i] = 1; else if ( dir[i] == 1 ) offset[i] = (dims[0] - 1); else if ( dir[i] == 2 ) offset[i] = (dims[0] - 1) * (dims[1] - 1); } for (pos=startIdx, j=0; j < diff[dir[1]]; j++) { for (i=0; i < diff[dir[0]]; i++) { idx = pos + i*offset[0]; ptIds[0] = i + j*(diff[dir[0]]+1); ptIds[1] = ptIds[0] + 1; ptIds[2] = ptIds[1] + diff[dir[0]] + 1; ptIds[3] = ptIds[2] - 1; cellId = newPolys->InsertNextCell(4,ptIds); outCD->CopyData(cd,idx,cellId); } pos += offset[1]; } break; case 3: // ------------------- grab points in volume -------------- // // Create data objects // for (i=0; i<3; i++) diff[i] = extent[2*i+1] - extent[2*i]; totPoints = (diff[0]+1) * (diff[1]+1) * (diff[2]+1); newPts = vtkPoints::New(); newPts->Allocate(totPoints); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(totPoints,1)); outPD->CopyAllocate(pd,totPoints); outCD->CopyAllocate(cd,totPoints); // // Create vertices and cells // offset[0] = dims[0]; offset[1] = dims[0]*dims[1]; for (pos=startIdx, k=0; k < (diff[2]+1); k++) { for (j=0; j < (diff[1]+1); j++) { pos = startIdx + j*offset[0] + k*offset[1]; for (i=0; i < (diff[0]+1); i++) { x = input->GetPoint(pos+i); ptIds[0] = newPts->InsertNextPoint(x); outPD->CopyData(pd,pos+i,ptIds[0]); cellId = newVerts->InsertNextCell(1,ptIds); outCD->CopyData(cd,pos+i,cellId); } } } break; /* end this case */ } // switch // // Update self and release memory // if (newPts) { output->SetPoints(newPts); newPts->Delete(); } if (newVerts) { output->SetVerts(newVerts); newVerts->Delete(); } if (newLines) { output->SetLines(newLines); newLines->Delete(); } if (newPolys) { output->SetPolys(newPolys); newPolys->Delete(); } } void vtkStructuredPointsGeometryFilter::SetExtent(int iMin, int iMax, int jMin, int jMax, int kMin, int kMax) { int extent[6]; extent[0] = iMin; extent[1] = iMax; extent[2] = jMin; extent[3] = jMax; extent[4] = kMin; extent[5] = kMax; this->SetExtent(extent); } // Specify (imin,imax, jmin,jmax, kmin,kmax) indices. void vtkStructuredPointsGeometryFilter::SetExtent(int *extent) { int i; if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] || extent[2] != this->Extent[2] || extent[3] != this->Extent[3] || extent[4] != this->Extent[4] || extent[5] != this->Extent[5] ) { this->Modified(); for (i=0; i<3; i++) { if ( extent[2*i] < 0 ) extent[2*i] = 0; if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i]; this->Extent[2*i] = extent[2*i]; this->Extent[2*i+1] = extent[2*i+1]; } } } void vtkStructuredPointsGeometryFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredPointsToPolyDataFilter::PrintSelf(os,indent); os << indent << "Extent: \n"; os << indent << " Imin,Imax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n"; os << indent << " Jmin,Jmax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n"; os << indent << " Kmin,Kmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n"; } <|endoftext|>
<commit_before>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 10000; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. cout << sin((PI/2) * (1/time_to_complete)) << endl; Pulse(out1, sin((PI/2) * (1/time_to_complete))); Wait(sin((PI/2) * (1/time_to_complete))); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <commit_msg>Update pwm.cpp<commit_after>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 10000; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. cout << sin((PI/2) * (1/clock())) << endl; Pulse(out1, sin((PI/2) * (1/time_to_complete))); Wait(sin((PI/2) * (1/time_to_complete))); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <|endoftext|>
<commit_before>#include <Sound.h> #include <Display.h> #include <SDL.h> #include <SDL_mixer.h> #include <hx/Thread.h> namespace nme { bool gSDLIsInit = false; class SDLSoundChannel; bool sChannelsInit = false; enum { sMaxChannels = 8 }; bool sUsedChannel[sMaxChannels]; bool sDoneChannel[sMaxChannels]; void *sUsedMusic = 0; bool sDoneMusic = false; unsigned int sSoundPos = 0; void onChannelDone(int inChannel) { if (sUsedChannel[inChannel]) sDoneChannel[inChannel] = true; } void onMusicDone() { if (sUsedMusic) sDoneMusic = true; } void onPostMix(void *udata, Uint8 *stream, int len) { sSoundPos += len; } static bool Init() { if (!gSDLIsInit) { fprintf(stderr,"Please init Stage before creating sound.\n"); return false; } if (!sChannelsInit) { sChannelsInit = true; for(int i=0;i<sMaxChannels;i++) { sUsedChannel[i] = false; sDoneChannel[i] = false; } Mix_ChannelFinished(onChannelDone); Mix_HookMusicFinished(onMusicDone); Mix_SetPostMix(onPostMix,0); } return sChannelsInit; } // --- Using "Mix_Chunk" API ---------------------------------------------------- class SDLSoundChannel : public SoundChannel { enum { BUF_SIZE = 16384 }; public: SDLSoundChannel(Object *inSound, Mix_Chunk *inChunk, double inStartTime, int inLoops, const SoundTransform &inTransform) { mChunk = inChunk; mDynamicBuffer = 0; mSound = inSound; mSound->IncRef(); mChannel = -1; // Allocate myself a channel if (mChunk) { for(int i=0;i<sMaxChannels;i++) if (!sUsedChannel[i]) { IncRef(); sDoneChannel[i] = false; sUsedChannel[i] = true; mChannel = i; break; } } if (mChannel>=0) { Mix_PlayChannel( mChannel , mChunk, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 ); Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); // Mix_SetPanning } } SDLSoundChannel(const ByteArray &inBytes, const SoundTransform &inTransform) { mChunk = 0; mDynamicBuffer = new short[BUF_SIZE]; memset(mDynamicBuffer,0,BUF_SIZE*sizeof(short)); mSound = 0; mChannel = -1; mDynamicChunk.allocated = 0; mDynamicChunk.abuf = (Uint8 *)mDynamicBuffer; mDynamicChunk.alen = BUF_SIZE; mDynamicChunk.volume = MIX_MAX_VOLUME; mDynamicChunk.length_ticks = 0; mDynamicFillPos = 0; mDynamicStartPos = 0; mDynamicDataDue = 0; Mix_QuerySpec(&mFrequency, &mFormat, &mChannels); // Allocate myself a channel for(int i=0;i<sMaxChannels;i++) if (!sUsedChannel[i]) { IncRef(); sDoneChannel[i] = false; sUsedChannel[i] = true; mChannel = i; break; } if (mChannel>=0) { FillBuffer(inBytes); // Just once ... if (mDynamicFillPos<2048) { mDynamicDone = true; mDynamicChunk.alen = mDynamicFillPos; Mix_PlayChannel( mChannel , &mDynamicChunk, 0 ); } else { mDynamicDone = false; Mix_PlayChannel( mChannel , &mDynamicChunk, -1 ); // TODO: Lock? mDynamicStartPos = sSoundPos; } Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); } } void FillBuffer(const ByteArray &inBytes) { int floats = inBytes.Size()/sizeof(float); const float *buffer = (const float *)inBytes.Bytes(); int pos = mDynamicFillPos & (BUF_SIZE-1); mDynamicFillPos += floats; int first = std::min( floats, BUF_SIZE-pos ); for(int i=0;i<first;i++) mDynamicBuffer[pos+i] = *buffer++ * 16385; if (first<floats) { floats -= first; for(int i=0;i<floats;i++) mDynamicBuffer[i] = *buffer++ * 16385; } } ~SDLSoundChannel() { delete [] mDynamicBuffer; if (mSound) mSound->DecRef(); } void CheckDone() { if (mChannel>=0 && sDoneChannel[mChannel]) { sDoneChannel[mChannel] = false; int c = mChannel; mChannel = -1; DecRef(); sUsedChannel[c] = 0; } } bool isComplete() { CheckDone(); return mChannel < 0; } double getLeft() { return 1; } double getRight() { return 1; } double getPosition() { return 1; } void stop() { if (mChannel>=0) Mix_HaltChannel(mChannel); } void setTransform(const SoundTransform &inTransform) { if (mChannel>=0) Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); } double getDataPosition() { int pos = (sSoundPos-mDynamicStartPos)*1000.0/mFrequency; } bool needsData() { if (!mDynamicBuffer || mDynamicDone) return false; if (mDynamicDataDue<=sSoundPos) { mDynamicDone = true; return true; } return false; } void addData(const ByteArray &inBytes) { mDynamicDone = false; mDynamicDataDue = mDynamicFillPos + mDynamicStartPos; FillBuffer(inBytes); } Object *mSound; Mix_Chunk *mChunk; int mChannel; Mix_Chunk mDynamicChunk; short *mDynamicBuffer; unsigned int mDynamicFillPos; unsigned int mDynamicStartPos; unsigned int mDynamicDataDue; bool mDynamicDone; int mFrequency; Uint16 mFormat; int mChannels; }; SoundChannel *SoundChannel::Create(const ByteArray &inBytes,const SoundTransform &inTransform) { return new SDLSoundChannel(inBytes,inTransform); } class SDLSound : public Sound { public: SDLSound(const std::string &inFilename) { IncRef(); #ifdef HX_MACOS char name[1024]; GetBundleFilename(inFilename.c_str(),name,1024); #else const char *name = inFilename.c_str(); #endif mChunk = Mix_LoadWAV(name); if ( mChunk == NULL ) { mError = SDL_GetError(); // printf("Error %s (%s)\n", mError.c_str(), name ); } } ~SDLSound() { if (mChunk) Mix_FreeChunk( mChunk ); } double getLength() { if (mChunk==0) return 0; #if defined(DYNAMIC_SDL) || defined(WEBOS) // ? return 0.0; #else return 0.0; //return mChunk->length_ticks; #endif } // Will return with one ref... SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform) { if (!mChunk) return 0; return new SDLSoundChannel(this,mChunk,startTime, loops,inTransform); } int getBytesLoaded() { return mChunk ? mChunk->alen : 0; } int getBytesTotal() { return mChunk ? mChunk->alen : 0; } bool ok() { return mChunk; } std::string getError() { return mError; } std::string mError; Mix_Chunk *mChunk; }; // --- Using "Mix_Music" API ---------------------------------------------------- class SDLMusicChannel : public SoundChannel { public: SDLMusicChannel(Object *inSound, Mix_Music *inMusic, double inStartTime, int inLoops, const SoundTransform &inTransform) { mMusic = inMusic; mSound = inSound; mSound->IncRef(); mPlaying = false; if (mMusic) { mPlaying = true; sUsedMusic = this; sDoneMusic = false; IncRef(); Mix_PlayMusic( mMusic, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 ); Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME ); // Mix_SetPanning } } ~SDLMusicChannel() { mSound->DecRef(); } void CheckDone() { if (mPlaying && (sDoneMusic || (sUsedMusic!=this)) ) { mPlaying = false; if (sUsedMusic == this) { sUsedMusic = 0; sDoneMusic = false; } DecRef(); } } bool isComplete() { CheckDone(); return !mPlaying; } double getLeft() { return 1; } double getRight() { return 1; } double getPosition() { return 1; } void stop() { if (mMusic) Mix_HaltMusic(); } void setTransform(const SoundTransform &inTransform) { if (mMusic>=0) Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME ); } bool mPlaying; Object *mSound; Mix_Music *mMusic; }; class SDLMusic : public Sound { public: SDLMusic(const std::string &inFilename) { IncRef(); #ifdef HX_MACOS char name[1024]; GetBundleFilename(inFilename.c_str(),name,1024); #else const char *name = inFilename.c_str(); #endif mMusic = Mix_LoadMUS(name); if ( mMusic == NULL ) { mError = SDL_GetError(); printf("Error %s (%s)\n", mError.c_str(), name ); } } ~SDLMusic() { if (mMusic) Mix_FreeMusic( mMusic ); } double getLength() { if (mMusic==0) return 0; // TODO: return 60000; } // Will return with one ref... SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform) { if (!mMusic) return 0; return new SDLMusicChannel(this,mMusic,startTime, loops,inTransform); } int getBytesLoaded() { return mMusic ? 100 : 0; } int getBytesTotal() { return mMusic ? 100 : 0; } bool ok() { return mMusic; } std::string getError() { return mError; } std::string mError; Mix_Music *mMusic; }; // --- External Interface ----------------------------------------------------------- Sound *Sound::Create(const std::string &inFilename,bool inForceMusic) { if (!Init()) return 0; Sound *sound = inForceMusic ? 0 : new SDLSound(inFilename); if (!sound || !sound->ok()) { if (sound) sound->DecRef(); sound = new SDLMusic(inFilename); } return sound; } } <commit_msg>Fix windows compile<commit_after>#include <Sound.h> #include <Display.h> #include <SDL.h> #include <SDL_mixer.h> #include <hx/Thread.h> namespace nme { bool gSDLIsInit = false; class SDLSoundChannel; bool sChannelsInit = false; enum { sMaxChannels = 8 }; bool sUsedChannel[sMaxChannels]; bool sDoneChannel[sMaxChannels]; void *sUsedMusic = 0; bool sDoneMusic = false; unsigned int sSoundPos = 0; void onChannelDone(int inChannel) { if (sUsedChannel[inChannel]) sDoneChannel[inChannel] = true; } void onMusicDone() { if (sUsedMusic) sDoneMusic = true; } void onPostMix(void *udata, Uint8 *stream, int len) { sSoundPos += len; } static bool Init() { if (!gSDLIsInit) { fprintf(stderr,"Please init Stage before creating sound.\n"); return false; } if (!sChannelsInit) { sChannelsInit = true; for(int i=0;i<sMaxChannels;i++) { sUsedChannel[i] = false; sDoneChannel[i] = false; } Mix_ChannelFinished(onChannelDone); Mix_HookMusicFinished(onMusicDone); Mix_SetPostMix(onPostMix,0); } return sChannelsInit; } // --- Using "Mix_Chunk" API ---------------------------------------------------- class SDLSoundChannel : public SoundChannel { enum { BUF_SIZE = 16384 }; public: SDLSoundChannel(Object *inSound, Mix_Chunk *inChunk, double inStartTime, int inLoops, const SoundTransform &inTransform) { mChunk = inChunk; mDynamicBuffer = 0; mSound = inSound; mSound->IncRef(); mChannel = -1; // Allocate myself a channel if (mChunk) { for(int i=0;i<sMaxChannels;i++) if (!sUsedChannel[i]) { IncRef(); sDoneChannel[i] = false; sUsedChannel[i] = true; mChannel = i; break; } } if (mChannel>=0) { Mix_PlayChannel( mChannel , mChunk, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 ); Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); // Mix_SetPanning } } SDLSoundChannel(const ByteArray &inBytes, const SoundTransform &inTransform) { mChunk = 0; mDynamicBuffer = new short[BUF_SIZE]; memset(mDynamicBuffer,0,BUF_SIZE*sizeof(short)); mSound = 0; mChannel = -1; mDynamicChunk.allocated = 0; mDynamicChunk.abuf = (Uint8 *)mDynamicBuffer; mDynamicChunk.alen = BUF_SIZE; mDynamicChunk.volume = MIX_MAX_VOLUME; mDynamicChunk.length_ticks = 0; mDynamicFillPos = 0; mDynamicStartPos = 0; mDynamicDataDue = 0; Mix_QuerySpec(&mFrequency, &mFormat, &mChannels); // Allocate myself a channel for(int i=0;i<sMaxChannels;i++) if (!sUsedChannel[i]) { IncRef(); sDoneChannel[i] = false; sUsedChannel[i] = true; mChannel = i; break; } if (mChannel>=0) { FillBuffer(inBytes); // Just once ... if (mDynamicFillPos<2048) { mDynamicDone = true; mDynamicChunk.alen = mDynamicFillPos; Mix_PlayChannel( mChannel , &mDynamicChunk, 0 ); } else { mDynamicDone = false; Mix_PlayChannel( mChannel , &mDynamicChunk, -1 ); // TODO: Lock? mDynamicStartPos = sSoundPos; } Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); } } void FillBuffer(const ByteArray &inBytes) { int floats = inBytes.Size()/sizeof(float); const float *buffer = (const float *)inBytes.Bytes(); int pos = mDynamicFillPos & (BUF_SIZE-1); mDynamicFillPos += floats; int first = BUF_SIZE-pos; if (floats<first) first = floats; for(int i=0;i<first;i++) mDynamicBuffer[pos+i] = *buffer++ * 16385; if (first<floats) { floats -= first; for(int i=0;i<floats;i++) mDynamicBuffer[i] = *buffer++ * 16385; } } ~SDLSoundChannel() { delete [] mDynamicBuffer; if (mSound) mSound->DecRef(); } void CheckDone() { if (mChannel>=0 && sDoneChannel[mChannel]) { sDoneChannel[mChannel] = false; int c = mChannel; mChannel = -1; DecRef(); sUsedChannel[c] = 0; } } bool isComplete() { CheckDone(); return mChannel < 0; } double getLeft() { return 1; } double getRight() { return 1; } double getPosition() { return 1; } void stop() { if (mChannel>=0) Mix_HaltChannel(mChannel); } void setTransform(const SoundTransform &inTransform) { if (mChannel>=0) Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME ); } double getDataPosition() { return (sSoundPos-mDynamicStartPos)*1000.0/mFrequency; } bool needsData() { if (!mDynamicBuffer || mDynamicDone) return false; if (mDynamicDataDue<=sSoundPos) { mDynamicDone = true; return true; } return false; } void addData(const ByteArray &inBytes) { mDynamicDone = false; mDynamicDataDue = mDynamicFillPos + mDynamicStartPos; FillBuffer(inBytes); } Object *mSound; Mix_Chunk *mChunk; int mChannel; Mix_Chunk mDynamicChunk; short *mDynamicBuffer; unsigned int mDynamicFillPos; unsigned int mDynamicStartPos; unsigned int mDynamicDataDue; bool mDynamicDone; int mFrequency; Uint16 mFormat; int mChannels; }; SoundChannel *SoundChannel::Create(const ByteArray &inBytes,const SoundTransform &inTransform) { return new SDLSoundChannel(inBytes,inTransform); } class SDLSound : public Sound { public: SDLSound(const std::string &inFilename) { IncRef(); #ifdef HX_MACOS char name[1024]; GetBundleFilename(inFilename.c_str(),name,1024); #else const char *name = inFilename.c_str(); #endif mChunk = Mix_LoadWAV(name); if ( mChunk == NULL ) { mError = SDL_GetError(); // printf("Error %s (%s)\n", mError.c_str(), name ); } } ~SDLSound() { if (mChunk) Mix_FreeChunk( mChunk ); } double getLength() { if (mChunk==0) return 0; #if defined(DYNAMIC_SDL) || defined(WEBOS) // ? return 0.0; #else return 0.0; //return mChunk->length_ticks; #endif } // Will return with one ref... SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform) { if (!mChunk) return 0; return new SDLSoundChannel(this,mChunk,startTime, loops,inTransform); } int getBytesLoaded() { return mChunk ? mChunk->alen : 0; } int getBytesTotal() { return mChunk ? mChunk->alen : 0; } bool ok() { return mChunk; } std::string getError() { return mError; } std::string mError; Mix_Chunk *mChunk; }; // --- Using "Mix_Music" API ---------------------------------------------------- class SDLMusicChannel : public SoundChannel { public: SDLMusicChannel(Object *inSound, Mix_Music *inMusic, double inStartTime, int inLoops, const SoundTransform &inTransform) { mMusic = inMusic; mSound = inSound; mSound->IncRef(); mPlaying = false; if (mMusic) { mPlaying = true; sUsedMusic = this; sDoneMusic = false; IncRef(); Mix_PlayMusic( mMusic, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 ); Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME ); // Mix_SetPanning } } ~SDLMusicChannel() { mSound->DecRef(); } void CheckDone() { if (mPlaying && (sDoneMusic || (sUsedMusic!=this)) ) { mPlaying = false; if (sUsedMusic == this) { sUsedMusic = 0; sDoneMusic = false; } DecRef(); } } bool isComplete() { CheckDone(); return !mPlaying; } double getLeft() { return 1; } double getRight() { return 1; } double getPosition() { return 1; } void stop() { if (mMusic) Mix_HaltMusic(); } void setTransform(const SoundTransform &inTransform) { if (mMusic>=0) Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME ); } bool mPlaying; Object *mSound; Mix_Music *mMusic; }; class SDLMusic : public Sound { public: SDLMusic(const std::string &inFilename) { IncRef(); #ifdef HX_MACOS char name[1024]; GetBundleFilename(inFilename.c_str(),name,1024); #else const char *name = inFilename.c_str(); #endif mMusic = Mix_LoadMUS(name); if ( mMusic == NULL ) { mError = SDL_GetError(); printf("Error %s (%s)\n", mError.c_str(), name ); } } ~SDLMusic() { if (mMusic) Mix_FreeMusic( mMusic ); } double getLength() { if (mMusic==0) return 0; // TODO: return 60000; } // Will return with one ref... SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform) { if (!mMusic) return 0; return new SDLMusicChannel(this,mMusic,startTime, loops,inTransform); } int getBytesLoaded() { return mMusic ? 100 : 0; } int getBytesTotal() { return mMusic ? 100 : 0; } bool ok() { return mMusic; } std::string getError() { return mError; } std::string mError; Mix_Music *mMusic; }; // --- External Interface ----------------------------------------------------------- Sound *Sound::Create(const std::string &inFilename,bool inForceMusic) { if (!Init()) return 0; Sound *sound = inForceMusic ? 0 : new SDLSound(inFilename); if (!sound || !sound->ok()) { if (sound) sound->DecRef(); sound = new SDLMusic(inFilename); } return sound; } } <|endoftext|>
<commit_before>#include <julia.h> #include "rvalue.h" #include "Values.h" using namespace std; jl_value_t *rPrimitive(const nj::Primitive &prim) { jl_value_t *res = 0; switch(prim.type()->getId()) { case nj::null_type: res = (jl_value_t*)jl_null; break; case nj::boolean_type: { const nj::Boolean &v = static_cast<const nj::Boolean&>(prim); if(v.val()) res = jl_true; else res = jl_false; } break; case nj::char_type: { const nj::Char &v = static_cast<const nj::Char&>(prim); res = jl_box_char(v.val()); } break; case nj::int64_type: { const nj::Int64 &v = static_cast<const nj::Int64&>(prim); res = jl_box_int64(v.val()); } break; case nj::int32_type: { const nj::Int32 &v = static_cast<const nj::Int32&>(prim); res = jl_box_int32(v.val()); } break; case nj::int16_type: { const nj::Int16 &v = static_cast<const nj::Int16&>(prim); res = jl_box_int16(v.val()); } break; case nj::uint64_type: { const nj::UInt64 &v = static_cast<const nj::UInt64&>(prim); res = jl_box_uint64(v.val()); } break; case nj::uint32_type: { const nj::UInt32 &v = static_cast<const nj::UInt32&>(prim); res = jl_box_uint32(v.val()); } break; case nj::uint16_type: { const nj::UInt16 &v = static_cast<const nj::UInt16&>(prim); res = jl_box_uint16(v.val()); } break; case nj::uchar_type: { const nj::UChar &v = static_cast<const nj::UChar&>(prim); res = jl_box_uint8(v.val()); } break; case nj::float64_type: { const nj::Float64 &v = static_cast<const nj::Float64&>(prim); res = jl_box_float64(v.val()); } break; case nj::float32_type: { const nj::Float32 &v = static_cast<const nj::Float32&>(prim); res = jl_box_float32(v.val()); } break; case nj::string_type: { const nj::String &v = static_cast<const nj::String&>(prim); res = jl_cstr_to_string(v.val().c_str()); } break; } return res; } template<typename V,typename E> jl_array_t *rArray(const shared_ptr<nj::Value> &array,jl_datatype_t *jl_element_type) { const nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*array); jl_value_t *jl_atype = jl_apply_array_type(jl_element_type,a.dims().size()); jl_tuple_t *dims = jl_alloc_tuple(a.dims().size()); int i = 0; for(size_t dim: a.dims()) jl_tupleset(dims,i++,dim); return jl_ptr_to_array(jl_atype,a.ptr(),dims,0); } jl_array_t *rArray(const shared_ptr<nj::Value> &array) { jl_array_t *res = 0; const nj::Array_t *atype = static_cast<const nj::Array_t*>(array->type()); switch(atype->etype()->getId()) { case nj::boolean_type: res = rArray<bool,nj::Boolean_t>(array,jl_bool_type); break; case nj::int64_type: res = rArray<int64_t,nj::Int64_t>(array,jl_int64_type); break; case nj::int32_type: res = rArray<int,nj::Int32_t>(array,jl_int32_type); break; case nj::int16_type: res = rArray<short,nj::Int16_t>(array,jl_int16_type); break; case nj::uint64_type: res = rArray<uint64_t,nj::UInt64_t>(array,jl_uint64_type); break; case nj::uint32_type: res = rArray<unsigned int,nj::UInt32_t>(array,jl_uint32_type); break; case nj::uint16_type: res = rArray<unsigned short,nj::UInt16_t>(array,jl_uint16_type); break; case nj::float64_type: res = rArray<double,nj::Float64_t>(array,jl_float64_type); break; case nj::float32_type: res = rArray<float,nj::Float32_t>(array,jl_float32_type); break; case nj::char_type: res = rArray<char,nj::Char_t>(array,jl_int8_type); break; case nj::uchar_type: res = rArray<unsigned char,nj::UChar_t>(array,jl_uint8_type); break; } return res; } jl_value_t *rvalue(const shared_ptr<nj::Value> &value) { if(value->isPrimitive()) { const nj::Primitive &p = static_cast<const nj::Primitive&>(*value); return rPrimitive(p); } else return (jl_value_t*)rArray(value); } <commit_msg>Changed linkage, namespace inclusion of rvalue<commit_after>#include <julia.h> #include "rvalue.h" #include "Values.h" using namespace std; static jl_value_t *rPrimitive(const nj::Primitive &prim) { jl_value_t *res = 0; switch(prim.type()->getId()) { case nj::null_type: res = (jl_value_t*)jl_null; break; case nj::boolean_type: { const nj::Boolean &v = static_cast<const nj::Boolean&>(prim); if(v.val()) res = jl_true; else res = jl_false; } break; case nj::char_type: { const nj::Char &v = static_cast<const nj::Char&>(prim); res = jl_box_char(v.val()); } break; case nj::int64_type: { const nj::Int64 &v = static_cast<const nj::Int64&>(prim); res = jl_box_int64(v.val()); } break; case nj::int32_type: { const nj::Int32 &v = static_cast<const nj::Int32&>(prim); res = jl_box_int32(v.val()); } break; case nj::int16_type: { const nj::Int16 &v = static_cast<const nj::Int16&>(prim); res = jl_box_int16(v.val()); } break; case nj::uint64_type: { const nj::UInt64 &v = static_cast<const nj::UInt64&>(prim); res = jl_box_uint64(v.val()); } break; case nj::uint32_type: { const nj::UInt32 &v = static_cast<const nj::UInt32&>(prim); res = jl_box_uint32(v.val()); } break; case nj::uint16_type: { const nj::UInt16 &v = static_cast<const nj::UInt16&>(prim); res = jl_box_uint16(v.val()); } break; case nj::uchar_type: { const nj::UChar &v = static_cast<const nj::UChar&>(prim); res = jl_box_uint8(v.val()); } break; case nj::float64_type: { const nj::Float64 &v = static_cast<const nj::Float64&>(prim); res = jl_box_float64(v.val()); } break; case nj::float32_type: { const nj::Float32 &v = static_cast<const nj::Float32&>(prim); res = jl_box_float32(v.val()); } break; case nj::string_type: { const nj::String &v = static_cast<const nj::String&>(prim); res = jl_cstr_to_string(v.val().c_str()); } break; } return res; } template<typename V,typename E> static jl_array_t *rArray(const shared_ptr<nj::Value> &array,jl_datatype_t *jl_element_type) { const nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*array); jl_value_t *jl_atype = jl_apply_array_type(jl_element_type,a.dims().size()); jl_tuple_t *dims = jl_alloc_tuple(a.dims().size()); int i = 0; for(size_t dim: a.dims()) jl_tupleset(dims,i++,dim); return jl_ptr_to_array(jl_atype,a.ptr(),dims,0); } static jl_array_t *rArray(const shared_ptr<nj::Value> &array) { jl_array_t *res = 0; const nj::Array_t *atype = static_cast<const nj::Array_t*>(array->type()); switch(atype->etype()->getId()) { case nj::boolean_type: res = rArray<bool,nj::Boolean_t>(array,jl_bool_type); break; case nj::int64_type: res = rArray<int64_t,nj::Int64_t>(array,jl_int64_type); break; case nj::int32_type: res = rArray<int,nj::Int32_t>(array,jl_int32_type); break; case nj::int16_type: res = rArray<short,nj::Int16_t>(array,jl_int16_type); break; case nj::uint64_type: res = rArray<uint64_t,nj::UInt64_t>(array,jl_uint64_type); break; case nj::uint32_type: res = rArray<unsigned int,nj::UInt32_t>(array,jl_uint32_type); break; case nj::uint16_type: res = rArray<unsigned short,nj::UInt16_t>(array,jl_uint16_type); break; case nj::float64_type: res = rArray<double,nj::Float64_t>(array,jl_float64_type); break; case nj::float32_type: res = rArray<float,nj::Float32_t>(array,jl_float32_type); break; case nj::char_type: res = rArray<char,nj::Char_t>(array,jl_int8_type); break; case nj::uchar_type: res = rArray<unsigned char,nj::UChar_t>(array,jl_uint8_type); break; } return res; } jl_value_t *nj::rvalue(const shared_ptr<nj::Value> &value) { if(value->isPrimitive()) { const nj::Primitive &p = static_cast<const nj::Primitive&>(*value); return rPrimitive(p); } else return (jl_value_t*)rArray(value); } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 <Urho3D/IO/File.h> #include <Urho3D/IO/Log.h> #include "GenerateClassWrappers.h" #include "GeneratorContext.h" namespace Urho3D { void GenerateClassWrappers::Start() { printer_ << "#pragma once"; printer_ << "#include <Urho3D/Urho3DAll.h>"; printer_ << ""; printer_ << "namespace Wrappers"; printer_ << "{"; } bool GenerateClassWrappers::Visit(MetaEntity* entity, cppast::visitor_info info) { if (entity->ast_ == nullptr) return true; if (entity->ast_->kind() != cppast::cpp_entity_kind::class_t) return true; // Visit only once if (info.event == info.container_entity_exit) return true; // Class is not supposed to be inherited if (generator->final_.Contains(entity->uniqueName_)) return true; const auto& cls = entity->Ast<cppast::cpp_class>(); if (!HasVirtual(cls) && !HasProtected(cls)) { // Skip children for classes that do not have virtual or protected members return info.event != info.container_entity_enter; } printer_ << fmt("class URHO3D_EXPORT_API {{name}} : public {{symbol}}", { {"name", entity->name_}, {"symbol", entity->uniqueName_}, }); printer_.Indent(); // Urho3D-specific if (IsSubclassOf(cls, "Urho3D::Object")) { printer_ << fmt("URHO3D_OBJECT({{name}}, {{symbol_name}});", {{"name", entity->name_}, {"symbol_name", entity->uniqueName_}}); } printer_.WriteLine("public:", false); // Wrap constructors for (const auto& e : entity->children_) { if (e->kind_ == cppast::cpp_entity_kind::constructor_t) { const auto& ctor = e->Ast<cppast::cpp_constructor>(); printer_ << fmt("{{name}}({{parameter_list}}) : {{symbol_name}}({{parameter_name_list}}) { }", {{"name", entity->name_}, {"symbol_name", entity->uniqueName_}, {"parameter_list", ParameterList(ctor.parameters())}, {"parameter_name_list", ParameterNameList(ctor.parameters())},}); } } printer_ << fmt("virtual ~{{name}}() = default;", {{"name", entity->name_}}); std::vector<std::string> wrappedList; auto implementWrapperClassMembers = [&](const MetaEntity* cls) { for (const auto& child : cls->children_) { if (child->kind_ == cppast::cpp_entity_kind::member_variable_t && child->access_ == cppast::cpp_protected) { // Getters and setters for protected class variables. const auto& var = child->Ast<cppast::cpp_member_variable>(); const auto& type = var.type(); // Avoid returning non-builtin complex types as by copy bool wouldReturnByCopy = type.kind() != cppast::cpp_type_kind::pointer_t && type.kind() != cppast::cpp_type_kind::reference_t && type.kind() != cppast::cpp_type_kind::builtin_t; auto vars = fmt({ {"name", child->name_}, {"type", cppast::to_string(type)}, {"ref", wouldReturnByCopy ? "&" : ""} }); printer_ << fmt("{{type}}{{ref}} __get_{{name}}() { return {{name}}; }", vars); printer_ << fmt("void __set_{{name}}({{type}} value) { {{name}} = value; }", vars); } else if (child->kind_ == cppast::cpp_entity_kind::member_function_t) { const auto& func = child->Ast<cppast::cpp_member_function>(); auto methodId = func.name() + func.signature(); if (std::find(wrappedList.begin(), wrappedList.end(), methodId) == wrappedList.end()) { wrappedList.emplace_back(methodId); // Function pointer that virtual method will call const auto& cls = child->parent_; auto vars = fmt({ {"type", cppast::to_string(func.return_type())}, {"name", child->name_}, {"class_name", entity->name_}, {"full_class_name", entity->uniqueName_}, {"parameter_list", ParameterList(func.parameters())}, {"parameter_name_list", ParameterNameList(func.parameters())}, {"return", IsVoid(func.return_type()) ? "" : "return"}, {"const", cppast::is_const(func.cv_qualifier()) ? "const " : ""}, {"has_params", Count(func.parameters()) > 0}, {"symbol_name", Sanitize(child->uniqueName_)} }); if (func.is_virtual()) { printer_ << fmt("{{type}}(*fn{{symbol_name}})({{class_name}} {{const}}*{{#has_params}}, {{/has_params}}{{parameter_list}}) = nullptr;", vars); // Virtual method that calls said pointer printer_ << fmt("{{type}} {{name}}({{parameter_list}}) {{const}}override", vars); printer_.Indent(); { printer_ << fmt("if (fn{{symbol_name}} == nullptr)", vars); printer_.Indent(); { printer_ << fmt("{{full_class_name}}::{{name}}({{parameter_name_list}});", vars); } printer_.Dedent(); printer_ << "else"; printer_.Indent(); { printer_ << fmt("{{return}}(fn{{symbol_name}})(this{{#has_params}}, {{/has_params}}{{parameter_name_list}});", vars); } printer_.Dedent(); } printer_.Dedent(); } else if (child->access_ == cppast::cpp_protected) // Protected virtuals are not exposed, no point { printer_ << fmt("{{type}} __public_{{name}}({{parameter_list}})", vars); printer_.Indent(); printer_ << fmt("{{name}}({{parameter_name_list}});", vars); printer_.Dedent(); } } } } }; std::function<void(MetaEntity*)> implementBaseWrapperClassMembers = [&](MetaEntity* cls) { const auto& astCls = cls->Ast<cppast::cpp_class>(); for (const auto& base : astCls.bases()) { if (base.access_specifier() == cppast::cpp_private) continue; auto* parentCls = GetEntity(base.type()); if (parentCls != nullptr) { auto* baseOverlay = static_cast<MetaEntity*>(parentCls->user_data()); implementWrapperClassMembers(baseOverlay); implementBaseWrapperClassMembers(baseOverlay); } else URHO3D_LOGWARNINGF("Base class %s not found!", base.name().c_str()); } }; implementWrapperClassMembers(entity); implementBaseWrapperClassMembers(entity); printer_.Dedent("};"); printer_ << ""; entity->sourceName_ = "Wrappers::" + entity->name_; // Wrap a wrapper class return true; } void GenerateClassWrappers::Stop() { printer_ << "}"; // namespace Wrappers File file(context_, GetSubsystem<GeneratorContext>()->outputDirCpp_ + "ClassWrappers.hpp", FILE_WRITE); if (!file.IsOpen()) { URHO3D_LOGERROR("Failed saving ClassWrappers.hpp"); return; } file.WriteLine(printer_.Get()); file.Close(); } } <commit_msg>Convert GenerateClassWrappersPass to use fmt lib.<commit_after>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 <fmt/format.h> #include <Urho3D/IO/File.h> #include <Urho3D/IO/Log.h> #include "GenerateClassWrappers.h" #include "GeneratorContext.h" namespace Urho3D { void GenerateClassWrappers::Start() { printer_ << "#pragma once"; printer_ << "#include <Urho3D/Urho3DAll.h>"; printer_ << ""; printer_ << "namespace Wrappers"; printer_ << "{"; } bool GenerateClassWrappers::Visit(MetaEntity* entity, cppast::visitor_info info) { if (entity->ast_ == nullptr) return true; if (entity->ast_->kind() != cppast::cpp_entity_kind::class_t) return true; // Visit only once if (info.event == info.container_entity_exit) return true; // Class is not supposed to be inherited if (generator->final_.Contains(entity->uniqueName_)) return true; const auto& cls = entity->Ast<cppast::cpp_class>(); if (!HasVirtual(cls) && !HasProtected(cls)) { // Skip children for classes that do not have virtual or protected members return info.event != info.container_entity_enter; } printer_ << fmt::format("class URHO3D_EXPORT_API {} : public {}", entity->name_, entity->uniqueName_); printer_.Indent(); // Urho3D-specific if (IsSubclassOf(cls, "Urho3D::Object")) printer_ << fmt::format("URHO3D_OBJECT({}, {});", entity->name_, entity->uniqueName_); printer_.WriteLine("public:", false); // Wrap constructors for (const auto& e : entity->children_) { if (e->kind_ == cppast::cpp_entity_kind::constructor_t) { const auto& ctor = e->Ast<cppast::cpp_constructor>(); printer_ << fmt::format("{}({}) : {}({}) {{ }}", entity->name_, ParameterList(ctor.parameters()), entity->uniqueName_, ParameterNameList(ctor.parameters())); } } printer_ << fmt::format("virtual ~{}() = default;", entity->name_); std::vector<std::string> wrappedList; auto implementWrapperClassMembers = [&](const MetaEntity* cls) { for (const auto& child : cls->children_) { if (child->kind_ == cppast::cpp_entity_kind::member_variable_t && child->access_ == cppast::cpp_protected) { // Getters and setters for protected class variables. const auto& var = child->Ast<cppast::cpp_member_variable>(); const auto& type = var.type(); // Avoid returning non-builtin complex types as by copy bool wouldReturnByCopy = type.kind() != cppast::cpp_type_kind::pointer_t && type.kind() != cppast::cpp_type_kind::reference_t && type.kind() != cppast::cpp_type_kind::builtin_t; auto name = child->name_; auto typeName = cppast::to_string(type); auto ref = wouldReturnByCopy ? "&" : ""; printer_ << fmt::format("{typeName}{ref} __get_{name}() {{ return {name}; }}", FMT_CAPTURE(name), FMT_CAPTURE(typeName), FMT_CAPTURE(ref)); printer_ << fmt::format("void __set_{name}({typeName} value) {{ {name} = value; }}", FMT_CAPTURE(name), FMT_CAPTURE(typeName), FMT_CAPTURE(ref)); } else if (child->kind_ == cppast::cpp_entity_kind::member_function_t) { const auto& func = child->Ast<cppast::cpp_member_function>(); auto methodId = func.name() + func.signature(); if (std::find(wrappedList.begin(), wrappedList.end(), methodId) == wrappedList.end()) { wrappedList.emplace_back(methodId); // Function pointer that virtual method will call const auto& cls = child->parent_; auto typeName = cppast::to_string(func.return_type()); auto name = child->name_; auto parameterList = ParameterList(func.parameters()); auto parameterNameList = ParameterNameList(func.parameters()); auto constModifier = cppast::is_const(func.cv_qualifier()) ? "const " : ""; auto pc = Count(func.parameters()) > 0 ? ", " : ""; auto symbolName = Sanitize(child->uniqueName_); auto fullClassName = entity->uniqueName_; auto className = entity->name_; if (func.is_virtual()) { printer_ << fmt::format("{typeName}(*fn{symbolName})({className} {constModifier}*{pc}{parameterList}) = nullptr;", FMT_CAPTURE(typeName), FMT_CAPTURE(symbolName), FMT_CAPTURE(className), FMT_CAPTURE(constModifier), FMT_CAPTURE(pc), FMT_CAPTURE(parameterList)); // Virtual method that calls said pointer printer_ << fmt::format("{typeName} {name}({parameterList}) {constModifier}override", FMT_CAPTURE(typeName), FMT_CAPTURE(name), FMT_CAPTURE(parameterList), FMT_CAPTURE(constModifier)); printer_.Indent(); { printer_ << fmt::format("if (fn{symbolName} == nullptr)", FMT_CAPTURE(symbolName)); printer_.Indent(); { printer_ << fmt::format("{fullClassName}::{name}({parameterNameList});", FMT_CAPTURE(fullClassName), FMT_CAPTURE(name), FMT_CAPTURE(parameterNameList)); } printer_.Dedent(); printer_ << "else"; printer_.Indent(); { printer_ << (IsVoid(func.return_type()) ? "" : "return ") + fmt::format("(fn{symbolName})(this{pc}{parameterNameList});", FMT_CAPTURE(symbolName), FMT_CAPTURE(pc), FMT_CAPTURE(parameterNameList)); } printer_.Dedent(); } printer_.Dedent(); } else if (child->access_ == cppast::cpp_protected) // Protected virtuals are not exposed, no point { printer_ << fmt::format("{typeName} __public_{name}({parameterList})", FMT_CAPTURE(typeName), FMT_CAPTURE(name), FMT_CAPTURE(parameterList)); printer_.Indent(); printer_ << fmt::format("{name}({parameterNameList});", FMT_CAPTURE(name), FMT_CAPTURE(parameterNameList)); printer_.Dedent(); } } } } }; std::function<void(MetaEntity*)> implementBaseWrapperClassMembers = [&](MetaEntity* cls) { const auto& astCls = cls->Ast<cppast::cpp_class>(); for (const auto& base : astCls.bases()) { if (base.access_specifier() == cppast::cpp_private) continue; auto* parentCls = GetEntity(base.type()); if (parentCls != nullptr) { auto* baseOverlay = static_cast<MetaEntity*>(parentCls->user_data()); implementWrapperClassMembers(baseOverlay); implementBaseWrapperClassMembers(baseOverlay); } else URHO3D_LOGWARNINGF("Base class %s not found!", base.name().c_str()); } }; implementWrapperClassMembers(entity); implementBaseWrapperClassMembers(entity); printer_.Dedent("};"); printer_ << ""; entity->sourceName_ = "Wrappers::" + entity->name_; // Wrap a wrapper class return true; } void GenerateClassWrappers::Stop() { printer_ << "}"; // namespace Wrappers File file(context_, GetSubsystem<GeneratorContext>()->outputDirCpp_ + "ClassWrappers.hpp", FILE_WRITE); if (!file.IsOpen()) { URHO3D_LOGERROR("Failed saving ClassWrappers.hpp"); return; } file.WriteLine(printer_.Get()); file.Close(); } } <|endoftext|>
<commit_before>/******************************************************************************* Yuri V. Krugloff. 2013-2015. http://www.tver-soft.org This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> *******************************************************************************/ #include "Functions.hpp" #include <stdlib.h> #include <string.h> #include <errno.h> #if defined(OS_WINDOWS) #include <io.h> #include <direct.h> #elif defined(OS_LINUX) || defined(OS_MACOS) #include <sys/stat.h> #include <unistd.h> #include <glob.h> #include <limits.h> #endif #include <time.h> #include "Logger.hpp" //------------------------------------------------------------------------------ using namespace std; //------------------------------------------------------------------------------ #ifdef _MSC_VER #define GETCWD _getcwd #define POPEN _popen #define PCLOSE _pclose #else #define GETCWD getcwd #define POPEN popen #define PCLOSE pclose #endif #ifdef OS_WINDOWS #define POPEN_MODE "rt" #else #define POPEN_MODE "r" #endif //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void eraseLastSeparators(string* pStr) { for (int i = static_cast<int>(pStr->size()) - 1; i >= 0; --i) { const char& c = pStr->at(i); if (c == '/' || c == '\\') pStr->erase(i); else break; } } //------------------------------------------------------------------------------ void addLastSeparator(string* pStr) { if (pStr != NULL && !pStr->empty()) { string::const_reverse_iterator Iter = pStr->rbegin(); if (*Iter != '/' && *Iter != '\\') *pStr += Functions::separator(); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Functions::splice(TStringList* pX, TStringList Y) { if (pX != NULL && !Y.empty()) { TStringList::iterator Iter = pX->end(); pX->splice(Iter, Y); } } //------------------------------------------------------------------------------ char Functions::separator() { return '/'; } //------------------------------------------------------------------------------ string Functions::normalizeSeparators(const string &path) { #ifdef OS_WINDOWS string Result = path; for (string::iterator Iter = Result.begin(); Iter != Result.end(); ++Iter) if (*Iter == '\\') *Iter = '/'; return Result; #else return path; #endif } //------------------------------------------------------------------------------ string Functions::trimSeparators(const string& str) { string Result; string::size_type first = 0; for (; first < str.length(); ++first) if (str[first] != '/' && str[first] != '\\') break; Result = str.substr(first); eraseLastSeparators(&Result); return Result; } //------------------------------------------------------------------------------ bool Functions::hasOnlyNormalSeparators(const char* path) { while (*path != '\0') if (*path++ == '\\') return false; return true; } //------------------------------------------------------------------------------ // Replace char in string to new substring. void Functions::replace(string* pS, char before, const char* after) { size_t len = strlen(after); size_t pos = pS->find(before); while (pos != string::npos) { pS->replace(pos, 1, after); pos = pS->find(before, pos + len); } } //------------------------------------------------------------------------------ bool Functions::startsWith(const string& str, const char* start) { return str.compare(0, strlen(start), start) == 0; } //------------------------------------------------------------------------------ string Functions::absolutePath(const string& relativePath) { string Result; #if defined(OS_WINDOWS) char AbsPath[_MAX_PATH]; if (_fullpath(AbsPath, relativePath.c_str(), _MAX_PATH) != NULL) Result = normalizeSeparators(AbsPath); #elif defined(OS_LINUX) || defined(OS_MACOS) char AbsPath[PATH_MAX]; if (realpath(relativePath.c_str(), AbsPath) != NULL) Result = AbsPath; #else #error "Unsupported OS." #endif if (Result.empty()) { LOG_E("Error translate path to absolute. Error %i.\n" " (%s)", errno, relativePath.c_str()); } eraseLastSeparators(&Result); return Result; } //------------------------------------------------------------------------------ string Functions::currentDir() { string Result; char* cwd = GETCWD(NULL, 0); if (cwd != NULL) { Result = cwd; free(cwd); } else { LOG_E("Error getting current directory. Error %i.\n", errno); } eraseLastSeparators(&Result); return normalizeSeparators(Result); } //------------------------------------------------------------------------------ bool Functions::isFileExists(const char* fileName) { #if defined(OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst(fileName, &FindData); if (FindHandle != -1) { _findclose(FindHandle); return true; } #elif defined(OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob(fileName, 0, NULL, &GlobData) == 0) { globfree(&GlobData); return true; } #else #error "Unsupported OS." #endif return false; } //------------------------------------------------------------------------------ // Getting size of opened file. long Functions::getFileSize(FILE* file) { #if defined(OS_WINDOWS) return _filelength(_fileno(file)); #elif defined(OS_LINUX) || defined(OS_MACOS) struct stat Stat; if (fstat(fileno(file), &Stat) == 0) return Stat.st_size; return -1; #else #error "Unsupported OS." #endif } //------------------------------------------------------------------------------ // Truncation file to empty (zero size). bool Functions::zeroFile(FILE* file) { rewind(file); #if defined(OS_WINDOWS) return _chsize(_fileno(file), 0) == 0; #elif defined(OS_LINUX) || defined(OS_MACOS) return ftruncate(fileno(file), 0) == 0; #else #error "Unsupported OS." #endif } //------------------------------------------------------------------------------ bool Functions::renameFile(const char* oldFileName, const char* newFileName) { LOG_V("Renaming file \"%s\"\n" " to \"%s\".\n", oldFileName, newFileName); if (!rename(oldFileName, newFileName) == 0) { LOG_E("Error renaming file \"%s\" to \"%s\". Error %i.\n", oldFileName, newFileName, errno); return false; } return true; } //------------------------------------------------------------------------------ bool Functions::copyFile(const char* fromFileName, const char* toFileName) { LOG_V("Copying file content from \"%s\"\n" " to \"%s\".\n", fromFileName, toFileName); bool Result = true; FILE* src = fopen(fromFileName, "rb"); if (src != NULL) { FILE* dst = fopen(toFileName, "wb"); if (dst != NULL) { char Buffer[1024 * 32]; // 32kb while (!feof(src)) { size_t size = fread(Buffer, 1, sizeof(Buffer), src); if (fwrite(Buffer, 1, size, dst) != size) { LOG_E("Error writing to file \"%s\".\n", toFileName); Result = false; break; } } fclose(dst); if (!Result) removeFile(toFileName); } else { LOG_E("Error opening file \"%s\" for writing.\n", toFileName); Result = false; } fclose(src); } else { LOG_E("Error opening file \"%s\" for reading.\n", fromFileName); Result = false; } return Result; } //------------------------------------------------------------------------------ bool Functions::removeFile(const char* fileName) { if (isFileExists(fileName)) { LOG_V("Removing file \"%s\"...\n", fileName); if (remove(fileName) != 0) { LOG_E("Error removing file \"%s\". Error %i.\n", fileName, errno); return false; } } return true; } //------------------------------------------------------------------------------ string Functions::currentTime(const char* format) { time_t rawTime = time(NULL); struct tm* timeInfo = localtime(&rawTime); const int BufferSize = 1024; char Buffer[BufferSize]; strftime(Buffer, BufferSize, format, timeInfo); return Buffer; } //------------------------------------------------------------------------------ std::string Functions::getProgramOutput(const char* fileName) { string Result; FILE* out; out = POPEN(fileName, POPEN_MODE); if (out != NULL) { char Buffer[1024]; while (fgets(Buffer, sizeof(Buffer), out) != NULL) Result += Buffer; if (ferror(out) != 0) { LOG_E("Error reading from pipe. Error %i.\n", errno); Result.clear(); } if (PCLOSE(out) == -1) LOG_E("Error closing pipe. Error %i.\n", errno); } else { LOG_E("Error running program \"%s\". Error %i.\n", fileName, errno); } return Result; } //------------------------------------------------------------------------------ TStringList Functions::findFiles(string dir, const string& mask) { TStringList Result; addLastSeparator(&dir); #if defined(OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst((dir + mask).c_str(), &FindData); if (FindHandle != -1) { do { if ((FindData.attrib & _A_SUBDIR) == 0) Result.push_back(dir + FindData.name); } while (_findnext(FindHandle, &FindData) == 0); _findclose(FindHandle); } #elif defined(OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob((dir + mask).c_str(), GLOB_MARK, NULL, &GlobData) == 0) { for (size_t i = 0; i < GlobData.gl_pathc; ++i) { const char* path = GlobData.gl_pathv[i]; if (path[strlen(path) - 1] != '/') Result.push_back(path); } globfree(&GlobData); } #else #error "Unsupported OS." #endif return Result; } //------------------------------------------------------------------------------ TStringList Functions::findFilesRecursive(string dir, const string& mask) { TStringList Result; addLastSeparator(&dir); #if defined (OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst((dir + "*").c_str(), &FindData); if (FindHandle != -1) { do { if ((FindData.attrib & _A_SUBDIR) != 0 && strcmp(FindData.name, ".") != 0 && strcmp(FindData.name, "..") != 0) { splice(&Result, findFilesRecursive(dir + FindData.name + "/", mask)); } } while (_findnext(FindHandle, &FindData) == 0); _findclose(FindHandle); } splice(&Result, findFiles(dir, mask)); #elif defined (OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob((dir + mask).c_str(), GLOB_MARK, NULL, &GlobData) == 0) { for (size_t i = 0; i < GlobData.gl_pathc; ++i) { const char* path = GlobData.gl_pathv[i]; if (path[strlen(path) - 1] != '/') Result.push_back(path); else splice(&Result, findFilesRecursive(path, mask)); } } #endif return Result; } //------------------------------------------------------------------------------ string Functions::stringListToStr(const TStringList& list, const string& prefix, const string& suffix) { string Result; for (TStringList::const_iterator Iter = list.begin(); Iter != list.end(); ++Iter) Result += prefix + *Iter + suffix; return Result; } //------------------------------------------------------------------------------ string Functions::stringMapToStr(const TStringMap& map, const string& prefix, const string& separator, const string& suffix) { string Result; for (TStringMap::const_iterator Iter = map.begin(); Iter != map.end(); ++Iter) Result += prefix + Iter->first + separator + Iter->second + suffix; return Result; } //------------------------------------------------------------------------------ <commit_msg>Silent warnings reported by Clang<commit_after>/******************************************************************************* Yuri V. Krugloff. 2013-2015. http://www.tver-soft.org This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> *******************************************************************************/ #include "Functions.hpp" #include <stdlib.h> #include <string.h> #include <errno.h> #if defined(OS_WINDOWS) #include <io.h> #include <direct.h> #elif defined(OS_LINUX) || defined(OS_MACOS) #include <sys/stat.h> #include <unistd.h> #include <glob.h> #include <limits.h> #endif #include <time.h> #include "Logger.hpp" //------------------------------------------------------------------------------ using namespace std; //------------------------------------------------------------------------------ #ifdef _MSC_VER #define GETCWD _getcwd #define POPEN _popen #define PCLOSE _pclose #else #define GETCWD getcwd #define POPEN popen #define PCLOSE pclose #endif #ifdef OS_WINDOWS #define POPEN_MODE "rt" #else #define POPEN_MODE "r" #endif //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void eraseLastSeparators(string* pStr) { for (int i = static_cast<int>(pStr->size()) - 1; i >= 0; --i) { const char& c = pStr->at(i); if (c == '/' || c == '\\') pStr->erase(i); else break; } } //------------------------------------------------------------------------------ void addLastSeparator(string* pStr) { if (pStr != NULL && !pStr->empty()) { string::const_reverse_iterator Iter = pStr->rbegin(); if (*Iter != '/' && *Iter != '\\') *pStr += Functions::separator(); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Functions::splice(TStringList* pX, TStringList Y) { if (pX != NULL && !Y.empty()) { TStringList::iterator Iter = pX->end(); pX->splice(Iter, Y); } } //------------------------------------------------------------------------------ char Functions::separator() { return '/'; } //------------------------------------------------------------------------------ string Functions::normalizeSeparators(const string &path) { #ifdef OS_WINDOWS string Result = path; for (string::iterator Iter = Result.begin(); Iter != Result.end(); ++Iter) if (*Iter == '\\') *Iter = '/'; return Result; #else return path; #endif } //------------------------------------------------------------------------------ string Functions::trimSeparators(const string& str) { string Result; string::size_type first = 0; for (; first < str.length(); ++first) if (str[first] != '/' && str[first] != '\\') break; Result = str.substr(first); eraseLastSeparators(&Result); return Result; } //------------------------------------------------------------------------------ bool Functions::hasOnlyNormalSeparators(const char* path) { while (*path != '\0') if (*path++ == '\\') return false; return true; } //------------------------------------------------------------------------------ // Replace char in string to new substring. void Functions::replace(string* pS, char before, const char* after) { size_t len = strlen(after); size_t pos = pS->find(before); while (pos != string::npos) { pS->replace(pos, 1, after); pos = pS->find(before, pos + len); } } //------------------------------------------------------------------------------ bool Functions::startsWith(const string& str, const char* start) { return str.compare(0, strlen(start), start) == 0; } //------------------------------------------------------------------------------ string Functions::absolutePath(const string& relativePath) { string Result; #if defined(OS_WINDOWS) char AbsPath[_MAX_PATH]; if (_fullpath(AbsPath, relativePath.c_str(), _MAX_PATH) != NULL) Result = normalizeSeparators(AbsPath); #elif defined(OS_LINUX) || defined(OS_MACOS) char AbsPath[PATH_MAX]; if (realpath(relativePath.c_str(), AbsPath) != NULL) Result = AbsPath; #else #error "Unsupported OS." #endif if (Result.empty()) { LOG_E("Error translate path to absolute. Error %i.\n" " (%s)", errno, relativePath.c_str()); } eraseLastSeparators(&Result); return Result; } //------------------------------------------------------------------------------ string Functions::currentDir() { string Result; char* cwd = GETCWD(NULL, 0); if (cwd != NULL) { Result = cwd; free(cwd); } else { LOG_E("Error getting current directory. Error %i.\n", errno); } eraseLastSeparators(&Result); return normalizeSeparators(Result); } //------------------------------------------------------------------------------ bool Functions::isFileExists(const char* fileName) { #if defined(OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst(fileName, &FindData); if (FindHandle != -1) { _findclose(FindHandle); return true; } #elif defined(OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob(fileName, 0, NULL, &GlobData) == 0) { globfree(&GlobData); return true; } #else #error "Unsupported OS." #endif return false; } //------------------------------------------------------------------------------ // Getting size of opened file. long Functions::getFileSize(FILE* file) { #if defined(OS_WINDOWS) return _filelength(_fileno(file)); #elif defined(OS_LINUX) || defined(OS_MACOS) struct stat Stat; if (fstat(fileno(file), &Stat) == 0) return Stat.st_size; return -1; #else #error "Unsupported OS." #endif } //------------------------------------------------------------------------------ // Truncation file to empty (zero size). bool Functions::zeroFile(FILE* file) { rewind(file); #if defined(OS_WINDOWS) return _chsize(_fileno(file), 0) == 0; #elif defined(OS_LINUX) || defined(OS_MACOS) return ftruncate(fileno(file), 0) == 0; #else #error "Unsupported OS." #endif } //------------------------------------------------------------------------------ bool Functions::renameFile(const char* oldFileName, const char* newFileName) { LOG_V("Renaming file \"%s\"\n" " to \"%s\".\n", oldFileName, newFileName); if (rename(oldFileName, newFileName) != 0) { LOG_E("Error renaming file \"%s\" to \"%s\". Error %i.\n", oldFileName, newFileName, errno); return false; } return true; } //------------------------------------------------------------------------------ bool Functions::copyFile(const char* fromFileName, const char* toFileName) { LOG_V("Copying file content from \"%s\"\n" " to \"%s\".\n", fromFileName, toFileName); bool Result = true; FILE* src = fopen(fromFileName, "rb"); if (src != NULL) { FILE* dst = fopen(toFileName, "wb"); if (dst != NULL) { char Buffer[1024 * 32]; // 32kb while (!feof(src)) { size_t size = fread(Buffer, 1, sizeof(Buffer), src); if (fwrite(Buffer, 1, size, dst) != size) { LOG_E("Error writing to file \"%s\".\n", toFileName); Result = false; break; } } fclose(dst); if (!Result) removeFile(toFileName); } else { LOG_E("Error opening file \"%s\" for writing.\n", toFileName); Result = false; } fclose(src); } else { LOG_E("Error opening file \"%s\" for reading.\n", fromFileName); Result = false; } return Result; } //------------------------------------------------------------------------------ bool Functions::removeFile(const char* fileName) { if (isFileExists(fileName)) { LOG_V("Removing file \"%s\"...\n", fileName); if (remove(fileName) != 0) { LOG_E("Error removing file \"%s\". Error %i.\n", fileName, errno); return false; } } return true; } //------------------------------------------------------------------------------ string Functions::currentTime(const char* format) { time_t rawTime = time(NULL); struct tm* timeInfo = localtime(&rawTime); const int BufferSize = 1024; char Buffer[BufferSize]; strftime(Buffer, BufferSize, format, timeInfo); return Buffer; } //------------------------------------------------------------------------------ std::string Functions::getProgramOutput(const char* fileName) { string Result; FILE* out; out = POPEN(fileName, POPEN_MODE); if (out != NULL) { char Buffer[1024]; while (fgets(Buffer, sizeof(Buffer), out) != NULL) Result += Buffer; if (ferror(out) != 0) { LOG_E("Error reading from pipe. Error %i.\n", errno); Result.clear(); } if (PCLOSE(out) == -1) LOG_E("Error closing pipe. Error %i.\n", errno); } else { LOG_E("Error running program \"%s\". Error %i.\n", fileName, errno); } return Result; } //------------------------------------------------------------------------------ TStringList Functions::findFiles(string dir, const string& mask) { TStringList Result; addLastSeparator(&dir); #if defined(OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst((dir + mask).c_str(), &FindData); if (FindHandle != -1) { do { if ((FindData.attrib & _A_SUBDIR) == 0) Result.push_back(dir + FindData.name); } while (_findnext(FindHandle, &FindData) == 0); _findclose(FindHandle); } #elif defined(OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob((dir + mask).c_str(), GLOB_MARK, NULL, &GlobData) == 0) { for (size_t i = 0; i < GlobData.gl_pathc; ++i) { const char* path = GlobData.gl_pathv[i]; if (path[strlen(path) - 1] != '/') Result.push_back(path); } globfree(&GlobData); } #else #error "Unsupported OS." #endif return Result; } //------------------------------------------------------------------------------ TStringList Functions::findFilesRecursive(string dir, const string& mask) { TStringList Result; addLastSeparator(&dir); #if defined (OS_WINDOWS) _finddata_t FindData; intptr_t FindHandle = _findfirst((dir + "*").c_str(), &FindData); if (FindHandle != -1) { do { if ((FindData.attrib & _A_SUBDIR) != 0 && strcmp(FindData.name, ".") != 0 && strcmp(FindData.name, "..") != 0) { splice(&Result, findFilesRecursive(dir + FindData.name + "/", mask)); } } while (_findnext(FindHandle, &FindData) == 0); _findclose(FindHandle); } splice(&Result, findFiles(dir, mask)); #elif defined (OS_LINUX) || defined(OS_MACOS) glob_t GlobData; if (glob((dir + mask).c_str(), GLOB_MARK, NULL, &GlobData) == 0) { for (size_t i = 0; i < GlobData.gl_pathc; ++i) { const char* path = GlobData.gl_pathv[i]; if (path[strlen(path) - 1] != '/') Result.push_back(path); else splice(&Result, findFilesRecursive(path, mask)); } } #endif return Result; } //------------------------------------------------------------------------------ string Functions::stringListToStr(const TStringList& list, const string& prefix, const string& suffix) { string Result; for (TStringList::const_iterator Iter = list.begin(); Iter != list.end(); ++Iter) Result += prefix + *Iter + suffix; return Result; } //------------------------------------------------------------------------------ string Functions::stringMapToStr(const TStringMap& map, const string& prefix, const string& separator, const string& suffix) { string Result; for (TStringMap::const_iterator Iter = map.begin(); Iter != map.end(); ++Iter) Result += prefix + Iter->first + separator + Iter->second + suffix; return Result; } //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>#include "NativeExample.h" #include <iostream> using namespace std; JNIEXPORT void JNICALL Java_NativeExample_callMe (JNIEnv *env, jobject jobj){ std::cout<<"Hello .."<<std::endl; jclass classObject = env->FindClass("Abc"); if(classObject==0){ std::cout<<"couldn't find class"<<std::endl; }else{ std::cout<<"found class"<<std::endl; } // use javap -s Abc to find methog signatures jmethodID constructor = env->GetMethodID(classObject,"<init>","()V"); jobject object = env->NewObject(classObject, constructor); // use javap -s Abc to find methog signatures jmethodID method1Object = env->GetMethodID(classObject,"method1","(I)V"); if(method1Object==0){ std::cout<<"coudn't find method"<<std::endl; }else{ std::cout<<"found method"<<std::endl; } object = env->NewObject(classObject, method1Object,2); } JNIEXPORT void JNICALL Java_NativeExample_printf (JNIEnv *env, jobject job, jstring jstring){ const char *nativeString = env->GetStringUTFChars(jstring,0); std::cout<<nativeString<<std::endl; env->ReleaseStringUTFChars(jstring, nativeString); } <commit_msg>method calls comments<commit_after>#include "NativeExample.h" #include <iostream> using namespace std; JNIEXPORT void JNICALL Java_NativeExample_callMe (JNIEnv *env, jobject jobj){ std::cout<<"Hello .."<<std::endl; jclass classObject = env->FindClass("Abc"); if(classObject==0){ std::cout<<"couldn't find class"<<std::endl; }else{ std::cout<<"found class"<<std::endl; } // use javap -s Abc to find method signatures jmethodID constructor = env->GetMethodID(classObject,"<init>","()V"); jobject object = env->NewObject(classObject, constructor); // use javap -s Abc to find method signatures jmethodID method1Object = env->GetMethodID(classObject,"method1","(I)V"); if(method1Object==0){ std::cout<<"coudn't find method"<<std::endl; }else{ std::cout<<"found method"<<std::endl; } object = env->NewObject(classObject, method1Object,2); } JNIEXPORT void JNICALL Java_NativeExample_printf (JNIEnv *env, jobject job, jstring jstring){ const char *nativeString = env->GetStringUTFChars(jstring,0); std::cout<<nativeString<<std::endl; env->ReleaseStringUTFChars(jstring, nativeString); } <|endoftext|>
<commit_before>/* * This file is part of Playslave-C++. * Playslave-C++ is licenced under MIT License. See LICENSE.txt for more * details. */ #define _POSIX_C_SOURCE 200809 #include <memory> #include <sstream> #include <vector> #include <cstdarg> /* CurrentStateIn */ #include <cstdbool> /* bool */ #include <cstdint> #include <cstdlib> #include <cstring> #include <algorithm> #include <thread> #include <chrono> #ifdef WIN32 struct timespec { time_t tv_sec; long tv_nsec; }; #include <Winsock2.h> #else #include <time.h> /* struct timespec */ #endif #include "cmd.h" /* struct cmd, check_commands */ #include "io.hpp" #include "audio.h" #include "constants.h" #include "messages.h" #include "player.h" Player::Player(const std::string &device) : device(device) { this->current_state = State::EJECTED; this->au = nullptr; this->position_listener = nullptr; this->position_period = std::chrono::microseconds(0); this->position_last = std::chrono::microseconds(0); this->position_last_invalid = true; } bool Player::Eject() { bool valid = CurrentStateIn({State::STOPPED, State::PLAYING}); if (valid) { this->au = nullptr; SetState(State::EJECTED); this->position_last = std::chrono::microseconds(0); } return valid; } bool Player::Play() { bool valid = CurrentStateIn({State::STOPPED}) && (this->au != nullptr); if (valid) { this->au->Start(); SetState(State::PLAYING); } return valid; } bool Player::Quit() { Eject(); SetState(State::QUITTING); return true; // Always a valid command. } bool Player::Stop() { bool valid = CurrentStateIn({State::PLAYING}); if (valid) { this->au->Stop(); SetState(State::STOPPED); } return valid; } bool Player::Load(const std::string &filename) { try { this->au = std::unique_ptr<AudioOutput>( new AudioOutput(filename, this->device)); this->position_last_invalid = true; Debug("Loaded ", filename); SetState(State::STOPPED); } catch (Error &error) { error.ToResponse(); Eject(); } return true; // Always a valid command. } bool Player::Seek(const std::string &time_str) { /* TODO: proper overflow checking */ std::istringstream is(time_str); uint64_t raw_time; std::string rest; is >> raw_time >> rest; std::chrono::microseconds position(0); if (rest == "s" || rest == "sec") { position = std::chrono::duration_cast< std::chrono::microseconds>( std::chrono::seconds(raw_time)); } else { /* Assume microseconds */ position = std::chrono::microseconds(raw_time); } /* Weed out any unwanted states */ bool valid = CurrentStateIn({State::PLAYING, State::STOPPED}); if (valid) { // enum state current_state = this->cstate; // cmd_stop(); // We need the player engine stopped in order to // seek this->au->SeekToPosition(position); this->position_last_invalid = true; // if (current_state == S_PLAY) { // If we were playing before we'd ideally like to resume // cmd_play(); //} } return valid; } State Player::CurrentState() { return this->current_state; } /* Performs an iteration of the player update loop. */ void Player::Update() { if (this->current_state == State::PLAYING) { if (this->au->IsHalted()) { Eject(); } else { SendPositionIfReady(); } } if (CurrentStateIn({State::PLAYING, State::STOPPED})) { bool more = this->au->Update(); if (!more) { Eject(); } } } /* Throws an error if the current state is not in the state set provided by * the initializer_list. */ bool Player::CurrentStateIn(std::initializer_list<State> states) { return std::any_of(states.begin(), states.end(), [this](State state) { return this->current_state == state; }); } /* Sets the player state and honks accordingly. */ void Player::SetState(State state) { State last_state = this->current_state; this->current_state = state; if (this->state_listener != nullptr) { this->state_listener(last_state, state); } } /** * Registers a listener for state changes. * @param listener The function to which state change signals shall be sent. */ void Player::RegisterStateListener(StateListener listener) { this->state_listener = listener; } /** * Sends a position signal to the outside environment, if ready to send one. * This only sends a signal if the requested amount of time has passed since the * last one. * It requires a handler to have been registered via SetTimeSignalHandler. */ void Player::SendPositionIfReady() { auto position = this->au->CurrentPosition<std::chrono::microseconds>(); if (IsReadyToSendPosition(position)) { this->position_listener(position); this->position_last = position; this->position_last_invalid = false; } } /** * Figures out whether it's time to send a position signal. * @param current_position The current position in the song. * @return True if enough time has elapsed for a signal to be sent; false * otherwise. */ bool Player::IsReadyToSendPosition(std::chrono::microseconds current_position) { bool ready = false; if (this->position_last_invalid) { ready = true; } else if (this->position_listener != nullptr) { auto difference = current_position - this->position_last; ready = difference >= this->position_period; } return ready; } /** * Registers a listener for position signals. * @param listener The function to which position signals shall be sent. * @param period_usecs The approximate period, in microseconds, between position * signals. */ void Player::RegisterPositionListener(PositionListener listener, const std::chrono::microseconds period) { this->position_listener = listener; this->position_period = period; } <commit_msg>Don't attempt to load with an empty filename<commit_after>/* * This file is part of Playslave-C++. * Playslave-C++ is licenced under MIT License. See LICENSE.txt for more * details. */ #define _POSIX_C_SOURCE 200809 #include <memory> #include <sstream> #include <vector> #include <cstdarg> /* CurrentStateIn */ #include <cstdbool> /* bool */ #include <cstdint> #include <cstdlib> #include <cstring> #include <algorithm> #include <thread> #include <chrono> #ifdef WIN32 struct timespec { time_t tv_sec; long tv_nsec; }; #include <Winsock2.h> #else #include <time.h> /* struct timespec */ #endif #include "cmd.h" /* struct cmd, check_commands */ #include "io.hpp" #include "audio.h" #include "constants.h" #include "messages.h" #include "player.h" Player::Player(const std::string &device) : device(device) { this->current_state = State::EJECTED; this->au = nullptr; this->position_listener = nullptr; this->position_period = std::chrono::microseconds(0); this->position_last = std::chrono::microseconds(0); this->position_last_invalid = true; } bool Player::Eject() { bool valid = CurrentStateIn({State::STOPPED, State::PLAYING}); if (valid) { this->au = nullptr; SetState(State::EJECTED); this->position_last = std::chrono::microseconds(0); } return valid; } bool Player::Play() { bool valid = CurrentStateIn({State::STOPPED}) && (this->au != nullptr); if (valid) { this->au->Start(); SetState(State::PLAYING); } return valid; } bool Player::Quit() { Eject(); SetState(State::QUITTING); return true; // Always a valid command. } bool Player::Stop() { bool valid = CurrentStateIn({State::PLAYING}); if (valid) { this->au->Stop(); SetState(State::STOPPED); } return valid; } bool Player::Load(const std::string &filename) { if (filename.length() == 0) return false; try { this->au = std::unique_ptr<AudioOutput>( new AudioOutput(filename, this->device)); this->position_last_invalid = true; Debug("Loaded ", filename); SetState(State::STOPPED); } catch (Error &error) { error.ToResponse(); Eject(); } return true; // Always a valid command. } bool Player::Seek(const std::string &time_str) { /* TODO: proper overflow checking */ std::istringstream is(time_str); uint64_t raw_time; std::string rest; is >> raw_time >> rest; std::chrono::microseconds position(0); if (rest == "s" || rest == "sec") { position = std::chrono::duration_cast< std::chrono::microseconds>( std::chrono::seconds(raw_time)); } else { /* Assume microseconds */ position = std::chrono::microseconds(raw_time); } /* Weed out any unwanted states */ bool valid = CurrentStateIn({State::PLAYING, State::STOPPED}); if (valid) { // enum state current_state = this->cstate; // cmd_stop(); // We need the player engine stopped in order to // seek this->au->SeekToPosition(position); this->position_last_invalid = true; // if (current_state == S_PLAY) { // If we were playing before we'd ideally like to resume // cmd_play(); //} } return valid; } State Player::CurrentState() { return this->current_state; } /* Performs an iteration of the player update loop. */ void Player::Update() { if (this->current_state == State::PLAYING) { if (this->au->IsHalted()) { Eject(); } else { SendPositionIfReady(); } } if (CurrentStateIn({State::PLAYING, State::STOPPED})) { bool more = this->au->Update(); if (!more) { Eject(); } } } /* Throws an error if the current state is not in the state set provided by * the initializer_list. */ bool Player::CurrentStateIn(std::initializer_list<State> states) { return std::any_of(states.begin(), states.end(), [this](State state) { return this->current_state == state; }); } /* Sets the player state and honks accordingly. */ void Player::SetState(State state) { State last_state = this->current_state; this->current_state = state; if (this->state_listener != nullptr) { this->state_listener(last_state, state); } } /** * Registers a listener for state changes. * @param listener The function to which state change signals shall be sent. */ void Player::RegisterStateListener(StateListener listener) { this->state_listener = listener; } /** * Sends a position signal to the outside environment, if ready to send one. * This only sends a signal if the requested amount of time has passed since the * last one. * It requires a handler to have been registered via SetTimeSignalHandler. */ void Player::SendPositionIfReady() { auto position = this->au->CurrentPosition<std::chrono::microseconds>(); if (IsReadyToSendPosition(position)) { this->position_listener(position); this->position_last = position; this->position_last_invalid = false; } } /** * Figures out whether it's time to send a position signal. * @param current_position The current position in the song. * @return True if enough time has elapsed for a signal to be sent; false * otherwise. */ bool Player::IsReadyToSendPosition(std::chrono::microseconds current_position) { bool ready = false; if (this->position_last_invalid) { ready = true; } else if (this->position_listener != nullptr) { auto difference = current_position - this->position_last; ready = difference >= this->position_period; } return ready; } /** * Registers a listener for position signals. * @param listener The function to which position signals shall be sent. * @param period_usecs The approximate period, in microseconds, between position * signals. */ void Player::RegisterPositionListener(PositionListener listener, const std::chrono::microseconds period) { this->position_listener = listener; this->position_period = period; } <|endoftext|>
<commit_before>#include "NegativeBinomialRand.h" template< typename T > NegativeBinomialRand<T>::NegativeBinomialRand(T number, double probability) : G(probability) { setParameters(number, probability); } template< typename T > std::string NegativeBinomialRand<T>::name() { return "Negative Binomial(" + toStringWithPrecision(getNumber()) + ", " + toStringWithPrecision(getProbability()) + ")"; } template< typename T > void NegativeBinomialRand<T>::setParameters(T number, double probability) { r = std::max(number, static_cast<T>(1.0)); p = std::min(std::max(probability, MIN_POSITIVE), 1.0); G.setProbability(1 - p); pdfCoef = std::pow(1 - p, r) / std::tgamma(r); Y.setParameters(r, p / (1 - p)); } template <> double NegativeBinomialRand<double>::P(int k) const { return (k < 0) ? 0 : pdfCoef * std::tgamma(r + k) / RandMath::factorial(k) * std::pow(p, k); } template <> double NegativeBinomialRand<int>::P(int k) const { return (k < 0) ? 0 : pdfCoef * RandMath::factorial(r + k - 1) / RandMath::factorial(k) * std::pow(p, k); } template< typename T > double NegativeBinomialRand<T>::F(double x) const { return 1.0 - RandMath::incompleteBetaFun(p, std::floor(x) + 1, r); } template<> double NegativeBinomialRand<double>::variate() const { return variateThroughGammaPoisson(); } template<> double NegativeBinomialRand<int>::variate() const { if (r < 10) return variateThroughGeometric(); return variateThroughGammaPoisson(); } template< typename T > double NegativeBinomialRand<T>::variateThroughGeometric() const { double res = 0; for (int i = 0; i != static_cast<int>(r); ++i) res += G.variate(); return res; } template< typename T > double NegativeBinomialRand<T>::variateThroughGammaPoisson() const { return PoissonRand::variate(Y.variate()); } template< typename T > double NegativeBinomialRand<T>::Mean() const { return p * r / (1 - p); } template< typename T > double NegativeBinomialRand<T>::Variance() const { return Mean() / (1 - p); } template< typename T > double NegativeBinomialRand<T>::Mode() const { return (r > 1) ? std::floor((r - 1) * p / (1 - p)) : 0; } template< typename T > double NegativeBinomialRand<T>::Skewness() const { return (1 + p) / std::sqrt(p * r); } template< typename T > double NegativeBinomialRand<T>::ExcessKurtosis() const { double kurtosis = (1 - p); kurtosis *= kurtosis; kurtosis /= p; kurtosis += 6; return kurtosis / r; } template class NegativeBinomialRand<int>; template class NegativeBinomialRand<double>; <commit_msg>Update NegativeBinomialRand.cpp<commit_after>#include "NegativeBinomialRand.h" template< typename T > NegativeBinomialRand<T>::NegativeBinomialRand(T number, double probability) : G(probability) { setParameters(number, probability); } template< typename T > std::string NegativeBinomialRand<T>::name() { return "Negative Binomial(" + toStringWithPrecision(getNumber()) + ", " + toStringWithPrecision(getProbability()) + ")"; } template< typename T > void NegativeBinomialRand<T>::setParameters(T number, double probability) { r = std::max(number, static_cast<T>(1.0)); p = std::min(std::max(probability, MIN_POSITIVE), 1.0); G.setProbability(1 - p); pdfCoef = std::pow(1 - p, r) / std::tgamma(r); Y.setParameters(r, p / (1 - p)); } template <> double NegativeBinomialRand<double>::P(int k) const { return (k < 0) ? 0 : pdfCoef * std::tgamma(r + k) / RandMath::factorial(k) * std::pow(p, k); } template <> double NegativeBinomialRand<int>::P(int k) const { return (k < 0) ? 0 : pdfCoef * RandMath::factorial(r + k - 1) / RandMath::factorial(k) * std::pow(p, k); } template< typename T > double NegativeBinomialRand<T>::F(double x) const { return 1.0 - RandMath::incompleteBetaFun(p, std::floor(x) + 1, r); } template<> double NegativeBinomialRand<double>::variate() const { return variateThroughGammaPoisson(); } template<> double NegativeBinomialRand<int>::variate() const { if (r < 10) return variateThroughGeometric(); return variateThroughGammaPoisson(); } template< typename T > double NegativeBinomialRand<T>::variateThroughGeometric() const { double res = 0; for (int i = 0; i != static_cast<int>(r); ++i) res += G.variate(); return res; } template< typename T > double NegativeBinomialRand<T>::variateThroughGammaPoisson() const { return PoissonRand::variate(Y.variate()); } template< typename T > double NegativeBinomialRand<T>::Mean() const { return p * r / (1 - p); } template< typename T > double NegativeBinomialRand<T>::Variance() const { return Mean() / (1 - p); } template< typename T > std::complex<double> NegativeBinomialRand<T>::CF(double t) const { double numerator = 1 - p; std::complex denominator(0, t); denominator = 1 - p * std::exp(denominator); return std::pow(numerator / denominator, r); } template< typename T > double NegativeBinomialRand<T>::Mode() const { return (r > 1) ? std::floor((r - 1) * p / (1 - p)) : 0; } template< typename T > double NegativeBinomialRand<T>::Skewness() const { return (1 + p) / std::sqrt(p * r); } template< typename T > double NegativeBinomialRand<T>::ExcessKurtosis() const { double kurtosis = (1 - p); kurtosis *= kurtosis; kurtosis /= p; kurtosis += 6; return kurtosis / r; } template class NegativeBinomialRand<int>; template class NegativeBinomialRand<double>; <|endoftext|>
<commit_before>/** * \file dcs/math/curvefit/interpolation/base1d.hpp * * \brief Base class for one-dimensional interpolation. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2013 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-commons (below referred to as "this program"). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP #define DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP #include <algorithm> #include <cstddef> #include <cmath> #include <dcs/assert.hpp> #include <dcs/debug.hpp> #include <dcs/exception.hpp> #include <dcs/math/traits/float.hpp> #include <stdexcept> #include <vector> //#define DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD 1 namespace dcs { namespace math { namespace curvefit { template <typename RealT> class base_1d_interpolator { public: typedef RealT real_type; public: template <typename XIterT, typename YIterT> base_1d_interpolator(XIterT first_x, XIterT last_x, YIterT first_y, YIterT last_y, ::std::size_t order, ::std::size_t m) : xx_(first_x, last_x), yy_(first_y, last_y), n_(xx_.size()), ord_(order), m_(m) #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD ,jsav_(0), cor_(false), dj_(::std::max(::std::size_t(1), static_cast< ::std::size_t >(::std::pow(n_, 0.25)))) #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD { DCS_ASSERT(n_ >= 2, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid number of interpolating points")); DCS_ASSERT(ord_ >= 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid interpolation order")); DCS_ASSERT(m_ >= 2, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid number of local points")); // DCS_ASSERT(m_ >= ord_, // DCS_EXCEPTION_THROW(::std::invalid_argument, // "Interpolation order cannot be greater than the number of local points")); DCS_ASSERT(m_ <= n_, DCS_EXCEPTION_THROW(::std::invalid_argument, "Number of local points cannot be greater than the number of interpolating points")); } public: real_type operator()(real_type x) const { return do_interpolate(x); } public: ::std::size_t order() const { return ord_; } public: ::std::size_t num_nodes() const { return xx_.size(); } public: ::std::size_t num_values() const { return yy_.size(); } public: ::std::vector<real_type> nodes() const { return xx_; } public: ::std::vector<real_type> values() const { return yy_(); } public: real_type node(::std::size_t i) const { return xx_[i]; } public: real_type value(::std::size_t i) const { return yy_[i]; } // Find the position k of the interval [xx_k,xx_{k+1}] where the given x falls such that // 'xx[k] <= x < xx[k+1], // for all 'x' within the table. // If 'x < xx[0]' then 'k' is 1. If 'x >= xx[n-1]' then 'k' is 'n-1' protected: ::std::size_t find(real_type x) const { #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD // Experimental return cor_ ? hunt(x) : locate(x); #else // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD //return sequential_find(x); return bsearch_find(x); #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD } #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD /// Find the location of a given value using the binary search method. protected: ::std::size_t locate(real_type x) const { bool ascnd(xx_[n_-1] >= xx_[0]); ::std::size_t jl(0); ::std::size_t ju(n_-1); while ((ju-jl) > 1) { //::std::size_t jm((ju+jl) >> 1); long jm((ju+jl) >> 1); if ((x >= xx_[jm]) == ascnd) { jl = jm; } else { ju = jm; } } cor_ = ::std::abs(jl-jsav_) > dj_ ? false : true; jsav_ = jl; return ::std::max(::std::ptrdiff_t(0), ::std::min(static_cast< ::std::ptrdiff_t >(n_-m_), static_cast< ::std::ptrdiff_t >(jl-((m_-2) >> 1)))); } /// Bracket a specified value inside an interval. protected: ::std::size_t hunt(real_type x) const { bool ascnd(xx_[n_-1] >= xx_[0]); ::std::ptrdiff_t jl(jsav_); ::std::ptrdiff_t ju(0); ::std::size_t inc(1); if (jl < 0 || jl > (n_-1)) { jl = 0; ju = n_-1; } else if ((x >= xx_[jl]) == ascnd) { while (true) { ju = jl + inc; if (ju >= (n_-1)) { ju = n_-1; break; } else if ((x < xx_[ju]) == ascnd) { break; } else { jl = ju; inc *= 2; } } } else { ju = jl; while (true) { jl = jl - inc; if (jl <= 0) { jl = 0; break; } else if ((x >= xx_[jl]) == ascnd) { break; } else { ju = jl; inc *= 2; } } } while ((ju-jl) > 1) { ::std::size_t jm((ju+jl) >> 1); if ((x >= xx_[jm]) == ascnd) { jl = jm; } else { ju = jm; } } cor_ = ::std::abs(jl-jsav_) > dj_ ? false : true; jsav_ = jl; return ::std::max(::std::ptrdiff_t(0), ::std::min(static_cast< ::std::ptrdiff_t >(n_-m_), static_cast< ::std::ptrdiff_t >(jl-((m_-2) >> 1)))); } #else // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD /// Locate a given value using a sequential search protected: ::std::size_t sequential_find(real_type x) const { if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[0])) { return 0; } for (::std::size_t i = 1; i < n_; ++i) { if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[i])) { return i-1; } } return n_-1; } /// Locate a given value by binary search protected: ::std::size_t bsearch_find(real_type x) const { // Handle out-of-domain points if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[0])) { return 0; } if (::dcs::math::float_traits<real_type>::approximately_greater_equal(x, xx_[n_-1])) { return n_-1; } ::std::size_t lo(0); ::std::size_t hi(n_-1); while (lo < (hi-1)) { const ::std::size_t mid((hi+lo) >> 1); if (::dcs::math::float_traits<real_type>::definitely_less(x, xx_[mid])) { hi = mid; } else { lo = mid; } } return lo; } #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD private: virtual real_type do_interpolate(real_type x) const = 0; private: const ::std::vector<real_type> xx_; ///< Data points private: const ::std::vector<real_type> yy_; ///< Data values // private: const ::std::size_t n_; ///< The number of interpolating points private: const long n_; ///< The number of interpolating points private: const ::std::size_t ord_; ///< The order of interpolation // private: const ::std::size_t m_; ///< The number of local points private: const long m_; ///< The number of local points #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD // private: mutable ::std::size_t jsav_; // private: mutable ::std::size_t cor_; // private: const ::std::size_t dj_; private: mutable long jsav_; private: mutable bool cor_; private: const long dj_; #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD }; // base_1d_interpolator }}} // Namespace dcs::math::curvefit #endif // DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP <commit_msg>(new:minor) Improved doc for bsearch_find method<commit_after>/** * \file dcs/math/curvefit/interpolation/base1d.hpp * * \brief Base class for one-dimensional interpolation. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2013 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-commons (below referred to as "this program"). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP #define DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP #include <algorithm> #include <cstddef> #include <cmath> #include <dcs/assert.hpp> #include <dcs/debug.hpp> #include <dcs/exception.hpp> #include <dcs/math/traits/float.hpp> #include <stdexcept> #include <vector> //#define DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD 1 namespace dcs { namespace math { namespace curvefit { template <typename RealT> class base_1d_interpolator { public: typedef RealT real_type; public: template <typename XIterT, typename YIterT> base_1d_interpolator(XIterT first_x, XIterT last_x, YIterT first_y, YIterT last_y, ::std::size_t order, ::std::size_t m) : xx_(first_x, last_x), yy_(first_y, last_y), n_(xx_.size()), ord_(order), m_(m) #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD ,jsav_(0), cor_(false), dj_(::std::max(::std::size_t(1), static_cast< ::std::size_t >(::std::pow(n_, 0.25)))) #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD { DCS_ASSERT(n_ >= 2, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid number of interpolating points")); DCS_ASSERT(ord_ >= 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid interpolation order")); DCS_ASSERT(m_ >= 2, DCS_EXCEPTION_THROW(::std::invalid_argument, "Invalid number of local points")); // DCS_ASSERT(m_ >= ord_, // DCS_EXCEPTION_THROW(::std::invalid_argument, // "Interpolation order cannot be greater than the number of local points")); DCS_ASSERT(m_ <= n_, DCS_EXCEPTION_THROW(::std::invalid_argument, "Number of local points cannot be greater than the number of interpolating points")); } public: real_type operator()(real_type x) const { return do_interpolate(x); } public: ::std::size_t order() const { return ord_; } public: ::std::size_t num_nodes() const { return xx_.size(); } public: ::std::size_t num_values() const { return yy_.size(); } public: ::std::vector<real_type> nodes() const { return xx_; } public: ::std::vector<real_type> values() const { return yy_(); } public: real_type node(::std::size_t i) const { return xx_[i]; } public: real_type value(::std::size_t i) const { return yy_[i]; } // Find the position k of the interval [xx_k,xx_{k+1}] where the given x falls such that // 'xx[k] <= x < xx[k+1], // for all 'x' within the table. // If 'x < xx[0]' then 'k' is 1. If 'x >= xx[n-1]' then 'k' is 'n-1' protected: ::std::size_t find(real_type x) const { #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD // Experimental return cor_ ? hunt(x) : locate(x); #else // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD //return sequential_find(x); return bsearch_find(x); #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD } #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD /// Find the location of a given value using the binary search method. protected: ::std::size_t locate(real_type x) const { bool ascnd(xx_[n_-1] >= xx_[0]); ::std::size_t jl(0); ::std::size_t ju(n_-1); while ((ju-jl) > 1) { //::std::size_t jm((ju+jl) >> 1); long jm((ju+jl) >> 1); if ((x >= xx_[jm]) == ascnd) { jl = jm; } else { ju = jm; } } cor_ = ::std::abs(jl-jsav_) > dj_ ? false : true; jsav_ = jl; return ::std::max(::std::ptrdiff_t(0), ::std::min(static_cast< ::std::ptrdiff_t >(n_-m_), static_cast< ::std::ptrdiff_t >(jl-((m_-2) >> 1)))); } /// Bracket a specified value inside an interval. protected: ::std::size_t hunt(real_type x) const { bool ascnd(xx_[n_-1] >= xx_[0]); ::std::ptrdiff_t jl(jsav_); ::std::ptrdiff_t ju(0); ::std::size_t inc(1); if (jl < 0 || jl > (n_-1)) { jl = 0; ju = n_-1; } else if ((x >= xx_[jl]) == ascnd) { while (true) { ju = jl + inc; if (ju >= (n_-1)) { ju = n_-1; break; } else if ((x < xx_[ju]) == ascnd) { break; } else { jl = ju; inc *= 2; } } } else { ju = jl; while (true) { jl = jl - inc; if (jl <= 0) { jl = 0; break; } else if ((x >= xx_[jl]) == ascnd) { break; } else { ju = jl; inc *= 2; } } } while ((ju-jl) > 1) { ::std::size_t jm((ju+jl) >> 1); if ((x >= xx_[jm]) == ascnd) { jl = jm; } else { ju = jm; } } cor_ = ::std::abs(jl-jsav_) > dj_ ? false : true; jsav_ = jl; return ::std::max(::std::ptrdiff_t(0), ::std::min(static_cast< ::std::ptrdiff_t >(n_-m_), static_cast< ::std::ptrdiff_t >(jl-((m_-2) >> 1)))); } #else // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD /// Locate a given value using a sequential search protected: ::std::size_t sequential_find(real_type x) const { if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[0])) { return 0; } for (::std::size_t i = 1; i < n_; ++i) { if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[i])) { return i-1; } } return n_-1; } /** * Locate a given value by binary search * * The resulting index \c j is guaranteed to be strictly less than the max * number of nodes and greater than or equal to 0, so that the implicit bracket * <code>[j,j+1]</code> always corresponds to a region within the implicit value * range of the value array. * * Specifically, suppose the node array is * \f$k=\{k_0, k_1, \ldots, k_m\}\f$, the index returned by this * function is: * \f{equation} * \begin{cases} * 0, & x \le k_0,\\ * j, & x > k_{j-1} && x \le k_j,\\ * m-1, & x \ge k_m,\\ * \end{cases} * \f} */ protected: ::std::size_t bsearch_find(real_type x) const { // Handle out-of-domain points if (::dcs::math::float_traits<real_type>::approximately_less_equal(x, xx_[0])) { return 0; } if (::dcs::math::float_traits<real_type>::approximately_greater_equal(x, xx_[n_-1])) { return n_-1; } ::std::size_t lo(0); ::std::size_t hi(n_-1); while (lo < (hi-1)) { const ::std::size_t mid((hi+lo) >> 1); if (::dcs::math::float_traits<real_type>::definitely_less(x, xx_[mid])) { hi = mid; } else { lo = mid; } } return lo; } #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD private: virtual real_type do_interpolate(real_type x) const = 0; private: const ::std::vector<real_type> xx_; ///< Data points private: const ::std::vector<real_type> yy_; ///< Data values // private: const ::std::size_t n_; ///< The number of interpolating points private: const long n_; ///< The number of interpolating points private: const ::std::size_t ord_; ///< The order of interpolation // private: const ::std::size_t m_; ///< The number of local points private: const long m_; ///< The number of local points #ifdef DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD // private: mutable ::std::size_t jsav_; // private: mutable ::std::size_t cor_; // private: const ::std::size_t dj_; private: mutable long jsav_; private: mutable bool cor_; private: const long dj_; #endif // DCS_MATH_CURVEFIT_INTERPOLATION_USE_CORRELATION_DRIVEN_SEARCH_METHOD }; // base_1d_interpolator }}} // Namespace dcs::math::curvefit #endif // DCS_MATH_CURVEFIT_INTERPOLATION_BASE1D_HPP <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * 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. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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. ** ***********************************************************************************************************************/ #include "Node.h" #include "../modelbase.h" #include "../model/Model.h" #include "commands/UndoCommand.h" #include "ModelException.h" #include "Reference.h" #include "Core/src/AdapterManager.h" using namespace Logger; namespace Model { ::Core::InitializationRegistry& nodeTypeInitializationRegistry(); DEFINE_TYPE_ID_BASE(Node, nodeTypeInitializationRegistry, "Node",) /*********************************************************************************************************************** * STATIC MEMBERS **********************************************************************************************************************/ int Node::numRegisteredTypes_ = 0; QHash<QString, Node::NodeConstructor> Node::nodeConstructorRegister; QHash<QString, Node::NodePersistenceConstructor> Node::nodePersistenceConstructorRegister; QSet<const Node*>& Node::partiallyLoadedNodes() { static QSet<const Node*> set; return set; } /*********************************************************************************************************************** * CONSTRUCTORS AND DESTRUCTORS **********************************************************************************************************************/ Node::Node(Node* parent) : parent_{parent} { if (parent && !parent->isModifyable()) throw ModelException("Trying to create a node with an non-modifiable parent."); } Node::~Node() { partiallyLoadedNodes().remove(this); } Node* Node::createDefaultInstance(Node*) { Q_ASSERT(false); return nullptr; } /*********************************************************************************************************************** * MAIN METHODS **********************************************************************************************************************/ void Node::execute(UndoCommand *command) { if ( this != command->target() ) throw ModelException("Command target differs from current node when executing commands"); Model* m = model(); if (m) { if ( !m->canBeModified(this) ) throw ModelException("Can not modify the current node."); m->pushCommandOnUndoStack(command); } else { command->redo(); SAFE_DELETE(command); } } Node* Node::lowestCommonAncestor(Node* other) { QList<Node*> thisParents; QList<Node*> otherParents; // Get all parents of the current node Node* n = this; while ( n ) { thisParents.prepend(n); n = n->parent(); } // Get all parents of the other node n = other; while ( n ) { otherParents.prepend(n); n = n->parent(); } // Find the lowest common ancestor n = nullptr; while ( thisParents.size() > 0 && otherParents.size() > 0 && thisParents.first() == otherParents.first() ) { n = thisParents.first(); thisParents.removeFirst(); otherParents.removeFirst(); } return n; } bool Node::isAncestorOf(const Node* other) const { if (other == nullptr) return false; const Node* p = other->parent(); while (p && p != this) p = p->parent(); return p == this; } Node* Node::childToSubnode(const Node* other) const { if (other == nullptr) return nullptr; const Node* child = other; const Node* parent = child->parent(); while (parent && parent != this) { child = parent; parent = child->parent(); } return parent == this ? const_cast<Node*>(child) : nullptr; } bool Node::isModifyable() const { Model* m = model(); return !m || m->canBeModified(this); } bool Node::replaceChild(Node*, Node*) { return false; } bool Node::findSymbols(QSet<Node*>& result, const SymbolMatcher& matcher, Node* source, FindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) { bool found{}; if (direction == SEARCH_HERE) { if (symbolMatches(matcher, symbolTypes)) { found = true; result.insert(this); } } else if (direction == SEARCH_DOWN) { for (auto c : childrenInScope()) found = c->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found; } else if (direction == SEARCH_UP) { auto ignore = childToSubnode(source); for (auto c : childrenInScope()) if (c != ignore) // Optimize the search by skipping this scope, since we've already searched there found = c->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found; if ((exhaustAllScopes || !found) && symbolMatches(matcher, symbolTypes)) { found = true; result.insert(this); } if ((exhaustAllScopes || !found) && parent_) found = parent_->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes) || found; } return found; } QList<Node*> Node::childrenInScope() const { return children(); } void Node::beginModification(const QString &text) { if (auto m = model()) m->beginModification(this, text); } void Node::endModification() { if (auto m = model()) m->endModification(); } QString Node::toDebugString() { auto ntdsa = Core::AdapterManager::adapt<NodeToDebugStringAdapter>(this); QString ret = ntdsa ? ntdsa->str : "no debug string for node"; SAFE_DELETE(ntdsa); return ret; } bool Node::hasPartiallyLoadedChildren() const { if (isPartiallyLoaded()) return true; return false; } /*********************************************************************************************************************** * GETTERS AND SETTERS **********************************************************************************************************************/ void Node::setParent(Node* parent) { //TODO: is this operation efficient and even possible when performed on top level objects such as namespaces and // packages? auto mOld = model(); auto mNew = parent ? parent->model() : nullptr; if (mOld || mNew) { QList<Node*> queue; queue.append(this); // Transfer unresolved references from the old model to the new one while (!queue.isEmpty()) { if (auto r = dynamic_cast<Reference*>(queue.first())) { if (!r->isResolved() ) { if (mOld) mOld->removeUnresolvedReference(r); if (mNew) mNew->addUnresolvedReference(r); } } queue.append(queue.first()->children()); queue.removeFirst(); } } parent_ = parent; } QList<Node*> Node::children() const { return QList<Node*>(); } bool Node::definesSymbol() const { return false; } const QString& Node::symbolName() const { static QString nullString; return nullString; } Node::SymbolTypes Node::symbolType() const { return UNSPECIFIED; } bool Node::isNewPersistenceUnit() const { return false; } Node* Node::persistentUnitNode() const { const Node* persistentUnitNode = this; const Node* prev = this; while ( persistentUnitNode && persistentUnitNode->isNewPersistenceUnit() == false ) { prev = persistentUnitNode; persistentUnitNode = persistentUnitNode->parent(); } if (persistentUnitNode) return const_cast<Node*> (persistentUnitNode); else return const_cast<Node*> (prev); } int Node::revision() const { return revision_; } void Node::incrementRevision() { revision_++; } void Node::addToRevision(int valueToAdd) { revision_ += valueToAdd; } NodeReadWriteLock* Node::accessLock() const { if ( parent_ ) return parent_->accessLock(); else return model()->rootLock(); } QList<UsedLibrary*> Node::usedLibraries() { QList<UsedLibrary*> all; for(auto c : children()) all << c->usedLibraries(); return all; } /*********************************************************************************************************************** * STATIC METHODS **********************************************************************************************************************/ int Node::registerNodeType(const QString &type, const NodeConstructor constructor, const NodePersistenceConstructor persistenceconstructor) { if ( isTypeRegistered(type) ) throw ModelException("Trying to register a node type that has already been registered: " + type); nodeConstructorRegister.insert(type, constructor); nodePersistenceConstructorRegister.insert(type, persistenceconstructor); ModelBase::log()->add(Log::LOGINFO, "Registered new node type " + type); ++numRegisteredTypes_; return numRegisteredTypes_; // Id 0 is reserved for Node } Node* Node::createNewNode(const QString &type, Node* parent) { auto iter = nodeConstructorRegister.find(type); if ( iter != nodeConstructorRegister.end() ) { return iter.value()(parent); } else { ModelBase::log()->add(Log::LOGERROR, "Could not create new node. Requested node type '" + type +"' has not been registered."); return nullptr; } } Node* Node::createNewNode(const QString &type, Node* parent, PersistentStore &store, bool partialLoadHint) { auto iter = nodePersistenceConstructorRegister.find(type); if ( iter != nodePersistenceConstructorRegister.end() ) { return iter.value()(parent, store, partialLoadHint); } else { ModelBase::log()->add(Log::LOGERROR, "Could not create new node from persistence. Requested node type '" + type + "' has not been registered."); return nullptr; } } bool Node::isTypeRegistered(const QString &type) { return nodeConstructorRegister.contains(type); } } <commit_msg>Resolve references across model boundaries by looking in libraries<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * 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. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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. ** ***********************************************************************************************************************/ #include "Node.h" #include "../modelbase.h" #include "../model/Model.h" #include "commands/UndoCommand.h" #include "ModelException.h" #include "Reference.h" #include "Core/src/AdapterManager.h" #include "UsedLibrary.h" using namespace Logger; namespace Model { ::Core::InitializationRegistry& nodeTypeInitializationRegistry(); DEFINE_TYPE_ID_BASE(Node, nodeTypeInitializationRegistry, "Node",) /*********************************************************************************************************************** * STATIC MEMBERS **********************************************************************************************************************/ int Node::numRegisteredTypes_ = 0; QHash<QString, Node::NodeConstructor> Node::nodeConstructorRegister; QHash<QString, Node::NodePersistenceConstructor> Node::nodePersistenceConstructorRegister; QSet<const Node*>& Node::partiallyLoadedNodes() { static QSet<const Node*> set; return set; } /*********************************************************************************************************************** * CONSTRUCTORS AND DESTRUCTORS **********************************************************************************************************************/ Node::Node(Node* parent) : parent_{parent} { if (parent && !parent->isModifyable()) throw ModelException("Trying to create a node with an non-modifiable parent."); } Node::~Node() { partiallyLoadedNodes().remove(this); } Node* Node::createDefaultInstance(Node*) { Q_ASSERT(false); return nullptr; } /*********************************************************************************************************************** * MAIN METHODS **********************************************************************************************************************/ void Node::execute(UndoCommand *command) { if ( this != command->target() ) throw ModelException("Command target differs from current node when executing commands"); Model* m = model(); if (m) { if ( !m->canBeModified(this) ) throw ModelException("Can not modify the current node."); m->pushCommandOnUndoStack(command); } else { command->redo(); SAFE_DELETE(command); } } Node* Node::lowestCommonAncestor(Node* other) { QList<Node*> thisParents; QList<Node*> otherParents; // Get all parents of the current node Node* n = this; while ( n ) { thisParents.prepend(n); n = n->parent(); } // Get all parents of the other node n = other; while ( n ) { otherParents.prepend(n); n = n->parent(); } // Find the lowest common ancestor n = nullptr; while ( thisParents.size() > 0 && otherParents.size() > 0 && thisParents.first() == otherParents.first() ) { n = thisParents.first(); thisParents.removeFirst(); otherParents.removeFirst(); } return n; } bool Node::isAncestorOf(const Node* other) const { if (other == nullptr) return false; const Node* p = other->parent(); while (p && p != this) p = p->parent(); return p == this; } Node* Node::childToSubnode(const Node* other) const { if (other == nullptr) return nullptr; const Node* child = other; const Node* parent = child->parent(); while (parent && parent != this) { child = parent; parent = child->parent(); } return parent == this ? const_cast<Node*>(child) : nullptr; } bool Node::isModifyable() const { Model* m = model(); return !m || m->canBeModified(this); } bool Node::replaceChild(Node*, Node*) { return false; } bool Node::findSymbols(QSet<Node*>& result, const SymbolMatcher& matcher, Node* source, FindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) { bool found{}; if (direction == SEARCH_HERE) { if (symbolMatches(matcher, symbolTypes)) { found = true; result.insert(this); } } else if (direction == SEARCH_DOWN) { for (auto c : childrenInScope()) found = c->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found; } else if (direction == SEARCH_UP) { auto ignore = childToSubnode(source); for (auto c : childrenInScope()) if (c != ignore) // Optimize the search by skipping this scope, since we've already searched there found = c->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found; if ((exhaustAllScopes || !found) && symbolMatches(matcher, symbolTypes)) { found = true; result.insert(this); } if ((exhaustAllScopes || !found) && parent_) found = parent_->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes) || found; // Search in libraries. This is only valid for root nodes if ((exhaustAllScopes || !found) && !parent_) for(auto l : usedLibraries()) { auto libRoot = l->libraryRoot(); Q_ASSERT(libRoot); found = libRoot->findSymbols(result, matcher, libRoot, SEARCH_DOWN, symbolTypes, exhaustAllScopes) || found; } } return found; } QList<Node*> Node::childrenInScope() const { return children(); } void Node::beginModification(const QString &text) { if (auto m = model()) m->beginModification(this, text); } void Node::endModification() { if (auto m = model()) m->endModification(); } QString Node::toDebugString() { auto ntdsa = Core::AdapterManager::adapt<NodeToDebugStringAdapter>(this); QString ret = ntdsa ? ntdsa->str : "no debug string for node"; SAFE_DELETE(ntdsa); return ret; } bool Node::hasPartiallyLoadedChildren() const { if (isPartiallyLoaded()) return true; return false; } /*********************************************************************************************************************** * GETTERS AND SETTERS **********************************************************************************************************************/ void Node::setParent(Node* parent) { //TODO: is this operation efficient and even possible when performed on top level objects such as namespaces and // packages? auto mOld = model(); auto mNew = parent ? parent->model() : nullptr; if (mOld || mNew) { QList<Node*> queue; queue.append(this); // Transfer unresolved references from the old model to the new one while (!queue.isEmpty()) { if (auto r = dynamic_cast<Reference*>(queue.first())) { if (!r->isResolved() ) { if (mOld) mOld->removeUnresolvedReference(r); if (mNew) mNew->addUnresolvedReference(r); } } queue.append(queue.first()->children()); queue.removeFirst(); } } parent_ = parent; } QList<Node*> Node::children() const { return QList<Node*>(); } bool Node::definesSymbol() const { return false; } const QString& Node::symbolName() const { static QString nullString; return nullString; } Node::SymbolTypes Node::symbolType() const { return UNSPECIFIED; } bool Node::isNewPersistenceUnit() const { return false; } Node* Node::persistentUnitNode() const { const Node* persistentUnitNode = this; const Node* prev = this; while ( persistentUnitNode && persistentUnitNode->isNewPersistenceUnit() == false ) { prev = persistentUnitNode; persistentUnitNode = persistentUnitNode->parent(); } if (persistentUnitNode) return const_cast<Node*> (persistentUnitNode); else return const_cast<Node*> (prev); } int Node::revision() const { return revision_; } void Node::incrementRevision() { revision_++; } void Node::addToRevision(int valueToAdd) { revision_ += valueToAdd; } NodeReadWriteLock* Node::accessLock() const { if ( parent_ ) return parent_->accessLock(); else return model()->rootLock(); } QList<UsedLibrary*> Node::usedLibraries() { QList<UsedLibrary*> all; for(auto c : children()) all << c->usedLibraries(); return all; } /*********************************************************************************************************************** * STATIC METHODS **********************************************************************************************************************/ int Node::registerNodeType(const QString &type, const NodeConstructor constructor, const NodePersistenceConstructor persistenceconstructor) { if ( isTypeRegistered(type) ) throw ModelException("Trying to register a node type that has already been registered: " + type); nodeConstructorRegister.insert(type, constructor); nodePersistenceConstructorRegister.insert(type, persistenceconstructor); ModelBase::log()->add(Log::LOGINFO, "Registered new node type " + type); ++numRegisteredTypes_; return numRegisteredTypes_; // Id 0 is reserved for Node } Node* Node::createNewNode(const QString &type, Node* parent) { auto iter = nodeConstructorRegister.find(type); if ( iter != nodeConstructorRegister.end() ) { return iter.value()(parent); } else { ModelBase::log()->add(Log::LOGERROR, "Could not create new node. Requested node type '" + type +"' has not been registered."); return nullptr; } } Node* Node::createNewNode(const QString &type, Node* parent, PersistentStore &store, bool partialLoadHint) { auto iter = nodePersistenceConstructorRegister.find(type); if ( iter != nodePersistenceConstructorRegister.end() ) { return iter.value()(parent, store, partialLoadHint); } else { ModelBase::log()->add(Log::LOGERROR, "Could not create new node from persistence. Requested node type '" + type + "' has not been registered."); return nullptr; } } bool Node::isTypeRegistered(const QString &type) { return nodeConstructorRegister.contains(type); } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief R8C PLUSE OUT/LCD メイン @n for ST7567 SPI (128 x 32) @n LCD: Aitendo M-G0812P7567 @n ENCODER: A: P10, B: P11 Com: Vss @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstring> #include "main.hpp" #include "system.hpp" #include "clock.hpp" #include "common/command.hpp" #include "common/format.hpp" #include "common/monograph.hpp" #include "port_def.hpp" #include "bitmap/font32.h" static const uint8_t* nmbs_[] = { nmb_0, nmb_1, nmb_2, nmb_3, nmb_4, nmb_5, nmb_6, nmb_7, nmb_8, nmb_9, txt_hz, txt_k }; static uint8_t enc_lvl_ = 0; static volatile int8_t enc_cnt_ = 0; class encoder { public: void operator() () { uint8_t lvl = device::P1(); ///< 状態の取得 uint8_t pos = ~enc_lvl_ & lvl; ///< 立ち上がりエッジ検出 uint8_t neg = enc_lvl_ & ~lvl; ///< 立ち下がりエッジ検出 enc_lvl_ = lvl; ///< 状態のセーブ if(pos & device::P1.B0.b()) { if(lvl & device::P1.B1.b()) { --enc_cnt_; } else { ++enc_cnt_; } } if(neg & device::P1.B0.b()) { if(lvl & device::P1.B1.b()) { ++enc_cnt_; } else { --enc_cnt_; } } if(pos & device::P1.B1.b()) { if(lvl & device::P1.B0.b()) { ++enc_cnt_; } else { --enc_cnt_; } } if(neg & device::P1.B1.b()) { if(lvl & device::P1.B0.b()) { --enc_cnt_; } else { ++enc_cnt_; } } } }; static device::trb_io<encoder> timer_b_; static uart0 uart0_; static utils::command<64> command_; static spi_base spi_base_; static spi_ctrl spi_ctrl_; static lcd lcd_; static graphics::monograph bitmap_; static timer_j timer_j_; extern "C" { void sci_putch(char ch) { uart0_.putch(ch); } char sci_getch(void) { return uart0_.getch(); } uint16_t sci_length() { return uart0_.length(); } void sci_puts(const char* str) { uart0_.puts(str); } } extern "C" { const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = { reinterpret_cast<void*>(brk_inst_), nullptr, // (0) reinterpret_cast<void*>(null_task_), nullptr, // (1) flash_ready reinterpret_cast<void*>(null_task_), nullptr, // (2) reinterpret_cast<void*>(null_task_), nullptr, // (3) reinterpret_cast<void*>(null_task_), nullptr, // (4) コンパレーターB1 reinterpret_cast<void*>(null_task_), nullptr, // (5) コンパレーターB3 reinterpret_cast<void*>(null_task_), nullptr, // (6) reinterpret_cast<void*>(null_task_), nullptr, // (7) タイマRC reinterpret_cast<void*>(null_task_), nullptr, // (8) reinterpret_cast<void*>(null_task_), nullptr, // (9) reinterpret_cast<void*>(null_task_), nullptr, // (10) reinterpret_cast<void*>(null_task_), nullptr, // (11) reinterpret_cast<void*>(null_task_), nullptr, // (12) reinterpret_cast<void*>(null_task_), nullptr, // (13) キー入力 reinterpret_cast<void*>(null_task_), nullptr, // (14) A/D 変換 reinterpret_cast<void*>(null_task_), nullptr, // (15) reinterpret_cast<void*>(null_task_), nullptr, // (16) reinterpret_cast<void*>(uart0_.isend), nullptr, // (17) UART0 送信 reinterpret_cast<void*>(uart0_.irecv), nullptr, // (18) UART0 受信 reinterpret_cast<void*>(null_task_), nullptr, // (19) reinterpret_cast<void*>(null_task_), nullptr, // (20) reinterpret_cast<void*>(null_task_), nullptr, // (21) /INT2 reinterpret_cast<void*>(timer_j_.itask_out),nullptr, // (22) タイマRJ2 reinterpret_cast<void*>(null_task_), nullptr, // (23) 周期タイマ reinterpret_cast<void*>(timer_b_.itask),nullptr, // (24) タイマRB2 reinterpret_cast<void*>(null_task_), nullptr, // (25) /INT1 reinterpret_cast<void*>(null_task_), nullptr, // (26) /INT3 reinterpret_cast<void*>(null_task_), nullptr, // (27) reinterpret_cast<void*>(null_task_), nullptr, // (28) reinterpret_cast<void*>(null_task_), nullptr, // (29) /INT0 reinterpret_cast<void*>(null_task_), nullptr, // (30) reinterpret_cast<void*>(null_task_), nullptr, // (31) }; } __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30uS(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; PRCR.PRC0 = 0; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(240, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart0_.start(19200, ir_level); } // エンコーダー入力の設定 P10: (Phi_A), P11: (Phi_B), Vss: (COM) { utils::PORT_MAP(utils::port_map::P10::PORT); utils::PORT_MAP(utils::port_map::P11::PORT); device::PD1.B0 = 0; device::PD1.B1 = 0; device::PUR1.B0 = 1; ///< プルアップ device::PUR1.B1 = 1; ///< プルアップ } // spi_base, spi_ctrl ポートの初期化 { spi_ctrl_.init(); spi_base_.init(); } // LCD を開始 { lcd_.start(); bitmap_.init(); bitmap_.clear(0); // bitmap_.frame(0, 0, 128, 32, 1); } uint32_t count = 20; // TRJ のパルス出力設定 { utils::PORT_MAP(utils::port_map::P17::TRJIO); uint8_t ir_level = 1; if(!timer_j_.pluse_out(count, ir_level)) { sci_puts("TRJ out of range.\n"); } } sci_puts("Start R8C PLUSE OUT/LCD\n"); command_.set_prompt("# "); uint8_t cnt = 0; uint32_t value = 0; while(1) { timer_b_.sync(); // エンコーダー値の増減 int32_t d = 0; if(enc_cnt_ >= 4) { enc_cnt_ = 0; d = 1; } else if(enc_cnt_ <= -4) { enc_cnt_ = 0; d = -1; } if(d) { if(count < 100) { d *= 1; } else if(count < 1000) { // 1KHz d *= 10; // 10Hz step } else if(count < 10000) { // 10KHz d *= 100; // 100Hz step } else if(count < 100000) { // 100KHz d *= 1000; // 1KHz step } else if(count < 1000000) { // 1MHz d *= 10000; // 10KHz step } else { d *= 100000; // 100KHz step } count += static_cast<uint32_t>(d); if(count < 20) count = 20; else if(count > 10000000) count = 10000000; } if(value != count) { value = count; timer_j_.set_cycle(count); if(count > 99999) { utils::format("%dKHz\n") % (count / 1000); } else { utils::format("%dHz\n") % count; } } // 1/15 sec if((cnt & 15) == 0) { bitmap_.clear(0); uint32_t n = count; bool khz = false; if(n > 99999) { n /= 1000; khz = true; } bitmap_.draw_mobj(20 * 4, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 3, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 2, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 1, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 0, 0, nmbs_[n % 10]); if(khz) { bitmap_.draw_mobj(20 * 5, 0, nmbs_[11]); bitmap_.draw_mobj(20 * 5 + 11, 0, nmbs_[10]); } else { bitmap_.draw_mobj(20 * 5, 0, nmbs_[10]); } lcd_.copy(bitmap_.fb()); } ++cnt; } } <commit_msg>Update pluse input<commit_after>//=====================================================================// /*! @file @brief R8C PLUSE OUT/LCD メイン @n for ST7567 SPI (128 x 32) @n LCD: Aitendo M-G0812P7567 @n ENCODER: A: P10, B: P11 Com: Vss @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstring> #include "main.hpp" #include "system.hpp" #include "clock.hpp" #include "common/command.hpp" #include "common/format.hpp" #include "common/monograph.hpp" #include "port_def.hpp" #include "bitmap/font32.h" static const uint8_t* nmbs_[] = { nmb_0, nmb_1, nmb_2, nmb_3, nmb_4, nmb_5, nmb_6, nmb_7, nmb_8, nmb_9, txt_hz, txt_k }; static uint8_t enc_lvl_ = 0; static volatile int8_t enc_cnt_ = 0; class encoder { public: void operator() () { uint8_t lvl = device::P1(); ///< 状態の取得 uint8_t pos = ~enc_lvl_ & lvl; ///< 立ち上がりエッジ検出 uint8_t neg = enc_lvl_ & ~lvl; ///< 立ち下がりエッジ検出 enc_lvl_ = lvl; ///< 状態のセーブ if(pos & device::P1.B0.b()) { if(lvl & device::P1.B1.b()) { --enc_cnt_; } else { ++enc_cnt_; } } if(neg & device::P1.B0.b()) { if(lvl & device::P1.B1.b()) { ++enc_cnt_; } else { --enc_cnt_; } } if(pos & device::P1.B1.b()) { if(lvl & device::P1.B0.b()) { ++enc_cnt_; } else { --enc_cnt_; } } if(neg & device::P1.B1.b()) { if(lvl & device::P1.B0.b()) { --enc_cnt_; } else { ++enc_cnt_; } } } }; static device::trb_io<encoder> timer_b_; static uart0 uart0_; static utils::command<64> command_; static spi_base spi_base_; static spi_ctrl spi_ctrl_; static lcd lcd_; static graphics::monograph bitmap_; static timer_j timer_j_; extern "C" { void sci_putch(char ch) { uart0_.putch(ch); } char sci_getch(void) { return uart0_.getch(); } uint16_t sci_length() { return uart0_.length(); } void sci_puts(const char* str) { uart0_.puts(str); } } extern "C" { const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = { reinterpret_cast<void*>(brk_inst_), nullptr, // (0) reinterpret_cast<void*>(null_task_), nullptr, // (1) flash_ready reinterpret_cast<void*>(null_task_), nullptr, // (2) reinterpret_cast<void*>(null_task_), nullptr, // (3) reinterpret_cast<void*>(null_task_), nullptr, // (4) コンパレーターB1 reinterpret_cast<void*>(null_task_), nullptr, // (5) コンパレーターB3 reinterpret_cast<void*>(null_task_), nullptr, // (6) reinterpret_cast<void*>(null_task_), nullptr, // (7) タイマRC reinterpret_cast<void*>(null_task_), nullptr, // (8) reinterpret_cast<void*>(null_task_), nullptr, // (9) reinterpret_cast<void*>(null_task_), nullptr, // (10) reinterpret_cast<void*>(null_task_), nullptr, // (11) reinterpret_cast<void*>(null_task_), nullptr, // (12) reinterpret_cast<void*>(null_task_), nullptr, // (13) キー入力 reinterpret_cast<void*>(null_task_), nullptr, // (14) A/D 変換 reinterpret_cast<void*>(null_task_), nullptr, // (15) reinterpret_cast<void*>(null_task_), nullptr, // (16) reinterpret_cast<void*>(uart0_.isend), nullptr, // (17) UART0 送信 reinterpret_cast<void*>(uart0_.irecv), nullptr, // (18) UART0 受信 reinterpret_cast<void*>(null_task_), nullptr, // (19) reinterpret_cast<void*>(null_task_), nullptr, // (20) reinterpret_cast<void*>(null_task_), nullptr, // (21) /INT2 reinterpret_cast<void*>(timer_j_.iout), nullptr, // (22) タイマRJ2 reinterpret_cast<void*>(null_task_), nullptr, // (23) 周期タイマ reinterpret_cast<void*>(timer_b_.itask),nullptr, // (24) タイマRB2 reinterpret_cast<void*>(null_task_), nullptr, // (25) /INT1 reinterpret_cast<void*>(null_task_), nullptr, // (26) /INT3 reinterpret_cast<void*>(null_task_), nullptr, // (27) reinterpret_cast<void*>(null_task_), nullptr, // (28) reinterpret_cast<void*>(null_task_), nullptr, // (29) /INT0 reinterpret_cast<void*>(null_task_), nullptr, // (30) reinterpret_cast<void*>(null_task_), nullptr, // (31) }; } __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30uS(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; PRCR.PRC0 = 0; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(240, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart0_.start(19200, ir_level); } // エンコーダー入力の設定 P10: (Phi_A), P11: (Phi_B), Vss: (COM) { utils::PORT_MAP(utils::port_map::P10::PORT); utils::PORT_MAP(utils::port_map::P11::PORT); device::PD1.B0 = 0; device::PD1.B1 = 0; device::PUR1.B0 = 1; ///< プルアップ device::PUR1.B1 = 1; ///< プルアップ } // spi_base, spi_ctrl ポートの初期化 { spi_ctrl_.init(); spi_base_.init(); } // LCD を開始 { lcd_.start(); bitmap_.init(); bitmap_.clear(0); // bitmap_.frame(0, 0, 128, 32, 1); } uint32_t count = 20; // TRJ のパルス出力設定 { utils::PORT_MAP(utils::port_map::P17::TRJIO); uint8_t ir_level = 1; if(!timer_j_.pluse_out(count, ir_level)) { sci_puts("TRJ out of range.\n"); } } sci_puts("Start R8C PLUSE OUT/LCD\n"); command_.set_prompt("# "); uint8_t cnt = 0; uint32_t value = 0; while(1) { timer_b_.sync(); // エンコーダー値の増減 int32_t d = 0; if(enc_cnt_ >= 4) { enc_cnt_ = 0; d = 1; } else if(enc_cnt_ <= -4) { enc_cnt_ = 0; d = -1; } if(d) { if(count < 100) { d *= 1; } else if(count < 1000) { // 1KHz d *= 10; // 10Hz step } else if(count < 10000) { // 10KHz d *= 100; // 100Hz step } else if(count < 100000) { // 100KHz d *= 1000; // 1KHz step } else if(count < 1000000) { // 1MHz d *= 10000; // 10KHz step } else { d *= 100000; // 100KHz step } count += static_cast<uint32_t>(d); if(count < 20) count = 20; else if(count > 10000000) count = 10000000; } if(value != count) { value = count; timer_j_.set_cycle(count); if(count > 99999) { utils::format("%dKHz\n") % (count / 1000); } else { utils::format("%dHz\n") % count; } } // 1/15 sec if((cnt & 15) == 0) { bitmap_.clear(0); uint32_t n = count; bool khz = false; if(n > 99999) { n /= 1000; khz = true; } bitmap_.draw_mobj(20 * 4, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 3, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 2, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 1, 0, nmbs_[n % 10]); n /= 10; bitmap_.draw_mobj(20 * 0, 0, nmbs_[n % 10]); if(khz) { bitmap_.draw_mobj(20 * 5, 0, nmbs_[11]); bitmap_.draw_mobj(20 * 5 + 11, 0, nmbs_[10]); } else { bitmap_.draw_mobj(20 * 5, 0, nmbs_[10]); } lcd_.copy(bitmap_.fb()); } ++cnt; } } <|endoftext|>
<commit_before>// Copyright 2017 Adam 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 <type_traits> #include <cstdint> #include <string> #ifndef ASMITH_REFLECTION_CLASS_HPP #define ASMITH_REFLECTION_CLASS_HPP namespace asmith { class reflection_variable; class reflection_function; class reflection_constructor; class reflection_destructor; class reflection_class { public: virtual ~reflection_class() {} virtual const char* get_name() const = 0; virtual size_t get_size() const = 0; virtual size_t get_variable_count() const = 0; virtual const reflection_variable& get_variable(size_t) const = 0; virtual size_t get_function_count() const = 0; virtual const reflection_function& get_function(size_t) const = 0; virtual size_t get_constructor_count() const = 0; virtual const reflection_constructor& get_constructor(size_t) const = 0; virtual const reflection_destructor& get_destructor() const = 0; virtual size_t get_parent_count() const = 0; virtual const reflection_class& get_parent_class(size_t) const = 0; }; template<class C, class T> using reflection_variable_ptr = T C::*; } #endif<commit_msg>Partial layout for auto_reflection_class<commit_after>// Copyright 2017 Adam 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 <type_traits> #include <cstdint> #include <string> #include <memory> #include <vector> #ifndef ASMITH_REFLECTION_CLASS_HPP #define ASMITH_REFLECTION_CLASS_HPP namespace asmith { class reflection_variable; class reflection_function; class reflection_constructor; class reflection_destructor; class reflection_class { public: virtual ~reflection_class() {} virtual const char* get_name() const = 0; virtual size_t get_size() const = 0; virtual size_t get_variable_count() const = 0; virtual const reflection_variable& get_variable(size_t) const = 0; virtual size_t get_function_count() const = 0; virtual const reflection_function& get_function(size_t) const = 0; virtual size_t get_constructor_count() const = 0; virtual const reflection_constructor& get_constructor(size_t) const = 0; virtual const reflection_destructor& get_destructor() const = 0; virtual size_t get_parent_count() const = 0; virtual const reflection_class& get_parent_class(size_t) const = 0; }; class auto_reflection_class : public reflection_class { private: std::vector<std::shared_ptr<reflection_class>> mParents; std::vector<std::shared_ptr<reflection_constructor>> mConstructors; std::vector<std::shared_ptr<reflection_variable>> mVariables; std::vector<std::shared_ptr<reflection_function>> mFunctions; std::shared_ptr<reflection_destructor> mDestructor; const std::string mName; const size_t mSize; public: auto_reflection_class(const std::string& aName, const size_t aSize) : mName(aName), mSize(aSize) {} //! \todo Add parent_classes, constructors, variables and destructor template<class CLASS, class RETURN, class... PARAMS> auto_reflection_class& function(const std::string& aName, RETURN(CLASS::*aPtr)(PARAMS...), const size_t aModifiers) { mFunctions.push_back(std::shared_ptr<reflection_function>( new typedef auto_reflection_function<CLASS, RETURN, PARAMS...>(aName, aPtr, aModifiers); )); return *this; } // Inherited from reflection_class const char* get_name() const override { mName.c_str(); } size_t get_size() const override { return mSize; } size_t get_variable_count() const override { return mVariables.size(); } const reflection_variable& get_variable(size_t aIndex) const override { return *mVariables[aIndex]; } size_t get_function_count() const override { return mFunctions.size(); } const reflection_function& get_function(size_t aIndex) const override { return *mFunctions[aIndex]; } size_t get_constructor_count() const override { return mConstructors.size(); } const reflection_constructor& get_constructor(size_t aIndex) const override { return *mConstructors[aIndex]; } const reflection_destructor& get_destructor() const override { return *mDestructor; } size_t get_parent_count() const override { return mParents.size(); } const reflection_class& get_parent_class(size_t aIndex) const override { return *mParents[aIndex]; } }; } #endif<|endoftext|>
<commit_before>#include "fenetre.h" #include "ui_fenetre.h" #include "fileManagement.h" //#include <QMessageBox> Fenetre::Fenetre(QWidget *parent) : QMainWindow(parent), ui(new Ui::Fenetre) { ui->setupUi(this); //on connecte les Qapplication connect(ui->actionNouveau,SIGNAL(triggered()),this,SLOT(nouveauFichier())); connect(ui->actionOuvrir,SIGNAL(triggered()),this,SLOT(ouvrirFichier())); connect(ui->actionSauvegarder,SIGNAL(triggered()),this,SLOT(sauvegarderFichier())); connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit())); index = loadIndexFromFile("runes.index"); //on charge les runes //on charge les icones des runes; vectorPixRune.push_back(new QPixmap("marque_ico.png")); vectorPixRune.push_back(new QPixmap("sceau_ico.png")); vectorPixRune.push_back(new QPixmap("glyphe_ico.png")); vectorPixRune.push_back(new QPixmap("quint_ico.png")); for (auto &a : index) { QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément QLabel* ico = new QLabel; //icone de rune ico->setPixmap(vectorPixRune[static_cast<unsigned>(a.getType())]->scaledToHeight(50,Qt::SmoothTransformation)); //on resize QLabel* nom = new QLabel(a.getColoredName()); //on met le nom coloré de la rune nom->setWordWrap(true); nom->setMaximumWidth(200); QLabel* intEffet = new QLabel(a.getColoredEffect()); layout->addWidget(ico); layout->addWidget(nom); layout->addWidget(intEffet); QListWidgetItem* item = new QListWidgetItem(); ui->DRunelist->addItem(item); //temporaire QWidget* wi = new QWidget; wi->setLayout(layout); item->setSizeHint(wi->sizeHint()); ui->DRunelist->setItemWidget(item,wi); } connect(ui->DRunelist,SIGNAL(clicked(QModelIndex)),this,SLOT(ajouteBonneList(QModelIndex))); //on connecte pour que quand on clique on ajoute la rune. //on connecte pour qu'on pouisse supprimer les runes des petites listes connect(ui->MarquesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerMarque(QModelIndex))); connect(ui->SceauxList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerSceau(QModelIndex))); connect(ui->GlyphesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerGlyphe(QModelIndex))); connect(ui->QuintList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerQuint(QModelIndex))); } Fenetre::~Fenetre() { delete ui; } void Fenetre::supprimerMarque(QModelIndex ind) { page.remove(RuneType::Marque, ind.row()); //on supprime la bonne rune ui->MarquesList->removeItemWidget(ui->MarquesList->currentItem()); //on delete l'item ui->MarquesList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerSceau(QModelIndex ind) { page.remove(RuneType::Sceau, ind.row()); //on supprime la bonne rune ui->SceauxList->removeItemWidget(ui->SceauxList->currentItem()); //on delete l'item ui->SceauxList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerGlyphe(QModelIndex ind) { page.remove(RuneType::Glyphe, ind.row()); //on supprime la bonne rune ui->GlyphesList->removeItemWidget(ui->GlyphesList->currentItem()); //on delete l'item ui->GlyphesList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerQuint(QModelIndex ind) { page.remove(RuneType::Quint, ind.row()); //on supprime la bonne rune ui->QuintList->removeItemWidget(ui->QuintList->currentItem()); //on delete l'item ui->QuintList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::ajouteBonneList(QModelIndex ind) { bool success = page.ajouterRune(index[ind.row()]); //On ajoute le bon index à la runepage. théoriquement c'est bon. if (success) //on a jouté la rune { if (index[ind.row()].getType() == RuneType::Marque) //on a cliqué sur une marque { addToList(ui->MarquesList, index[ind.row()]); //on ajoute à la liste des marques } else if (index[ind.row()].getType() == RuneType::Sceau) //on a cliqué sur un sceau { addToList(ui->SceauxList, index[ind.row()]); //on ajoute à la liste des sceaux } else if (index[ind.row()].getType() == RuneType::Glyphe) //on a cliqué sur un glyphe { addToList(ui->GlyphesList, index[ind.row()]); //on ajoute à la liste des glyphes } else if (index[ind.row()].getType() == RuneType::Quint) //on a cliqué sur une quintessence { addToList(ui->QuintList, index[ind.row()]); //on ajoute à la liste des quints } } updateStats(); } void Fenetre::addToList(QListWidget* list, Rune const& rune) { QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément QLabel* nom = new QLabel(rune.getColoredName(7)); //on met le nom coloré de la rune nom->setWordWrap(true); nom->setMaximumWidth(125); QLabel* intEffet = new QLabel(rune.getColoredEffect(8)); layout->addWidget(nom); layout->addWidget(intEffet); QListWidgetItem* item = new QListWidgetItem(); list->addItem(item); //temporaire QWidget* wi = new QWidget; wi->setLayout(layout); item->setSizeHint(wi->sizeHint()); list->setItemWidget(item,wi); } void Fenetre::nouveauFichier() { //on vide les listes ui->MarquesList->clear(); ui->SceauxList->clear(); ui->GlyphesList->clear(); ui->QuintList->clear(); //on vide la page page.clear(); updateStats(); } void Fenetre::ouvrirFichier() { //rien pour le moment } void Fenetre::sauvegarderFichier() { //rien non plus } void Fenetre::updateStats() { if (ui->MarquesList->count() == 0 && ui->SceauxList->count() == 0 && ui->GlyphesList->count() == 0 && ui->QuintList->count() == 0) //les listes sont toutes vides { ui->StatLabel->setText(""); //on vide le texte } else { QString newLabel{"<html><head/><body>"}; QString tmp{""}; std::vector<Effet> allEffect = page.getAllEffect(); //on récupère tous les effets de la page ! for (auto &a : allEffect) //on parcoure tous les effets { tmp = (a.second > 0) ? "<span style=\" color:#d00000; font-size:20pt; font-weight:400\">+ " : "<span style=\" color:#0267b5; font-size:20pt; font-weight:400\">- "; //on prend le signe du bonus //+/- XX STAT (avec de la coloration et STAT en italique) newLabel += "<p align=\"center\">" + tmp + QString::number(abs(a.second)) + " </span><span style=\" font-style:italic; color:#000000; font-size:20pt; font-weight:600\">" + a.first.c_str() + "</span></p>"; } newLabel += "</body></html>"; //on finit la mise en page ui->StatLabel->setText(newLabel); } } <commit_msg>C'est bon on peut cliquer partout sur le QListItemWidget sans problèmes ! Note à moi même : pour les QListView, pressed >>>>> clicked !<commit_after>#include "fenetre.h" #include "ui_fenetre.h" #include "fileManagement.h" #include <QMessageBox> Fenetre::Fenetre(QWidget *parent) : QMainWindow(parent), ui(new Ui::Fenetre) { ui->setupUi(this); //on connecte les Qapplication connect(ui->actionNouveau,SIGNAL(triggered()),this,SLOT(nouveauFichier())); connect(ui->actionOuvrir,SIGNAL(triggered()),this,SLOT(ouvrirFichier())); connect(ui->actionSauvegarder,SIGNAL(triggered()),this,SLOT(sauvegarderFichier())); connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit())); index = loadIndexFromFile("runes.index"); //on charge les runes //on charge les icones des runes; vectorPixRune.push_back(new QPixmap("marque_ico.png")); vectorPixRune.push_back(new QPixmap("sceau_ico.png")); vectorPixRune.push_back(new QPixmap("glyphe_ico.png")); vectorPixRune.push_back(new QPixmap("quint_ico.png")); for (auto &a : index) { QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément QLabel* ico = new QLabel; //icone de rune ico->setPixmap(vectorPixRune[static_cast<unsigned>(a.getType())]->scaledToHeight(50,Qt::SmoothTransformation)); //on resize QLabel* nom = new QLabel(a.getColoredName()); //on met le nom coloré de la rune nom->setWordWrap(true); nom->setMaximumWidth(200); QLabel* intEffet = new QLabel(a.getColoredEffect()); layout->addWidget(ico); layout->addWidget(nom); layout->addWidget(intEffet); QListWidgetItem* item = new QListWidgetItem(); ui->DRunelist->addItem(item); //temporaire QWidget* wi = new QWidget; wi->setLayout(layout); item->setSizeHint(wi->sizeHint()); ui->DRunelist->setItemWidget(item,wi); } connect(ui->DRunelist,SIGNAL(pressed(QModelIndex)),this,SLOT(ajouteBonneList(QModelIndex))); //on connecte pour que quand on clique on ajoute la rune. //on connecte pour qu'on pouisse supprimer les runes des petites listes connect(ui->MarquesList,SIGNAL(pressed(QModelIndex)),this,SLOT(supprimerMarque(QModelIndex))); connect(ui->SceauxList,SIGNAL(pressed(QModelIndex)),this,SLOT(supprimerSceau(QModelIndex))); connect(ui->GlyphesList,SIGNAL(pressed(QModelIndex)),this,SLOT(supprimerGlyphe(QModelIndex))); connect(ui->QuintList,SIGNAL(pressed(QModelIndex)),this,SLOT(supprimerQuint(QModelIndex))); } Fenetre::~Fenetre() { delete ui; } void Fenetre::supprimerMarque(QModelIndex ind) { page.remove(RuneType::Marque, ind.row()); //on supprime la bonne rune ui->MarquesList->removeItemWidget(ui->MarquesList->currentItem()); //on delete l'item ui->MarquesList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerSceau(QModelIndex ind) { page.remove(RuneType::Sceau, ind.row()); //on supprime la bonne rune ui->SceauxList->removeItemWidget(ui->SceauxList->currentItem()); //on delete l'item ui->SceauxList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerGlyphe(QModelIndex ind) { page.remove(RuneType::Glyphe, ind.row()); //on supprime la bonne rune ui->GlyphesList->removeItemWidget(ui->GlyphesList->currentItem()); //on delete l'item ui->GlyphesList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::supprimerQuint(QModelIndex ind) { page.remove(RuneType::Quint, ind.row()); //on supprime la bonne rune ui->QuintList->removeItemWidget(ui->QuintList->currentItem()); //on delete l'item ui->QuintList->takeItem(ind.row()); //on enlève les espaces updateStats(); } void Fenetre::ajouteBonneList(QModelIndex ind) { bool success = page.ajouterRune(index[ind.row()]); //On ajoute le bon index à la runepage. théoriquement c'est bon. if (success) //on a jouté la rune { if (index[ind.row()].getType() == RuneType::Marque) //on a cliqué sur une marque { addToList(ui->MarquesList, index[ind.row()]); //on ajoute à la liste des marques } else if (index[ind.row()].getType() == RuneType::Sceau) //on a cliqué sur un sceau { addToList(ui->SceauxList, index[ind.row()]); //on ajoute à la liste des sceaux } else if (index[ind.row()].getType() == RuneType::Glyphe) //on a cliqué sur un glyphe { addToList(ui->GlyphesList, index[ind.row()]); //on ajoute à la liste des glyphes } else if (index[ind.row()].getType() == RuneType::Quint) //on a cliqué sur une quintessence { addToList(ui->QuintList, index[ind.row()]); //on ajoute à la liste des quints } } updateStats(); } void Fenetre::addToList(QListWidget* list, Rune const& rune) { QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément QLabel* nom = new QLabel(rune.getColoredName(7)); //on met le nom coloré de la rune nom->setWordWrap(true); nom->setMaximumWidth(125); QLabel* intEffet = new QLabel(rune.getColoredEffect(8)); layout->addWidget(nom); layout->addWidget(intEffet); QListWidgetItem* item = new QListWidgetItem(); list->addItem(item); //temporaire QWidget* wi = new QWidget; wi->setLayout(layout); item->setSizeHint(wi->sizeHint()); list->setItemWidget(item,wi); } void Fenetre::nouveauFichier() { //on vide les listes ui->MarquesList->clear(); ui->SceauxList->clear(); ui->GlyphesList->clear(); ui->QuintList->clear(); //on vide la page page.clear(); updateStats(); } void Fenetre::ouvrirFichier() { //rien pour le moment } void Fenetre::sauvegarderFichier() { //rien non plus } void Fenetre::updateStats() { if (ui->MarquesList->count() == 0 && ui->SceauxList->count() == 0 && ui->GlyphesList->count() == 0 && ui->QuintList->count() == 0) //les listes sont toutes vides { ui->StatLabel->setText(""); //on vide le texte } else { QString newLabel{"<html><head/><body>"}; QString tmp{""}; std::vector<Effet> allEffect = page.getAllEffect(); //on récupère tous les effets de la page ! for (auto &a : allEffect) //on parcoure tous les effets { tmp = (a.second > 0) ? "<span style=\" color:#d00000; font-size:20pt; font-weight:400\">+ " : "<span style=\" color:#0267b5; font-size:20pt; font-weight:400\">- "; //on prend le signe du bonus //+/- XX STAT (avec de la coloration et STAT en italique) newLabel += "<p align=\"center\">" + tmp + QString::number(abs(a.second)) + " </span><span style=\" font-style:italic; color:#000000; font-size:20pt; font-weight:600\">" + a.first.c_str() + "</span></p>"; } newLabel += "</body></html>"; //on finit la mise en page ui->StatLabel->setText(newLabel); } } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nl_bond.h" #include <cassert> #include <glog/logging.h> #include <linux/if_bridge.h> #include <netlink/route/link.h> #include <netlink/route/link/bonding.h> #include "cnetlink.h" #include "nl_output.h" #include "sai.h" namespace basebox { nl_bond::nl_bond(cnetlink *nl) : swi(nullptr), nl(nl) {} void nl_bond::clear() noexcept { lag_members.clear(); ifi2lag.clear(); } uint32_t nl_bond::get_lag_id(rtnl_link *bond) { assert(bond); return get_lag_id(rtnl_link_get_ifindex(bond)); } uint32_t nl_bond::get_lag_id(int ifindex) { auto it = ifi2lag.find(ifindex); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": lag_id not found for if=" << ifindex; return 0; } return it->second; } std::set<uint32_t> nl_bond::get_members(rtnl_link *bond) { auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } return mem_it->second; } std::set<uint32_t> nl_bond::get_members_by_port_id(uint32_t port_id) { auto mem_it = lag_members.find(port_id); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for port_id=" << port_id; return {}; } return mem_it->second; } int nl_bond::update_lag(rtnl_link *old_link, rtnl_link *new_link) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE VLOG(1) << __FUNCTION__ << ": updating bond interface "; int rv = 0; uint8_t o_mode, n_mode; uint32_t lag_id = nl->get_port_id(new_link); if (lag_id == 0) { rv = add_lag(new_link); if (rv < 0) return rv; lag_id = rv; } rv = rtnl_link_bond_get_mode(old_link, &o_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } rv = rtnl_link_bond_get_mode(new_link, &n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } if (o_mode != n_mode) { VLOG(1) << __FUNCTION__ << ": bond mode updated " << static_cast<uint32_t>(n_mode); rv = swi->lag_set_mode(lag_id, n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to set active state for " << OBJ_CAST(new_link); } return 0; } add_l3_address(new_link); #endif return 0; } int nl_bond::add_lag(rtnl_link *bond) { uint32_t lag_id = 0; int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint8_t mode; rtnl_link_bond_get_mode(bond, &mode); assert(bond); rv = swi->lag_create(&lag_id, rtnl_link_get_name(bond), mode); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to create lag for " << OBJ_CAST(bond); return rv; } rv = lag_id; auto rv_emp = ifi2lag.emplace(std::make_pair(rtnl_link_get_ifindex(bond), lag_id)); if (!rv_emp.second) { VLOG(1) << __FUNCTION__ << ": lag exists with lag_id=" << rv_emp.first->second << " for bond " << OBJ_CAST(bond); rv = rv_emp.first->second; if (lag_id != rv_emp.first->second) swi->lag_remove(lag_id); } #endif return rv; } int nl_bond::remove_lag(rtnl_link *bond) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE int rv = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return -ENODEV; } rv = swi->lag_remove(it->second); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to remove lag with lag_id=" << it->second << " for bond " << OBJ_CAST(bond); return rv; } ifi2lag.erase(it); #endif return 0; } int nl_bond::add_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint32_t lag_id; uint8_t state = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": no lag_id found creating new for " << OBJ_CAST(bond); rv = add_lag(bond); if (rv < 0) return rv; lag_id = rv; } else { lag_id = it->second; } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignoring port " << OBJ_CAST(link); return -EINVAL; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { // No ports in lag std::set<uint32_t> members; members.insert(port_id); auto lm_rv = lag_members.emplace(lag_id, members); } else { mem_it->second.insert(port_id); } rv = rtnl_link_bond_slave_get_state(link, &state); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get slave state for " << OBJ_CAST(link); } rv = swi->lag_add_member(lag_id, port_id); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed add member " << port_id; return -EINVAL; } rv = swi->lag_set_member_active(lag_id, port_id, state == 0); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed set active member " << port_id; return -EINVAL; } if (rtnl_link_get_master(bond)) { // check bridge attachement auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); if (br_link) { VLOG(2) << __FUNCTION__ << ": bond was already bridge slave: " << OBJ_CAST(br_link); nl->link_created(br_link); auto new_state = rtnl_link_bridge_get_port_state(br_link); std::string state; switch (new_state) { case BR_STATE_FORWARDING: state = "forward"; break; case BR_STATE_BLOCKING: state = "block"; break; case BR_STATE_DISABLED: state = "disable"; break; case BR_STATE_LISTENING: state = "listen"; break; case BR_STATE_LEARNING: state = "learn"; break; default: VLOG(1) << __FUNCTION__ << ": stp state change not supported"; return rv; } swi->ofdpa_stg_state_port_set(port_id, state); } rv = nl->set_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } // XXX FIXME check for vlan interfaces // Adding an IP address here will ensure that every slave that is // added will retry to add the address. It will not be written to the // ASIC, but repeated messages will be seen // This should be done in ::add_lag, but for currently unknown reasons // this fails when the lag has no members yet. So keep it here for now. add_l3_address(bond); #endif return rv; } int nl_bond::remove_lag_member(rtnl_link *link) { assert(link); int master_id = rtnl_link_get_master(link); auto master = nl->get_link(master_id, AF_UNSPEC); return remove_lag_member(master, link); } int nl_bond::remove_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(FATAL) << __FUNCTION__ << ": no lag_id found for " << OBJ_CAST(bond); } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignore invalid lag port " << OBJ_CAST(link); return -EINVAL; } auto lm_rv = lag_members.find(it->second); if (lm_rv == lag_members.end()) { VLOG(1) << __FUNCTION__ << ": ignore invalid attached port " << OBJ_CAST(link); return -EINVAL; } rv = swi->lag_remove_member(it->second, port_id); lag_members.erase(lm_rv); if (nl->is_bridge_interface(bond)) { swi->ofdpa_stg_state_port_set(port_id, "forward"); auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); rv = nl->unset_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } if (lm_rv->second.empty()) remove_l3_address(bond); if (nl->is_bridge_interface(bond)) swi->ofdpa_stg_state_port_set(port_id, "forward"); #endif return rv; } int nl_bond::update_lag_member(rtnl_link *old_slave, rtnl_link *new_slave) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(new_slave); int rv; uint8_t new_state; uint8_t old_state; int n_master_id = rtnl_link_get_master(new_slave); int o_master_id = rtnl_link_get_master(old_slave); auto new_master = nl->get_link(n_master_id, AF_UNSPEC); auto old_master = nl->get_link(o_master_id, AF_UNSPEC); auto port_id = nl->get_port_id(new_slave); if (old_master != new_master || new_master == 0) { return -EINVAL; } rv = rtnl_link_bond_slave_get_state(new_slave, &new_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rtnl_link_bond_slave_get_state(old_slave, &old_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rv = swi->lag_set_member_active(nl->get_port_id(new_master), port_id, new_state == 0); #endif return 0; } int nl_bond::add_l3_address(rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(link); std::deque<rtnl_addr *> addresses; nl->get_l3_addrs(link, &addresses); for (auto i : addresses) { LOG(INFO) << __FUNCTION__ << ": adding address=" << OBJ_CAST(i); rv = nl->add_l3_addr(i); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ":failed to add l3 address " << OBJ_CAST(i) << " to " << OBJ_CAST(link); } LOG(INFO) << __FUNCTION__ << ": added l3 addresses to bond " << OBJ_CAST(link); #endif return rv; } int nl_bond::remove_l3_address(rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(link); std::deque<rtnl_addr *> addresses; nl->get_l3_addrs(link, &addresses); for (auto i : addresses) { rv = nl->del_l3_addr(i); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ":failed to remove l3 address from " << OBJ_CAST(link); } #endif return rv; } } // namespace basebox <commit_msg>nl_bond: update configured vlans when changing bond members<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nl_bond.h" #include <cassert> #include <glog/logging.h> #include <linux/if_bridge.h> #include <netlink/route/link.h> #include <netlink/route/link/bonding.h> #include "cnetlink.h" #include "nl_output.h" #include "sai.h" namespace basebox { nl_bond::nl_bond(cnetlink *nl) : swi(nullptr), nl(nl) {} void nl_bond::clear() noexcept { lag_members.clear(); ifi2lag.clear(); } uint32_t nl_bond::get_lag_id(rtnl_link *bond) { assert(bond); return get_lag_id(rtnl_link_get_ifindex(bond)); } uint32_t nl_bond::get_lag_id(int ifindex) { auto it = ifi2lag.find(ifindex); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": lag_id not found for if=" << ifindex; return 0; } return it->second; } std::set<uint32_t> nl_bond::get_members(rtnl_link *bond) { auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } return mem_it->second; } std::set<uint32_t> nl_bond::get_members_by_port_id(uint32_t port_id) { auto mem_it = lag_members.find(port_id); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for port_id=" << port_id; return {}; } return mem_it->second; } int nl_bond::update_lag(rtnl_link *old_link, rtnl_link *new_link) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE VLOG(1) << __FUNCTION__ << ": updating bond interface "; int rv = 0; uint8_t o_mode, n_mode; uint32_t lag_id = nl->get_port_id(new_link); if (lag_id == 0) { rv = add_lag(new_link); if (rv < 0) return rv; lag_id = rv; } rv = rtnl_link_bond_get_mode(old_link, &o_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } rv = rtnl_link_bond_get_mode(new_link, &n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } if (o_mode != n_mode) { VLOG(1) << __FUNCTION__ << ": bond mode updated " << static_cast<uint32_t>(n_mode); rv = swi->lag_set_mode(lag_id, n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to set active state for " << OBJ_CAST(new_link); } return 0; } add_l3_address(new_link); #endif return 0; } int nl_bond::add_lag(rtnl_link *bond) { uint32_t lag_id = 0; int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint8_t mode; rtnl_link_bond_get_mode(bond, &mode); assert(bond); rv = swi->lag_create(&lag_id, rtnl_link_get_name(bond), mode); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to create lag for " << OBJ_CAST(bond); return rv; } rv = lag_id; auto rv_emp = ifi2lag.emplace(std::make_pair(rtnl_link_get_ifindex(bond), lag_id)); if (!rv_emp.second) { VLOG(1) << __FUNCTION__ << ": lag exists with lag_id=" << rv_emp.first->second << " for bond " << OBJ_CAST(bond); rv = rv_emp.first->second; if (lag_id != rv_emp.first->second) swi->lag_remove(lag_id); } #endif return rv; } int nl_bond::remove_lag(rtnl_link *bond) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE int rv = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return -ENODEV; } rv = swi->lag_remove(it->second); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to remove lag with lag_id=" << it->second << " for bond " << OBJ_CAST(bond); return rv; } ifi2lag.erase(it); #endif return 0; } int nl_bond::add_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint32_t lag_id; uint8_t state = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": no lag_id found creating new for " << OBJ_CAST(bond); rv = add_lag(bond); if (rv < 0) return rv; lag_id = rv; } else { lag_id = it->second; } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignoring port " << OBJ_CAST(link); return -EINVAL; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { // No ports in lag std::set<uint32_t> members; members.insert(port_id); auto lm_rv = lag_members.emplace(lag_id, members); } else { mem_it->second.insert(port_id); } rv = rtnl_link_bond_slave_get_state(link, &state); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get slave state for " << OBJ_CAST(link); } rv = swi->lag_add_member(lag_id, port_id); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed add member " << port_id; return -EINVAL; } rv = swi->lag_set_member_active(lag_id, port_id, state == 0); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed set active member " << port_id; return -EINVAL; } if (rtnl_link_get_master(bond)) { // check bridge attachement auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); if (br_link) { VLOG(2) << __FUNCTION__ << ": bond was already bridge slave: " << OBJ_CAST(br_link); nl->link_created(br_link); auto new_state = rtnl_link_bridge_get_port_state(br_link); std::string state; switch (new_state) { case BR_STATE_FORWARDING: state = "forward"; break; case BR_STATE_BLOCKING: state = "block"; break; case BR_STATE_DISABLED: state = "disable"; break; case BR_STATE_LISTENING: state = "listen"; break; case BR_STATE_LEARNING: state = "learn"; break; default: VLOG(1) << __FUNCTION__ << ": stp state change not supported"; return rv; } swi->ofdpa_stg_state_port_set(port_id, state); } rv = nl->set_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); for (auto vid : vlans) { swi->ingress_port_vlan_add(port_id, vid, false); swi->egress_port_vlan_add(port_id, vid, false); } } // XXX FIXME check for vlan interfaces // Adding an IP address here will ensure that every slave that is // added will retry to add the address. It will not be written to the // ASIC, but repeated messages will be seen // This should be done in ::add_lag, but for currently unknown reasons // this fails when the lag has no members yet. So keep it here for now. add_l3_address(bond); #endif return rv; } int nl_bond::remove_lag_member(rtnl_link *link) { assert(link); int master_id = rtnl_link_get_master(link); auto master = nl->get_link(master_id, AF_UNSPEC); return remove_lag_member(master, link); } int nl_bond::remove_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(FATAL) << __FUNCTION__ << ": no lag_id found for " << OBJ_CAST(bond); } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignore invalid lag port " << OBJ_CAST(link); return -EINVAL; } auto lm_rv = lag_members.find(it->second); if (lm_rv == lag_members.end()) { VLOG(1) << __FUNCTION__ << ": ignore invalid attached port " << OBJ_CAST(link); return -EINVAL; } rv = swi->lag_remove_member(it->second, port_id); lag_members.erase(lm_rv); if (nl->is_bridge_interface(bond)) { swi->ofdpa_stg_state_port_set(port_id, "forward"); auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); rv = nl->unset_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); if (lm_rv->second.empty()) remove_l3_address(bond); if (nl->is_bridge_interface(bond)) swi->ofdpa_stg_state_port_set(port_id, "forward"); for (auto vid : vlans) { swi->ingress_port_vlan_remove(port_id, vid, false); swi->egress_port_vlan_remove(port_id, vid); } } #endif return rv; } int nl_bond::update_lag_member(rtnl_link *old_slave, rtnl_link *new_slave) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(new_slave); int rv; uint8_t new_state; uint8_t old_state; int n_master_id = rtnl_link_get_master(new_slave); int o_master_id = rtnl_link_get_master(old_slave); auto new_master = nl->get_link(n_master_id, AF_UNSPEC); auto old_master = nl->get_link(o_master_id, AF_UNSPEC); auto port_id = nl->get_port_id(new_slave); if (old_master != new_master || new_master == 0) { return -EINVAL; } rv = rtnl_link_bond_slave_get_state(new_slave, &new_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rtnl_link_bond_slave_get_state(old_slave, &old_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rv = swi->lag_set_member_active(nl->get_port_id(new_master), port_id, new_state == 0); #endif return 0; } int nl_bond::add_l3_address(rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(link); std::deque<rtnl_addr *> addresses; nl->get_l3_addrs(link, &addresses); for (auto i : addresses) { LOG(INFO) << __FUNCTION__ << ": adding address=" << OBJ_CAST(i); rv = nl->add_l3_addr(i); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ":failed to add l3 address " << OBJ_CAST(i) << " to " << OBJ_CAST(link); } LOG(INFO) << __FUNCTION__ << ": added l3 addresses to bond " << OBJ_CAST(link); #endif return rv; } int nl_bond::remove_l3_address(rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(link); std::deque<rtnl_addr *> addresses; nl->get_l3_addrs(link, &addresses); for (auto i : addresses) { rv = nl->del_l3_addr(i); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ":failed to remove l3 address from " << OBJ_CAST(link); } #endif return rv; } } // namespace basebox <|endoftext|>
<commit_before>//============================================================================ // Name : ToolKitTest.cpp // Author : xzl // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <signal.h> #include <unistd.h> #include <iostream> #include "Util/logger.h" #include "Util/util.h" #include "Util/RingBuffer.h" #include "Thread/threadgroup.h" #include <list> using namespace std; using namespace ZL::Util; using namespace ZL::Thread; bool g_bExitRead = false; bool g_bExitWrite = false; RingBuffer<string>::Ptr g_ringBuf(new RingBuffer<string>(48)); void onReadEvent(const string &str){ //读事件模式性 DebugL << str; } void onDetachEvent(){ WarnL; } void doRead(int threadNum){ //主动读模式采用轮训机制 效率比较差,可以加入条件变量机制改造 auto reader = g_ringBuf->attach(); while(!g_bExitRead){ auto ptr = reader->read(); if(ptr){ InfoL << "thread " << threadNum << ":" << *ptr; }else{ InfoL << "thread " << threadNum << ": read nullptr!"; usleep(100 * 1000); } } } void doWrite(){ int i = 0; while(!g_bExitWrite){ g_ringBuf->write(to_string(++i)); usleep(100 * 1000); } } int main() { Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace)); //Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>()); //添加一个读取器 auto ringReader = g_ringBuf->attach(); ringReader->setReadCB([](const string &pkt){ onReadEvent(pkt); }); ringReader->setDetachCB([](){ onDetachEvent(); }); //主动读取线程 thread_group group; for(int i = 0 ;i < 4 ; ++i){ group.create_thread([i](){ doRead(i); }); } //写线程 group.create_thread([](){ doWrite(); }); sleep(1); //写线程退出 g_bExitWrite = true; sleep(1); //释放环形缓冲 g_ringBuf.reset(); sleep(1); g_bExitRead = true; group.join_all(); Logger::Destory(); return 0; } <commit_msg>fixed<commit_after>//============================================================================ // Name : ToolKitTest.cpp // Author : xzl // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <signal.h> #include <unistd.h> #include <iostream> #include "Util/logger.h" #include "Util/util.h" #include "Util/RingBuffer.h" #include "Thread/threadgroup.h" #include <list> using namespace std; using namespace ZL::Util; using namespace ZL::Thread; bool g_bExitRead = false; bool g_bExitWrite = false; RingBuffer<string>::Ptr g_ringBuf(new RingBuffer<string>()); void onReadEvent(const string &str){ //读事件模式性 DebugL << str; } void onDetachEvent(){ WarnL; } void doWrite(){ int i = 0; while(!g_bExitWrite){ g_ringBuf->write(to_string(++i),true); usleep(100 * 1000); } } int main() { Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace)); //Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>()); //添加一个读取器 auto ringReader = g_ringBuf->attach(); ringReader->setReadCB([](const string &pkt){ onReadEvent(pkt); }); ringReader->setDetachCB([](){ onDetachEvent(); }); thread_group group; //写线程 group.create_thread([](){ doWrite(); }); sleep(1); //写线程退出 g_bExitWrite = true; sleep(1); //释放环形缓冲 g_ringBuf.reset(); sleep(1); g_bExitRead = true; group.join_all(); Logger::Destory(); return 0; } <|endoftext|>
<commit_before>#pragma once #include <nlohmann/json.hpp> namespace dai { /// NodeIo informations such as name, type, ... struct NodeIoInfo { enum class Type { MSender, SSender, MReceiver, SReceiver }; std::string group; std::string name; Type type = Type::SReceiver; bool blocking = true; int queueSize = 8; struct Options { bool waitForMessage = false; } options; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(NodeIoInfo::Options, waitForMessage); NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(NodeIoInfo, group, name, type, blocking, queueSize, options); } // namespace dai <commit_msg>Removed 'options' from NodeIoInfo<commit_after>#pragma once #include <nlohmann/json.hpp> namespace dai { /// NodeIo informations such as name, type, ... struct NodeIoInfo { enum class Type { MSender, SSender, MReceiver, SReceiver }; std::string group; std::string name; Type type = Type::SReceiver; bool blocking = true; int queueSize = 8; bool waitForMessage = false; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(NodeIoInfo, group, name, type, blocking, queueSize, waitForMessage); } // namespace dai <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <sstream> #include <Eigen/Dense> #include "gtest/gtest.h" #include "bicycle.h" /* * A and B expected state space matrices generated using dtk.bicycle: * * from dtk.bicycle import * * np.set_printoptions(precision=16) * A, B = benchmark_state_space(*benchmark_matrices(), v=1, g=9.80665) */ namespace { Eigen::Matrix<double, 4, 4> A; Eigen::Matrix<double, 4, 2> B( (Eigen::Matrix<double, 4, 2>() << 0. , 0. , 0. , 0. , 0.0159349789179135, -0.1240920254115741, -0.1240920254115741, 4.3238401808042282).finished() ); std::string output_matrices(Eigen::MatrixXd expected, Eigen::MatrixXd actual) { std::stringstream ss; ss << "expected:\n" << expected << "\nactual:\n" << actual << std::endl; return ss.str(); } } // namespace TEST(StateSpace, ContinuousV1) { model::Bicycle bicycle("benchmark_matrices.txt", 1.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -1.4625257433243051, -0.1055224498056882, -0.330515398992312 , 11.7154748079957685, 28.9264833312917631, 3.6768052333214327, -3.0848655274330694; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } TEST(StateSpace, ContinuousV3) { model::Bicycle bicycle("benchmark_matrices.txt", 3.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -8.5921076477970253, -0.3165673494170646, -0.9915461969769359, 11.7154748079957685, 13.1527626512942426, 11.0304156999642977, -9.2545965822992091; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } TEST(StateSpace, ContinuousV5) { model::Bicycle bicycle("benchmark_matrices.txt", 5.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -22.8512714567424666, -0.5276122490284411, -1.6525769949615603, 11.7154748079957685, -18.3946787087007344, 18.384026166607164 , -15.4243276371653479; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } <commit_msg>Test computation of discrete state space matrices<commit_after>#include <iostream> #include <string> #include <sstream> #include <Eigen/Dense> #include "gtest/gtest.h" #include "bicycle.h" /* * A and B expected state space matrices generated using dtk.bicycle: * * from dtk.bicycle import * * np.set_printoptions(precision=16) * A, B = benchmark_state_space(*benchmark_matrices(), v=1, g=9.80665) * * Ad, Bd generated using scipy.signal * * import scipy.signal as sig * sig.cont2discrete((A, B, np.eye(4), np.zeros((4, 2))), 1/200) */ namespace { const double dt = 1.0/200; Eigen::Matrix<double, 4, 4> A; Eigen::Matrix<double, 4, 2> B( (Eigen::Matrix<double, 4, 2>() << 0. , 0. , 0. , 0. , 0.0159349789179135, -0.1240920254115741, -0.1240920254115741, 4.3238401808042282).finished() ); Eigen::Matrix<double, 4, 4> Ad; Eigen::Matrix<double, 4, 2> Bd; std::string output_matrices(Eigen::MatrixXd expected, Eigen::MatrixXd actual) { std::stringstream ss; ss << "expected:\n" << expected << "\nactual:\n" << actual << std::endl; return ss.str(); } } // namespace TEST(StateSpace, ContinuousV1) { model::Bicycle bicycle("benchmark_matrices.txt", 1.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -1.4625257433243051, -0.1055224498056882, -0.330515398992312 , 11.7154748079957685, 28.9264833312917631, 3.6768052333214327, -3.0848655274330694; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } TEST(StateSpace, ContinuousV3) { model::Bicycle bicycle("benchmark_matrices.txt", 3.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -8.5921076477970253, -0.3165673494170646, -0.9915461969769359, 11.7154748079957685, 13.1527626512942426, 11.0304156999642977, -9.2545965822992091; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } TEST(StateSpace, ContinuousV5) { model::Bicycle bicycle("benchmark_matrices.txt", 5.0); A << 0. , 0. , 1. , 0. , 0. , 0. , 0. , 1. , 9.4865338000460664, -22.8512714567424666, -0.5276122490284411, -1.6525769949615603, 11.7154748079957685, -18.3946787087007344, 18.384026166607164 , -15.4243276371653479; EXPECT_TRUE(bicycle.A().isApprox(A)) << output_matrices(bicycle.A(), A); EXPECT_TRUE(bicycle.B().isApprox(B)) << output_matrices(bicycle.B(), B); } TEST(StateSpace, DiscreteV1) { model::Bicycle bicycle("benchmark_matrices.txt", 1.0, dt); Ad << 1.0001184820643081e+00, -1.8478167519170527e-05, 4.9988533321204658e-03, -4.1402267568149167e-06, 1.4642849817488363e-04, 1.0003596378458957e+00, 4.5963276543359894e-05, 4.9622093457528903e-03, 4.7373286374364838e-02, -7.4307138855974368e-03, 9.9957576800707704e-01, -1.6579041282911602e-03, 5.8570670758658606e-02, 1.4347204345110903e-01, 1.8386655631933688e-02, 9.8503669772459101e-01; Bd << 2.0001145816138571e-07, -1.5807242572795020e-06, -1.5420741274461165e-06, 5.3764780115010109e-05, 8.0170391584997460e-05, -6.3821951352698188e-04, -6.1503818438800187e-04, 2.1450096478647790e-02; EXPECT_TRUE(bicycle.Ad().isApprox(Ad)) << output_matrices(bicycle.Ad(), Ad); EXPECT_TRUE(bicycle.Bd().isApprox(Bd)) << output_matrices(bicycle.Bd(), Bd); } TEST(StateSpace, DiscreteV3) { model::Bicycle bicycle("benchmark_matrices.txt", 3.0, dt); Ad << 1.0001182770323798e+00, -1.0761577382854053e-04, 4.9960146578785398e-03, -1.2376061665969063e-05, 1.4636823146804625e-04, 1.0001599497146791e+00, 1.3595045476592029e-04, 4.8861238841920599e-03, 4.7249870478820497e-02, -4.3089075152114520e-02, 9.9840018880958248e-01, -4.9468596498928336e-03, 5.8532959858267050e-02, 6.3097926791482337e-02, 5.3999308360513393e-02, 9.5480604315894413e-01; Bd << 2.0164212892573775e-07, -1.6395468174733748e-06, -1.5238824775089880e-06, 5.3195920730699685e-05, 8.1147158805629875e-05, -6.7347769059348866e-04, -6.0416264157068470e-04, 2.1109948411569327e-02; EXPECT_TRUE(bicycle.Ad().isApprox(Ad)) << output_matrices(bicycle.Ad(), Ad); EXPECT_TRUE(bicycle.Bd().isApprox(Bd)) << output_matrices(bicycle.Bd(), Bd); } TEST(StateSpace, DiscreteV5) { model::Bicycle bicycle("benchmark_matrices.txt", 5.0, dt); Ad << 1.0001184820643081e+00, -1.8478167519170527e-05, 4.9988533321204658e-03, -4.1402267568149167e-06, 1.4642849817488363e-04, 1.0003596378458957e+00, 4.5963276543359894e-05, 4.9622093457528903e-03, 4.7373286374364838e-02, -7.4307138855974368e-03, 9.9957576800707704e-01, -1.6579041282911602e-03, 5.8570670758658606e-02, 1.4347204345110903e-01, 1.8386655631933688e-02, 9.8503669772459101e-01; Bd << 2.0001145816138571e-07, -1.5807242572795020e-06, -1.5420741274461165e-06, 5.3764780115010109e-05, 8.0170391584997460e-05, -6.3821951352698188e-04, -6.1503818438800187e-04, 2.1450096478647790e-02; Ad << 1.0001180700462438e+00, -2.8474586368268200e-04, 4.9929766799901975e-03, -2.0583494132583435e-05, 1.4630038234223096e-04, 9.9976730145466564e-01, 2.2402776466154753e-04, 4.8110697443882302e-03, 4.7124896630597990e-02, -1.1371723873036946e-01, 9.9710530689603383e-01, -8.2185377039953947e-03, 5.8489213351501479e-02, -9.3617401457300686e-02, 8.8474932659789590e-02, 9.2518956230185589e-01; Bd << 2.0326445533610386e-07, -1.6981861891088082e-06, -1.5058897428593093e-06, 5.2632958211780904e-05, 8.2117225610236940e-05, -7.0858832804455301e-04, -5.9344551127057076e-04, 2.0774496614372077e-02; EXPECT_TRUE(bicycle.Ad().isApprox(Ad)) << output_matrices(bicycle.Ad(), Ad); EXPECT_TRUE(bicycle.Bd().isApprox(Bd)) << output_matrices(bicycle.Bd(), Bd); } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER 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. */ #ifndef TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #define TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_id.hpp" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/config.hpp" namespace libtorrent { struct http_connection; class entry; class http_parser; class connection_queue; class session_settings; class TORRENT_EXPORT http_tracker_connection : public tracker_connection { friend class tracker_manager; public: http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& password = ""); void close(); private: boost::intrusive_ptr<http_tracker_connection> self() { return boost::intrusive_ptr<http_tracker_connection>(this); } void on_response(asio::error_code const& ec, http_parser const& parser , char const* data, int size); virtual void on_timeout() {} void parse(int status_code, const entry& e); bool extract_peer_info(const entry& e, peer_entry& ret); tracker_manager& m_man; boost::shared_ptr<http_connection> m_tracker_connection; }; } #endif // TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED <commit_msg>silence msvc warning<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER 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. */ #ifndef TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #define TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_id.hpp" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/config.hpp" namespace libtorrent { struct http_connection; class entry; class http_parser; class connection_queue; struct session_settings; class TORRENT_EXPORT http_tracker_connection : public tracker_connection { friend class tracker_manager; public: http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& password = ""); void close(); private: boost::intrusive_ptr<http_tracker_connection> self() { return boost::intrusive_ptr<http_tracker_connection>(this); } void on_response(asio::error_code const& ec, http_parser const& parser , char const* data, int size); virtual void on_timeout() {} void parse(int status_code, const entry& e); bool extract_peer_info(const entry& e, peer_entry& ret); tracker_manager& m_man; boost::shared_ptr<http_connection> m_tracker_connection; }; } #endif // TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED <|endoftext|>
<commit_before>/** @addtogroup Simulation * @{ * \copyright TU Dresden ZIH. All rights reserved. * \authors Martin Flehmig, Marc Hartung, Marcus Walther * \date Nov 2015 */ #ifndef INCLUDE_SIMULATION_OPENMPSIMULATION_HPP_ #define INCLUDE_SIMULATION_OPENMPSIMULATION_HPP_ #include <fmi/AbstractFmu.hpp> #include "Stdafx.hpp" #include "solver/AbstractSolver.hpp" #include "simulation/SerialSimulation.hpp" namespace Simulation { /** * This class represents an OpenMP parallel simulation for shared memory systems. * Several solvers and their associated FMUs can be handled. */ class OpenMPSimulation : public SerialSimulation { public: /** * Create OpenMP simulation from given solvers. * @param solvers */ //OpenMPSimulation(vector<Solver::AbstractSolverSPtr> solvers, const string_type & scheduleKind = "auto"); OpenMPSimulation(const Initialization::SimulationPlan & in, const vector<std::shared_ptr<Solver::ISolver>> & solver); /** * Destructor. Destroys OpenMP simulation object and frees allocates resources. */ virtual ~OpenMPSimulation(); /** * As long as the simulation end time is not reached, this method calls * the solve methods (time integration) for all solvers in parallel. * \remark: OpenMP parallel for loop is used. */ virtual void simulate(); /** * Returns if a simulation is a MPI, OpenMP or Serial simulation * @return string_type One of: {"serial", "openmp", "mpi"} */ virtual string_type getSimulationType() const; private: /** * It is possible to specify the OpenMP loop schedule algorithm. * Possible values are: static, dynamic, guided, auto, runtime. * Default: auto * * Todo: Add the possibility to control schedule value of OpenMP loops through config file and/or command line. */ string_type _scheduleKind; }; } /* namespace Simulation */ #endif /* INCLUDE_SIMULATION_OPENMPSMULATION_HPP_ */ /** * @} */ <commit_msg>Add empty line for better reading<commit_after>/** @addtogroup Simulation * @{ * \copyright TU Dresden ZIH. All rights reserved. * \authors Martin Flehmig, Marc Hartung, Marcus Walther * \date Nov 2015 */ #ifndef INCLUDE_SIMULATION_OPENMPSIMULATION_HPP_ #define INCLUDE_SIMULATION_OPENMPSIMULATION_HPP_ #include <fmi/AbstractFmu.hpp> #include "Stdafx.hpp" #include "solver/AbstractSolver.hpp" #include "simulation/SerialSimulation.hpp" namespace Simulation { /** * This class represents an OpenMP parallel simulation for shared memory systems. * Several solvers and their associated FMUs can be handled. */ class OpenMPSimulation : public SerialSimulation { public: /** * Create OpenMP simulation from given solvers. * @param solvers */ //OpenMPSimulation(vector<Solver::AbstractSolverSPtr> solvers, const string_type & scheduleKind = "auto"); OpenMPSimulation(const Initialization::SimulationPlan & in, const vector<std::shared_ptr<Solver::ISolver>> & solver); /** * Destructor. Destroys OpenMP simulation object and frees allocates resources. */ virtual ~OpenMPSimulation(); /** * As long as the simulation end time is not reached, this method calls * the solve methods (time integration) for all solvers in parallel. * \remark: OpenMP parallel for loop is used. */ virtual void simulate(); /** * Returns if a simulation is a MPI, OpenMP or Serial simulation * @return string_type One of: {"serial", "openmp", "mpi"} */ virtual string_type getSimulationType() const; private: /** * It is possible to specify the OpenMP loop schedule algorithm. * Possible values are: static, dynamic, guided, auto, runtime. * Default: auto * * Todo: Add the possibility to control schedule value of OpenMP loops through config file and/or command line. */ string_type _scheduleKind; }; } /* namespace Simulation */ #endif /* INCLUDE_SIMULATION_OPENMPSMULATION_HPP_ */ /** * @} */ <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #ifndef VAST_COMMAND_HPP #define VAST_COMMAND_HPP #include <functional> #include <memory> #include <string> #include <string_view> #include <caf/actor_system_config.hpp> #include <caf/fwd.hpp> #include <caf/message.hpp> #include <caf/detail/unordered_flat_map.hpp> #include "vast/error.hpp" #include "vast/data.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/data.hpp" #include "vast/detail/steady_map.hpp" #include "vast/detail/string.hpp" namespace vast { /// A top-level command. class command { public: // -- member types ----------------------------------------------------------- /// An option of a command. struct option { template <class T = bool> static std::pair<std::string, option> make(const std::string& tag, std::string desc, T x = {}) { auto s = detail::split_to_str(tag, ","); std::string shortcut; if (s.size() >= 2) shortcut = s[1][0]; return {s[0], {std::move(shortcut), std::move(desc), data{std::forward<T>(x)}}}; } std::string shortcut; std::string description; data value; }; /// Owning pointer to a command. using unique_ptr = std::unique_ptr<command>; /// Group of configuration parameters. using opt_group = caf::actor_system_config::opt_group; /// Maps names of config parameters to their value. using opt_map = std::map<std::string, caf::config_value>; /// Returns a CLI option as name/value pair. using get_opt = std::function<std::pair<std::string, caf::config_value>()>; /// Wraps the result of proceed. enum proceed_result { proceed_ok, stop_successful, stop_with_error }; // -- constructors, destructors, and assignment operators -------------------- command(); command(command* parent, std::string_view name); virtual ~command(); /// Runs the command and blocks until execution completes. /// @returns An exit code suitable for returning from main. int run(caf::actor_system& sys, caf::message args); /// Runs the command and blocks until execution completes. /// @returns An exit code suitable for returning from main. int run(caf::actor_system& sys, opt_map& options, caf::message args); /// Prints usage to `std::cerr`. void usage(); /// Defines a sub-command. /// @param name The name of the command. /// @param desc The description of the command. command& cmd(const std::string& name, std::string desc = ""); /// Parses command line arguments and dispatches the contained command to the /// registered sub-command. /// @param args The command line arguments. void dispatch(const std::vector<std::string>& args) const; /// Retrieves an option value. /// @param x The name of the option. /// @returns The value for *x* or `nullptr` if `x` is not a valid option. const data* get(const std::string& x) const; std::string description; detail::steady_map<std::string, option> options; /// Returns the full name for this command. std::string full_name(); /// Queries whether this command has no parent. bool is_root() const noexcept; inline const std::string_view& name() const noexcept { return name_; } template <class T, class... Ts> T* add(std::string_view name, Ts&&... xs) { auto ptr = std::make_unique<T>(this, name, std::forward<Ts>(xs)...); auto result = ptr.get(); if (!nested_.emplace(name, std::move(ptr)).second) { throw std::invalid_argument("name already exists"); } return result; } template <class T> caf::optional<T> get(const opt_map& xs, const std::string& name) { // Map T to the clostest type in config_value. using cfg_type = typename std::conditional< std::is_integral<T>::value && !std::is_same<bool, T>::value, int64_t, typename std::conditional< std::is_floating_point<T>::value, double, T >::type >::type; auto i = xs.find(name); if (i == xs.end()) return caf::none; auto result = caf::get_if<cfg_type>(&i->second); if (!result) return caf::none; return static_cast<T>(*result); } template <class T> T get_or(const opt_map& xs, const std::string& name, T fallback) { auto result = get<T>(xs, name); if (!result) return fallback; return *result; } protected: /// Checks whether a command is ready to proceed, i.e., whether the /// configuration allows for calling `run_impl` or `run` on a nested command. virtual proceed_result proceed(caf::actor_system& sys, opt_map& options, caf::message args); virtual int run_impl(caf::actor_system& sys, opt_map& options, caf::message args); template <class T> void add_opt(std::string name, std::string descr, T& ref) { opts_.emplace_back(name, std::move(descr), ref); // Extract the long name from the full name (format: "long,l"). auto pos = name.find_first_of(','); if (pos < name.size()) name.resize(pos); get_opts_.emplace_back([name = std::move(name), &ref] { // Map T to the clostest type in config_value. using cfg_type = typename std::conditional< std::is_integral<T>::value && !std::is_same<bool, T>::value, int64_t, typename std::conditional< std::is_floating_point<T>::value, double, T >::type >::type; cfg_type copy = ref; return std::make_pair(name, caf::config_value{std::move(copy)}); }); } private: /// Separates arguments into the arguments for the current command, the name /// of the subcommand, and the arguments for the subcommand. std::tuple<caf::message, std::string, caf::message> separate_args(const caf::message& args); caf::detail::unordered_flat_map<std::string_view, unique_ptr> nested_; command* parent_; std::string_view name_; std::vector<caf::message::cli_arg> opts_; std::vector<get_opt> get_opts_; }; } // namespace vast #endif <commit_msg>Add command::root convenience function<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #ifndef VAST_COMMAND_HPP #define VAST_COMMAND_HPP #include <functional> #include <memory> #include <string> #include <string_view> #include <caf/actor_system_config.hpp> #include <caf/fwd.hpp> #include <caf/message.hpp> #include <caf/detail/unordered_flat_map.hpp> #include "vast/error.hpp" #include "vast/data.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/data.hpp" #include "vast/detail/steady_map.hpp" #include "vast/detail/string.hpp" namespace vast { /// A top-level command. class command { public: // -- member types ----------------------------------------------------------- /// An option of a command. struct option { template <class T = bool> static std::pair<std::string, option> make(const std::string& tag, std::string desc, T x = {}) { auto s = detail::split_to_str(tag, ","); std::string shortcut; if (s.size() >= 2) shortcut = s[1][0]; return {s[0], {std::move(shortcut), std::move(desc), data{std::forward<T>(x)}}}; } std::string shortcut; std::string description; data value; }; /// Owning pointer to a command. using unique_ptr = std::unique_ptr<command>; /// Group of configuration parameters. using opt_group = caf::actor_system_config::opt_group; /// Maps names of config parameters to their value. using opt_map = std::map<std::string, caf::config_value>; /// Returns a CLI option as name/value pair. using get_opt = std::function<std::pair<std::string, caf::config_value>()>; /// Wraps the result of proceed. enum proceed_result { proceed_ok, stop_successful, stop_with_error }; // -- constructors, destructors, and assignment operators -------------------- command(); command(command* parent, std::string_view name); virtual ~command(); /// Runs the command and blocks until execution completes. /// @returns An exit code suitable for returning from main. int run(caf::actor_system& sys, caf::message args); /// Runs the command and blocks until execution completes. /// @returns An exit code suitable for returning from main. int run(caf::actor_system& sys, opt_map& options, caf::message args); /// Prints usage to `std::cerr`. void usage(); /// Defines a sub-command. /// @param name The name of the command. /// @param desc The description of the command. command& cmd(const std::string& name, std::string desc = ""); /// Parses command line arguments and dispatches the contained command to the /// registered sub-command. /// @param args The command line arguments. void dispatch(const std::vector<std::string>& args) const; /// Retrieves an option value. /// @param x The name of the option. /// @returns The value for *x* or `nullptr` if `x` is not a valid option. const data* get(const std::string& x) const; std::string description; detail::steady_map<std::string, option> options; /// Returns the full name for this command. std::string full_name(); /// Queries whether this command has no parent. bool is_root() const noexcept; /// Queries whether this command has no parent. command& root() noexcept { return is_root() ? *this : parent_->root(); } inline const std::string_view& name() const noexcept { return name_; } template <class T, class... Ts> T* add(std::string_view name, Ts&&... xs) { auto ptr = std::make_unique<T>(this, name, std::forward<Ts>(xs)...); auto result = ptr.get(); if (!nested_.emplace(name, std::move(ptr)).second) { throw std::invalid_argument("name already exists"); } return result; } template <class T> caf::optional<T> get(const opt_map& xs, const std::string& name) { // Map T to the clostest type in config_value. using cfg_type = typename std::conditional< std::is_integral<T>::value && !std::is_same<bool, T>::value, int64_t, typename std::conditional< std::is_floating_point<T>::value, double, T >::type >::type; auto i = xs.find(name); if (i == xs.end()) return caf::none; auto result = caf::get_if<cfg_type>(&i->second); if (!result) return caf::none; return static_cast<T>(*result); } template <class T> T get_or(const opt_map& xs, const std::string& name, T fallback) { auto result = get<T>(xs, name); if (!result) return fallback; return *result; } protected: /// Checks whether a command is ready to proceed, i.e., whether the /// configuration allows for calling `run_impl` or `run` on a nested command. virtual proceed_result proceed(caf::actor_system& sys, opt_map& options, caf::message args); virtual int run_impl(caf::actor_system& sys, opt_map& options, caf::message args); template <class T> void add_opt(std::string name, std::string descr, T& ref) { opts_.emplace_back(name, std::move(descr), ref); // Extract the long name from the full name (format: "long,l"). auto pos = name.find_first_of(','); if (pos < name.size()) name.resize(pos); get_opts_.emplace_back([name = std::move(name), &ref] { // Map T to the clostest type in config_value. using cfg_type = typename std::conditional< std::is_integral<T>::value && !std::is_same<bool, T>::value, int64_t, typename std::conditional< std::is_floating_point<T>::value, double, T >::type >::type; cfg_type copy = ref; return std::make_pair(name, caf::config_value{std::move(copy)}); }); } private: /// Separates arguments into the arguments for the current command, the name /// of the subcommand, and the arguments for the subcommand. std::tuple<caf::message, std::string, caf::message> separate_args(const caf::message& args); caf::detail::unordered_flat_map<std::string_view, unique_ptr> nested_; command* parent_; std::string_view name_; std::vector<caf::message::cli_arg> opts_; std::vector<get_opt> get_opts_; }; } // namespace vast #endif <|endoftext|>
<commit_before>//============================================================================ //==== Titre: Standard_ErrorHandler.cxx //==== Role : class "Standard_ErrorHandler" implementation. //============================================================================ #include <Standard_ErrorHandler.hxx> #include <Standard_Failure.hxx> #include <Standard_ErrorHandlerCallback.hxx> #include <Standard_Mutex.hxx> #include <Standard.hxx> #ifndef WNT #include <pthread.h> #else #include <windows.h> #endif // =========================================================================== // The class "Standard_ErrorHandler" variables // =========================================================================== // During [sig]setjmp()/[sig]longjmp() K_SETJMP is non zero (try) // So if there is an abort request and if K_SETJMP is non zero, the abort // request will be ignored. If the abort request do a raise during a setjmp // or a longjmp, there will be a "terminating SEGV" impossible to handle. //==== The top of the Errors Stack =========================================== static Standard_ErrorHandler* Top = 0; // A mutex to protect from concurrent access to Top // Note that we should NOT use Sentry while in this class, as Sentry // would register mutex as callback in the current exception handler static Standard_Mutex theMutex; static inline Standard_ThreadId GetThreadID() { #ifndef WNT return pthread_self(); #else return GetCurrentThreadId(); #endif } //============================================================================ //==== Constructor : Create a ErrorHandler structure. And add it at the //==== 'Top' of "ErrorHandler's stack". //============================================================================ Standard_ErrorHandler::Standard_ErrorHandler () : myStatus(Standard_HandlerVoid), myCallbackPtr(0) { myThread = GetThreadID(); if (Standard::IsReentrant()) theMutex.Lock(); myPrevious = Top; Top = this; if (Standard::IsReentrant()) theMutex.Unlock(); } //============================================================================ //==== Destructor : Delete the ErrorHandler and Abort if there is a 'Error'. //============================================================================ void Standard_ErrorHandler::Destroy() { Unlink(); if(myStatus==Standard_HandlerJumped) { //jumped, but not caut Abort(); } } //======================================================================= //function : Unlink //purpose : //======================================================================= void Standard_ErrorHandler::Unlink() { // put a lock on the stack if (Standard::IsReentrant()) theMutex.Lock(); Standard_ErrorHandler* aPrevious = 0; Standard_ErrorHandler* aCurrent = Top; // locate this handler in the stack while(aCurrent!=0 && this!=aCurrent) { aPrevious = aCurrent; aCurrent = aCurrent->myPrevious; } if(aCurrent==0) { if (Standard::IsReentrant()) theMutex.Unlock(); return; } if(aPrevious==0) { // a top exception taken Top = aCurrent->myPrevious; } else { aPrevious->myPrevious=aCurrent->myPrevious; } myPrevious = 0; if (Standard::IsReentrant()) theMutex.Unlock(); // unlink and destroy all registered callbacks Standard_Address aPtr = aCurrent->myCallbackPtr; myCallbackPtr = 0; while ( aPtr ) { Standard_ErrorHandlerCallback* aCallback = (Standard_ErrorHandlerCallback*)aPtr; aPtr = aCallback->myNext; // Call destructor explicitly, as we know that it will not be called automatically aCallback->DestroyCallback(); } } //======================================================================= //function : IsInTryBlock //purpose : test if the code is currently running in //======================================================================= Standard_Boolean Standard_ErrorHandler::IsInTryBlock() { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_False); return anActive != NULL && anActive->myLabel != NULL; } //============================================================================ //==== Abort: make a longjmp to the saved Context. //==== Abort if there is a non null 'Error' //============================================================================ void Standard_ErrorHandler::Abort () { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_True); //==== Check if can do the "longjmp" ======================================= if(anActive == NULL || anActive->myLabel == NULL) { cerr << "*** Abort *** an exception was raised, but no catch was found." << endl; Handle(Standard_Failure) anErr = ( anActive != NULL && ! anActive->myCaughtError.IsNull() ? anActive->myCaughtError : Standard_Failure::Caught() ); if ( ! anErr.IsNull() ) cerr << "\t... The exception is:" << anErr->GetMessageString() << endl; exit(1); } anActive->myStatus = Standard_HandlerJumped; longjmp(anActive->myLabel, Standard_True); } //============================================================================ //==== Catches: If there is a 'Error', and it is in good type //==== returns True and clean 'Error', else returns False. //============================================================================ Standard_Boolean Standard_ErrorHandler::Catches (const Handle(Standard_Type)& AType) { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerJumped, Standard_False); if(anActive==0) return Standard_False; if(anActive->myCaughtError.IsNull()) return Standard_False; if(anActive->myCaughtError->IsKind(AType)){ myStatus=Standard_HandlerProcessed; return Standard_True; } else { return Standard_False; } } Handle(Standard_Failure) Standard_ErrorHandler::LastCaughtError() { Handle(Standard_Failure) aHandle; Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerProcessed, Standard_False); if(anActive!=0) aHandle = anActive->myCaughtError; return aHandle; } Handle(Standard_Failure) Standard_ErrorHandler::Error() const { return myCaughtError; } void Standard_ErrorHandler::Error(const Handle(Standard_Failure)& aError) { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_False); if(anActive==0) Abort(); anActive->myCaughtError = aError; } Standard_ErrorHandler* Standard_ErrorHandler::FindHandler(const Standard_HandlerStatus theStatus, const Standard_Boolean theUnlink) { // lock the stack if (Standard::IsReentrant()) theMutex.Lock(); // Find the current ErrorHandler Accordin tread Standard_ErrorHandler* aPrevious = 0; Standard_ErrorHandler* aCurrent = Top; Standard_ErrorHandler* anActive = 0; Standard_Boolean aStop = Standard_False; Standard_ThreadId aTreadId = GetThreadID(); // searching an exception with correct ID number // which is not processed for the moment while(!aStop) { while(aCurrent!=NULL && aTreadId!=aCurrent->myThread) { aPrevious = aCurrent; aCurrent = aCurrent->myPrevious; } if(aCurrent!=NULL) { if(theStatus!=aCurrent->myStatus) { if(theUnlink) { //unlink current if(aPrevious==0) { // a top exception taken Top = aCurrent->myPrevious; } else { aPrevious->myPrevious=aCurrent->myPrevious; } } //shift aCurrent = aCurrent->myPrevious; } else { //found one anActive = aCurrent; aStop = Standard_True; } } else { //Current is NULL, means that no handlesr aStop = Standard_True; } } if (Standard::IsReentrant()) theMutex.Unlock(); return anActive; } <commit_msg>Move code to work around a BCC bug<commit_after>//============================================================================ //==== Titre: Standard_ErrorHandler.cxx //==== Role : class "Standard_ErrorHandler" implementation. //============================================================================ #include <Standard_ErrorHandler.hxx> #include <Standard_Failure.hxx> #include <Standard_ErrorHandlerCallback.hxx> #include <Standard_Mutex.hxx> #include <Standard.hxx> #ifndef WNT #include <pthread.h> #else #include <windows.h> #endif // =========================================================================== // The class "Standard_ErrorHandler" variables // =========================================================================== // During [sig]setjmp()/[sig]longjmp() K_SETJMP is non zero (try) // So if there is an abort request and if K_SETJMP is non zero, the abort // request will be ignored. If the abort request do a raise during a setjmp // or a longjmp, there will be a "terminating SEGV" impossible to handle. //Somehow borland needs this inline global function to be declared first ... ?? static inline Standard_ThreadId GetThreadID() { #ifndef WNT return pthread_self(); #else return GetCurrentThreadId(); #endif } //==== The top of the Errors Stack =========================================== static Standard_ErrorHandler* Top = 0; // A mutex to protect from concurrent access to Top // Note that we should NOT use Sentry while in this class, as Sentry // would register mutex as callback in the current exception handler static Standard_Mutex theMutex; //============================================================================ //==== Constructor : Create a ErrorHandler structure. And add it at the //==== 'Top' of "ErrorHandler's stack". //============================================================================ Standard_ErrorHandler::Standard_ErrorHandler () : myStatus(Standard_HandlerVoid), myCallbackPtr(0) { myThread = GetThreadID(); if (Standard::IsReentrant()) theMutex.Lock(); myPrevious = Top; Top = this; if (Standard::IsReentrant()) theMutex.Unlock(); } //============================================================================ //==== Destructor : Delete the ErrorHandler and Abort if there is a 'Error'. //============================================================================ void Standard_ErrorHandler::Destroy() { Unlink(); if(myStatus==Standard_HandlerJumped) { //jumped, but not caut Abort(); } } //======================================================================= //function : Unlink //purpose : //======================================================================= void Standard_ErrorHandler::Unlink() { // put a lock on the stack if (Standard::IsReentrant()) theMutex.Lock(); Standard_ErrorHandler* aPrevious = 0; Standard_ErrorHandler* aCurrent = Top; // locate this handler in the stack while(aCurrent!=0 && this!=aCurrent) { aPrevious = aCurrent; aCurrent = aCurrent->myPrevious; } if(aCurrent==0) { if (Standard::IsReentrant()) theMutex.Unlock(); return; } if(aPrevious==0) { // a top exception taken Top = aCurrent->myPrevious; } else { aPrevious->myPrevious=aCurrent->myPrevious; } myPrevious = 0; if (Standard::IsReentrant()) theMutex.Unlock(); // unlink and destroy all registered callbacks Standard_Address aPtr = aCurrent->myCallbackPtr; myCallbackPtr = 0; while ( aPtr ) { Standard_ErrorHandlerCallback* aCallback = (Standard_ErrorHandlerCallback*)aPtr; aPtr = aCallback->myNext; // Call destructor explicitly, as we know that it will not be called automatically aCallback->DestroyCallback(); } } //======================================================================= //function : IsInTryBlock //purpose : test if the code is currently running in //======================================================================= Standard_Boolean Standard_ErrorHandler::IsInTryBlock() { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_False); return anActive != NULL && anActive->myLabel != NULL; } //============================================================================ //==== Abort: make a longjmp to the saved Context. //==== Abort if there is a non null 'Error' //============================================================================ void Standard_ErrorHandler::Abort () { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_True); //==== Check if can do the "longjmp" ======================================= if(anActive == NULL || anActive->myLabel == NULL) { cerr << "*** Abort *** an exception was raised, but no catch was found." << endl; Handle(Standard_Failure) anErr = ( anActive != NULL && ! anActive->myCaughtError.IsNull() ? anActive->myCaughtError : Standard_Failure::Caught() ); if ( ! anErr.IsNull() ) cerr << "\t... The exception is:" << anErr->GetMessageString() << endl; exit(1); } anActive->myStatus = Standard_HandlerJumped; longjmp(anActive->myLabel, Standard_True); } //============================================================================ //==== Catches: If there is a 'Error', and it is in good type //==== returns True and clean 'Error', else returns False. //============================================================================ Standard_Boolean Standard_ErrorHandler::Catches (const Handle(Standard_Type)& AType) { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerJumped, Standard_False); if(anActive==0) return Standard_False; if(anActive->myCaughtError.IsNull()) return Standard_False; if(anActive->myCaughtError->IsKind(AType)){ myStatus=Standard_HandlerProcessed; return Standard_True; } else { return Standard_False; } } Handle(Standard_Failure) Standard_ErrorHandler::LastCaughtError() { Handle(Standard_Failure) aHandle; Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerProcessed, Standard_False); if(anActive!=0) aHandle = anActive->myCaughtError; return aHandle; } Handle(Standard_Failure) Standard_ErrorHandler::Error() const { return myCaughtError; } void Standard_ErrorHandler::Error(const Handle(Standard_Failure)& aError) { Standard_ErrorHandler* anActive = FindHandler(Standard_HandlerVoid, Standard_False); if(anActive==0) Abort(); anActive->myCaughtError = aError; } Standard_ErrorHandler* Standard_ErrorHandler::FindHandler(const Standard_HandlerStatus theStatus, const Standard_Boolean theUnlink) { // lock the stack if (Standard::IsReentrant()) theMutex.Lock(); // Find the current ErrorHandler Accordin tread Standard_ErrorHandler* aPrevious = 0; Standard_ErrorHandler* aCurrent = Top; Standard_ErrorHandler* anActive = 0; Standard_Boolean aStop = Standard_False; Standard_ThreadId aTreadId = GetThreadID(); // searching an exception with correct ID number // which is not processed for the moment while(!aStop) { while(aCurrent!=NULL && aTreadId!=aCurrent->myThread) { aPrevious = aCurrent; aCurrent = aCurrent->myPrevious; } if(aCurrent!=NULL) { if(theStatus!=aCurrent->myStatus) { if(theUnlink) { //unlink current if(aPrevious==0) { // a top exception taken Top = aCurrent->myPrevious; } else { aPrevious->myPrevious=aCurrent->myPrevious; } } //shift aCurrent = aCurrent->myPrevious; } else { //found one anActive = aCurrent; aStop = Standard_True; } } else { //Current is NULL, means that no handlesr aStop = Standard_True; } } if (Standard::IsReentrant()) theMutex.Unlock(); return anActive; } <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole_api.h" #include "async.h" #include <thread> #include <atomic> #include <unordered_map> #include <condition_variable> #include <mutex> #include <queue> using namespace std; typedef swAio_event async_event; swAsyncIO SwooleAIO; static void swAio_free(void *private_data); int swAio_callback(swReactor *reactor, swEvent *_event) { int i; async_event *events[SW_AIO_EVENT_NUM]; ssize_t n = read(_event->fd, events, sizeof(async_event*) * SW_AIO_EVENT_NUM); if (n < 0) { swSysWarn("read() failed"); return SW_ERR; } for (i = 0; i < n / (int) sizeof(async_event*); i++) { if (!events[i]->canceled) { events[i]->callback(events[i]); } SwooleAIO.task_num--; delete events[i]; } return SW_OK; } struct thread_context { thread *_thread; atomic<bool> *_exit_flag; thread_context(thread *_thread, atomic<bool> *_exit_flag) : _thread(_thread), _exit_flag(_exit_flag) { } }; class async_event_queue { public: inline bool push(async_event *event) { unique_lock<mutex> lock(_mutex); _queue.push(event); return true; } inline async_event* pop() { unique_lock<mutex> lock(_mutex); if (_queue.empty()) { return nullptr; } async_event* retval = _queue.front(); _queue.pop(); return retval; } inline bool empty() { unique_lock<mutex> lock(_mutex); return _queue.empty(); } inline size_t count() { return _queue.size(); } private: queue<async_event*> _queue; mutex _mutex; }; class async_thread_pool { public: async_thread_pool(size_t _min_threads, size_t _max_threads) { n_waiting = 0; running = false; min_threads = _min_threads; max_threads = _max_threads; current_task_id = 0; current_pid = getpid(); if (swPipeBase_create(&_aio_pipe, 0) < 0) { swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL); } _pipe_read = _aio_pipe.getFd(&_aio_pipe, 0); _pipe_write = _aio_pipe.getFd(&_aio_pipe, 1); swoole_event_add(_pipe_read, SW_EVENT_READ, SW_FD_AIO); } ~async_thread_pool() { shutdown(); if (SwooleTG.reactor) { swoole_event_del(_pipe_read); } _aio_pipe.close(&_aio_pipe); } void schedule() { //++ if (n_waiting == 0 && threads.size() < max_threads) { create_thread(); } //-- else if (n_waiting > min_threads) { thread_context *tc = &threads.front(); *tc->_exit_flag = false; tc->_thread->detach(); delete tc->_thread; threads.pop(); } } bool start() { running = true; for (size_t i = 0; i < min_threads; i++) { create_thread(); } return true; } bool shutdown() { if (!running) { return false; } running = false; _mutex.lock(); _cv.notify_all(); _mutex.unlock(); while (!threads.empty()) { thread_context *tc = &threads.front(); if (tc->_thread->joinable()) { tc->_thread->join(); } threads.pop(); } return true; } async_event* dispatch(const async_event *request) { auto _event_copy = new async_event(*request); schedule(); _event_copy->task_id = current_task_id++; _queue.push(_event_copy); _cv.notify_one(); return _event_copy; } inline size_t thread_count() { return threads.size(); } inline size_t queue_count() { return _queue.count(); } pid_t current_pid; private: void create_thread() { atomic<bool> *exit_flag = new atomic<bool>(false); try { thread *_thread = new thread([this, &exit_flag]() { SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE); if (SwooleTG.buffer_stack == nullptr) { return; } swSignal_none(); while (running) { async_event *event; event = _queue.pop(); if (event) { if (sw_unlikely(event->handler == nullptr)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else if (sw_unlikely(event->canceled)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else { event->handler(event); } swTrace("aio_thread ok. ret=%d, error=%d", event->ret, event->error); _error: while (true) { SwooleAIO.lock.lock(&SwooleAIO.lock); int ret = write(_pipe_write, &event, sizeof(event)); SwooleAIO.lock.unlock(&SwooleAIO.lock); if (ret < 0) { if (errno == EAGAIN) { swSocket_wait(_pipe_write, 1000, SW_EVENT_WRITE); continue; } else if (errno == EINTR) { continue; } else { swSysWarn("sendto swoole_aio_pipe_write failed"); } } break; } // exit if (*exit_flag) { break; } } else { unique_lock<mutex> lock(_mutex); if (running) { ++n_waiting; _cv.wait(lock); --n_waiting; } } } delete exit_flag; }); threads.push(thread_context(_thread, exit_flag)); } catch (const std::system_error& e) { swSysNotice("create aio thread failed, please check your system configuration or adjust max_thread_count"); delete exit_flag; return; } } size_t min_threads; size_t max_threads; swPipe _aio_pipe; int _pipe_read; int _pipe_write; int current_task_id; queue<thread_context> threads; async_event_queue _queue; bool running; atomic<int> n_waiting; mutex _mutex; condition_variable _cv; }; static async_thread_pool *pool = nullptr; static int swAio_init() { if (SwooleAIO.init) { swWarn("AIO has already been initialized"); return SW_ERR; } if (!SwooleTG.reactor) { swWarn("no event loop, cannot initialized"); return SW_ERR; } if (swMutex_create(&SwooleAIO.lock, 0) < 0) { swWarn("create mutex lock error"); return SW_ERR; } if (SwooleAIO.min_thread_num == 0) { SwooleAIO.min_thread_num = SW_AIO_THREAD_DEFAULT_NUM; } if (SwooleAIO.max_thread_num == 0) { SwooleAIO.max_thread_num = (SW_CPU_NUM * 2) * SW_AIO_THREAD_NUM_MULTIPLE; } if (SwooleAIO.min_thread_num > SwooleAIO.max_thread_num) { SwooleAIO.max_thread_num = SwooleAIO.min_thread_num; } swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr); pool = new async_thread_pool(SwooleAIO.min_thread_num, SwooleAIO.max_thread_num); pool->start(); SwooleAIO.init = 1; return SW_OK; } size_t swAio_thread_count() { return pool ? pool->thread_count() : 0; } int swAio_dispatch(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; async_event *event = pool->dispatch(request); return event->task_id; } swAio_event* swAio_dispatch2(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; return pool->dispatch(request); } static void swAio_free(void *private_data) { if (!SwooleAIO.init) { return; } if (pool->current_pid == getpid()) { delete pool; } pool = nullptr; SwooleAIO.init = 0; } <commit_msg>Fix warning<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole_api.h" #include "async.h" #include <thread> #include <atomic> #include <unordered_map> #include <condition_variable> #include <mutex> #include <queue> using namespace std; typedef swAio_event async_event; swAsyncIO SwooleAIO; static void swAio_free(void *private_data); int swAio_callback(swReactor *reactor, swEvent *_event) { async_event *events[SW_AIO_EVENT_NUM]; ssize_t n = read(_event->fd, events, sizeof(async_event*) * SW_AIO_EVENT_NUM); if (n < 0) { swSysWarn("read() failed"); return SW_ERR; } for (size_t i = 0; i < n / sizeof(async_event *); i++) { if (!events[i]->canceled) { events[i]->callback(events[i]); } SwooleAIO.task_num--; delete events[i]; } return SW_OK; } struct thread_context { thread *_thread; atomic<bool> *_exit_flag; thread_context(thread *_thread, atomic<bool> *_exit_flag) : _thread(_thread), _exit_flag(_exit_flag) { } }; class async_event_queue { public: inline bool push(async_event *event) { unique_lock<mutex> lock(_mutex); _queue.push(event); return true; } inline async_event* pop() { unique_lock<mutex> lock(_mutex); if (_queue.empty()) { return nullptr; } async_event* retval = _queue.front(); _queue.pop(); return retval; } inline bool empty() { unique_lock<mutex> lock(_mutex); return _queue.empty(); } inline size_t count() { return _queue.size(); } private: queue<async_event*> _queue; mutex _mutex; }; class async_thread_pool { public: async_thread_pool(size_t _min_threads, size_t _max_threads) { n_waiting = 0; running = false; min_threads = _min_threads; max_threads = _max_threads; current_task_id = 0; current_pid = getpid(); if (swPipeBase_create(&_aio_pipe, 0) < 0) { swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL); } _pipe_read = _aio_pipe.getFd(&_aio_pipe, 0); _pipe_write = _aio_pipe.getFd(&_aio_pipe, 1); swoole_event_add(_pipe_read, SW_EVENT_READ, SW_FD_AIO); } ~async_thread_pool() { shutdown(); if (SwooleTG.reactor) { swoole_event_del(_pipe_read); } _aio_pipe.close(&_aio_pipe); } void schedule() { //++ if (n_waiting == 0 && threads.size() < max_threads) { create_thread(); } //-- else if (n_waiting > min_threads) { thread_context *tc = &threads.front(); *tc->_exit_flag = false; tc->_thread->detach(); delete tc->_thread; threads.pop(); } } bool start() { running = true; for (size_t i = 0; i < min_threads; i++) { create_thread(); } return true; } bool shutdown() { if (!running) { return false; } running = false; _mutex.lock(); _cv.notify_all(); _mutex.unlock(); while (!threads.empty()) { thread_context *tc = &threads.front(); if (tc->_thread->joinable()) { tc->_thread->join(); } threads.pop(); } return true; } async_event* dispatch(const async_event *request) { auto _event_copy = new async_event(*request); schedule(); _event_copy->task_id = current_task_id++; _queue.push(_event_copy); _cv.notify_one(); return _event_copy; } inline size_t thread_count() { return threads.size(); } inline size_t queue_count() { return _queue.count(); } pid_t current_pid; private: void create_thread() { atomic<bool> *exit_flag = new atomic<bool>(false); try { thread *_thread = new thread([this, &exit_flag]() { SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE); if (SwooleTG.buffer_stack == nullptr) { return; } swSignal_none(); while (running) { async_event *event; event = _queue.pop(); if (event) { if (sw_unlikely(event->handler == nullptr)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else if (sw_unlikely(event->canceled)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else { event->handler(event); } swTrace("aio_thread ok. ret=%d, error=%d", event->ret, event->error); _error: while (true) { SwooleAIO.lock.lock(&SwooleAIO.lock); int ret = write(_pipe_write, &event, sizeof(event)); SwooleAIO.lock.unlock(&SwooleAIO.lock); if (ret < 0) { if (errno == EAGAIN) { swSocket_wait(_pipe_write, 1000, SW_EVENT_WRITE); continue; } else if (errno == EINTR) { continue; } else { swSysWarn("sendto swoole_aio_pipe_write failed"); } } break; } // exit if (*exit_flag) { break; } } else { unique_lock<mutex> lock(_mutex); if (running) { ++n_waiting; _cv.wait(lock); --n_waiting; } } } delete exit_flag; }); threads.push(thread_context(_thread, exit_flag)); } catch (const std::system_error& e) { swSysNotice("create aio thread failed, please check your system configuration or adjust max_thread_count"); delete exit_flag; return; } } size_t min_threads; size_t max_threads; swPipe _aio_pipe; int _pipe_read; int _pipe_write; int current_task_id; queue<thread_context> threads; async_event_queue _queue; bool running; atomic<size_t> n_waiting; mutex _mutex; condition_variable _cv; }; static async_thread_pool *pool = nullptr; static int swAio_init() { if (SwooleAIO.init) { swWarn("AIO has already been initialized"); return SW_ERR; } if (!SwooleTG.reactor) { swWarn("no event loop, cannot initialized"); return SW_ERR; } if (swMutex_create(&SwooleAIO.lock, 0) < 0) { swWarn("create mutex lock error"); return SW_ERR; } if (SwooleAIO.min_thread_num == 0) { SwooleAIO.min_thread_num = SW_AIO_THREAD_DEFAULT_NUM; } if (SwooleAIO.max_thread_num == 0) { SwooleAIO.max_thread_num = (SW_CPU_NUM * 2) * SW_AIO_THREAD_NUM_MULTIPLE; } if (SwooleAIO.min_thread_num > SwooleAIO.max_thread_num) { SwooleAIO.max_thread_num = SwooleAIO.min_thread_num; } swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr); pool = new async_thread_pool(SwooleAIO.min_thread_num, SwooleAIO.max_thread_num); pool->start(); SwooleAIO.init = 1; return SW_OK; } size_t swAio_thread_count() { return pool ? pool->thread_count() : 0; } int swAio_dispatch(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; async_event *event = pool->dispatch(request); return event->task_id; } swAio_event* swAio_dispatch2(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; return pool->dispatch(request); } static void swAio_free(void *private_data) { if (!SwooleAIO.init) { return; } if (pool->current_pid == getpid()) { delete pool; } pool = nullptr; SwooleAIO.init = 0; } <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <[email protected]> Copyright © 2015 Jonathan Hale <[email protected]> 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 <memory.h> #include <Corrade/Containers/Array.h> #include <Magnum/Magnum.h> #include <Magnum/Math/Vector2.h> #include <Magnum/Math/Vector3.h> #include <Magnum/Mesh.h> #include <Corrade/Utility/utilities.h> #include <Magnum/Buffer.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Renderer.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Math/Quaternion.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Framebuffer.h> #include <Magnum/Renderbuffer.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Context.h> #include "Types.h" #include "HmdCamera.h" #include "CubeDrawable.h" #include <Magnum/LibOvrIntegration/LibOvrIntegration.h> #include <Magnum/LibOvrIntegration/Context.h> #include <Magnum/LibOvrIntegration/Hmd.h> #include <Magnum/LibOvrIntegration/HmdEnum.h> namespace Magnum { namespace Examples { using namespace LibOvrIntegration; /** * @brief The Application class of OvrExample. * @author Jonathan Hale (Squareys) */ class OvrExample: public Platform::Application { public: explicit OvrExample(const Arguments& arguments); virtual ~OvrExample(); protected: virtual void keyPressEvent(KeyEvent& event) override; private: void drawEvent() override; LibOvrIntegration::Context _ovrContext; std::unique_ptr<Hmd> _hmd; std::unique_ptr<Buffer> _indexBuffer, _vertexBuffer; std::unique_ptr<Mesh> _mesh; std::unique_ptr<Shaders::Phong> _shader; Scene3D _scene; Object3D _cameraObject; Object3D _eyes[2]; SceneGraph::DrawableGroup3D _drawables; std::unique_ptr<HmdCamera> _cameras[2]; std::unique_ptr<Object3D> _cubes[4]; std::unique_ptr<CubeDrawable> _cubeDrawables[4]; std::unique_ptr<Framebuffer> _mirrorFramebuffer; Texture2D* _mirrorTexture; LayerEyeFov* _layer; PerformanceHudMode _curPerfHudMode; }; OvrExample::OvrExample(const Arguments& arguments) : Platform::Application(arguments, nullptr), _indexBuffer(nullptr), _vertexBuffer(nullptr), _mesh(nullptr), _shader(nullptr), _scene(), _cameraObject(&_scene), _curPerfHudMode(PerformanceHudMode::Off) { /* connect to an Hmd, or create a debug hmd with DK2 type in case none is connected. */ _hmd = LibOvrIntegration::Context::get().createHmd(0, HmdType::DK2); /* get the hmd display resolution */ Vector2i resolution = _hmd->resolution() / 2; /* create a context with the hmd display resolution */ Configuration conf; conf.setTitle("Magnum OculusVR Example") .setSize(resolution) .setSampleCount(16); if(!tryCreateContext(conf)) createContext(conf.setSampleCount(0)); /* the oculus sdk compositor does some "magic" to reduce latency. For * that to work, vsync needs to be turned off. */ if(!setSwapInterval(0)) Error() << "Could not turn off vsync."; Renderer::enable(Renderer::Feature::DepthTest); _hmd->setEnabledCaps(HmdCapability::LowPersistence | HmdCapability::DynamicPrediction ); _hmd->configureTracking(HmdTrackingCapability::Orientation | HmdTrackingCapability::MagYawCorrection | HmdTrackingCapability::Position, {}); _hmd->configureRendering(); /* setup mirroring of oculus sdk compositor results to a texture which can later be blitted * onto the defaultFramebuffer. */ _mirrorTexture = &_hmd->createMirrorTexture(TextureFormat::RGBA, resolution); _mirrorFramebuffer.reset(new Framebuffer(Range2Di::fromSize({}, resolution))); _mirrorFramebuffer->attachTexture(Framebuffer::ColorAttachment(0), *_mirrorTexture, 0) .mapForRead(Framebuffer::ColorAttachment(0)); /* Setup cube mesh. */ const Trade::MeshData3D cube = Primitives::Cube::solid(); _vertexBuffer.reset(new Buffer()); _vertexBuffer->setData( MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices()); _indexBuffer.reset(new Buffer()); _indexBuffer->setData(indexData, BufferUsage::StaticDraw); _mesh.reset(new Mesh()); _mesh->setPrimitive(cube.primitive()).setCount(cube.indices().size()).addVertexBuffer( *_vertexBuffer, 0, Shaders::Phong::Position {}, Shaders::Phong::Normal {}).setIndexBuffer(*_indexBuffer, 0, indexType, indexStart, indexEnd); /* setup shader */ _shader.reset(new Shaders::Phong()); /* setup scene */ _cubes[0] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[0]->rotateY(Deg(45.0f)); _cubes[0]->translate({0.0f, 0.0f, -3.0f}); _cubeDrawables[0] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 1.0f, 0.0f}, _cubes[0].get(), &_drawables)); _cubes[1] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[1]->rotateY(Deg(45.0f)); _cubes[1]->translate({5.0f, 0.0f, 0.0f}); _cubeDrawables[1] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 0.0f, 0.0f}, _cubes[1].get(), &_drawables)); _cubes[2] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[2]->rotateY(Deg(45.0f)); _cubes[2]->translate({-10.0f, 0.0f, 0.0f}); _cubeDrawables[2] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 0.0f, 1.0f}, _cubes[2].get(), &_drawables)); _cubes[3] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[3]->rotateY(Deg(45.0f)); _cubes[3]->translate({0.0f, 0.0f, 7.0f}); _cubeDrawables[3] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 1.0f, 1.0f}, _cubes[3].get(), &_drawables)); /* setup compositor layers */ _layer = &LibOvrIntegration::Context::get().compositor().addLayerEyeFov(); _layer->setFov(*_hmd.get()); _layer->setHighQuality(true); /* setup cameras */ _eyes[0].setParent(&_cameraObject); _eyes[1].setParent(&_cameraObject); for(int eye = 0; eye < 2; ++eye) { /* projection matrix is set in the camera, since it requires some hmd-specific fov etc. */ _cameras[eye].reset(new HmdCamera(*_hmd, eye, _eyes[eye])); _layer->setColorTexture(eye, _cameras[eye]->textureSet()); _layer->setViewport(eye, {{}, _cameras[eye]->viewport()}); } } OvrExample::~OvrExample() { } void OvrExample::drawEvent() { /* get orientation and position of the hmd. */ std::array<DualQuaternion, 2> poses = _hmd->pollEyePoses().eyePoses(); /* draw the scene for both cameras */ for(int eye = 0; eye < 2; ++eye) { /* set the transformation according to rift trackers */ _eyes[eye].setTransformation(poses[eye].toMatrix()); /* render each eye. */ _cameras[eye]->draw(_drawables); } /* set the layers eye poses to the poses chached in the _hmd. */ _layer->setRenderPoses(*_hmd.get()); /* let the libOVR sdk compositor do its magic! */ LibOvrIntegration::Context::get().compositor().submitFrame(*_hmd.get()); /* blit mirror texture to defaultFramebuffer. */ const Vector2i size = _mirrorTexture->imageSize(0); Framebuffer::blit(*_mirrorFramebuffer, defaultFramebuffer, {{0, size.y()}, {size.x(), 0}}, {{}, size}, FramebufferBlit::Color, FramebufferBlitFilter::Nearest); if(_hmd->isDebugHmd()) { /* provide some rotation, but only without real devices to avoid vr sickness ;) */ _cameraObject.rotateY(Deg(0.1f)); } swapBuffers(); redraw(); } void OvrExample::keyPressEvent(KeyEvent& event) { if(event.key() == KeyEvent::Key::F11) { /* toggle through the performance hud modes */ switch(_curPerfHudMode) { case PerformanceHudMode::Off: _curPerfHudMode = PerformanceHudMode::LatencyTiming; break; case PerformanceHudMode::LatencyTiming: _curPerfHudMode = PerformanceHudMode::RenderTiming; break; case PerformanceHudMode::RenderTiming: _curPerfHudMode = PerformanceHudMode::Off; break; } /** libovr has a bug where performance hud will block the app when using a debug hmd */ if(!_hmd->isDebugHmd()) { _hmd->setPerformanceHudMode(_curPerfHudMode); } } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::OvrExample) <commit_msg>ovr: Exit application on Esc.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <[email protected]> Copyright © 2015 Jonathan Hale <[email protected]> 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 <memory.h> #include <Corrade/Containers/Array.h> #include <Magnum/Magnum.h> #include <Magnum/Math/Vector2.h> #include <Magnum/Math/Vector3.h> #include <Magnum/Mesh.h> #include <Corrade/Utility/utilities.h> #include <Magnum/Buffer.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Renderer.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Math/Quaternion.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Framebuffer.h> #include <Magnum/Renderbuffer.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Context.h> #include "Types.h" #include "HmdCamera.h" #include "CubeDrawable.h" #include <Magnum/LibOvrIntegration/LibOvrIntegration.h> #include <Magnum/LibOvrIntegration/Context.h> #include <Magnum/LibOvrIntegration/Hmd.h> #include <Magnum/LibOvrIntegration/HmdEnum.h> namespace Magnum { namespace Examples { using namespace LibOvrIntegration; /** * @brief The Application class of OvrExample. * @author Jonathan Hale (Squareys) */ class OvrExample: public Platform::Application { public: explicit OvrExample(const Arguments& arguments); virtual ~OvrExample(); protected: virtual void keyPressEvent(KeyEvent& event) override; private: void drawEvent() override; LibOvrIntegration::Context _ovrContext; std::unique_ptr<Hmd> _hmd; std::unique_ptr<Buffer> _indexBuffer, _vertexBuffer; std::unique_ptr<Mesh> _mesh; std::unique_ptr<Shaders::Phong> _shader; Scene3D _scene; Object3D _cameraObject; Object3D _eyes[2]; SceneGraph::DrawableGroup3D _drawables; std::unique_ptr<HmdCamera> _cameras[2]; std::unique_ptr<Object3D> _cubes[4]; std::unique_ptr<CubeDrawable> _cubeDrawables[4]; std::unique_ptr<Framebuffer> _mirrorFramebuffer; Texture2D* _mirrorTexture; LayerEyeFov* _layer; PerformanceHudMode _curPerfHudMode; }; OvrExample::OvrExample(const Arguments& arguments) : Platform::Application(arguments, nullptr), _indexBuffer(nullptr), _vertexBuffer(nullptr), _mesh(nullptr), _shader(nullptr), _scene(), _cameraObject(&_scene), _curPerfHudMode(PerformanceHudMode::Off) { /* connect to an Hmd, or create a debug hmd with DK2 type in case none is connected. */ _hmd = LibOvrIntegration::Context::get().createHmd(0, HmdType::DK2); /* get the hmd display resolution */ Vector2i resolution = _hmd->resolution() / 2; /* create a context with the hmd display resolution */ Configuration conf; conf.setTitle("Magnum OculusVR Example") .setSize(resolution) .setSampleCount(16); if(!tryCreateContext(conf)) createContext(conf.setSampleCount(0)); /* the oculus sdk compositor does some "magic" to reduce latency. For * that to work, vsync needs to be turned off. */ if(!setSwapInterval(0)) Error() << "Could not turn off vsync."; Renderer::enable(Renderer::Feature::DepthTest); _hmd->setEnabledCaps(HmdCapability::LowPersistence | HmdCapability::DynamicPrediction ); _hmd->configureTracking(HmdTrackingCapability::Orientation | HmdTrackingCapability::MagYawCorrection | HmdTrackingCapability::Position, {}); _hmd->configureRendering(); /* setup mirroring of oculus sdk compositor results to a texture which can later be blitted * onto the defaultFramebuffer. */ _mirrorTexture = &_hmd->createMirrorTexture(TextureFormat::RGBA, resolution); _mirrorFramebuffer.reset(new Framebuffer(Range2Di::fromSize({}, resolution))); _mirrorFramebuffer->attachTexture(Framebuffer::ColorAttachment(0), *_mirrorTexture, 0) .mapForRead(Framebuffer::ColorAttachment(0)); /* Setup cube mesh. */ const Trade::MeshData3D cube = Primitives::Cube::solid(); _vertexBuffer.reset(new Buffer()); _vertexBuffer->setData( MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices()); _indexBuffer.reset(new Buffer()); _indexBuffer->setData(indexData, BufferUsage::StaticDraw); _mesh.reset(new Mesh()); _mesh->setPrimitive(cube.primitive()).setCount(cube.indices().size()).addVertexBuffer( *_vertexBuffer, 0, Shaders::Phong::Position {}, Shaders::Phong::Normal {}).setIndexBuffer(*_indexBuffer, 0, indexType, indexStart, indexEnd); /* setup shader */ _shader.reset(new Shaders::Phong()); /* setup scene */ _cubes[0] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[0]->rotateY(Deg(45.0f)); _cubes[0]->translate({0.0f, 0.0f, -3.0f}); _cubeDrawables[0] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 1.0f, 0.0f}, _cubes[0].get(), &_drawables)); _cubes[1] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[1]->rotateY(Deg(45.0f)); _cubes[1]->translate({5.0f, 0.0f, 0.0f}); _cubeDrawables[1] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 0.0f, 0.0f}, _cubes[1].get(), &_drawables)); _cubes[2] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[2]->rotateY(Deg(45.0f)); _cubes[2]->translate({-10.0f, 0.0f, 0.0f}); _cubeDrawables[2] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 0.0f, 1.0f}, _cubes[2].get(), &_drawables)); _cubes[3] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[3]->rotateY(Deg(45.0f)); _cubes[3]->translate({0.0f, 0.0f, 7.0f}); _cubeDrawables[3] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 1.0f, 1.0f}, _cubes[3].get(), &_drawables)); /* setup compositor layers */ _layer = &LibOvrIntegration::Context::get().compositor().addLayerEyeFov(); _layer->setFov(*_hmd.get()); _layer->setHighQuality(true); /* setup cameras */ _eyes[0].setParent(&_cameraObject); _eyes[1].setParent(&_cameraObject); for(int eye = 0; eye < 2; ++eye) { /* projection matrix is set in the camera, since it requires some hmd-specific fov etc. */ _cameras[eye].reset(new HmdCamera(*_hmd, eye, _eyes[eye])); _layer->setColorTexture(eye, _cameras[eye]->textureSet()); _layer->setViewport(eye, {{}, _cameras[eye]->viewport()}); } } OvrExample::~OvrExample() { } void OvrExample::drawEvent() { /* get orientation and position of the hmd. */ std::array<DualQuaternion, 2> poses = _hmd->pollEyePoses().eyePoses(); /* draw the scene for both cameras */ for(int eye = 0; eye < 2; ++eye) { /* set the transformation according to rift trackers */ _eyes[eye].setTransformation(poses[eye].toMatrix()); /* render each eye. */ _cameras[eye]->draw(_drawables); } /* set the layers eye poses to the poses chached in the _hmd. */ _layer->setRenderPoses(*_hmd.get()); /* let the libOVR sdk compositor do its magic! */ LibOvrIntegration::Context::get().compositor().submitFrame(*_hmd.get()); /* blit mirror texture to defaultFramebuffer. */ const Vector2i size = _mirrorTexture->imageSize(0); Framebuffer::blit(*_mirrorFramebuffer, defaultFramebuffer, {{0, size.y()}, {size.x(), 0}}, {{}, size}, FramebufferBlit::Color, FramebufferBlitFilter::Nearest); if(_hmd->isDebugHmd()) { /* provide some rotation, but only without real devices to avoid vr sickness ;) */ _cameraObject.rotateY(Deg(0.1f)); } swapBuffers(); redraw(); } void OvrExample::keyPressEvent(KeyEvent& event) { if(event.key() == KeyEvent::Key::F11) { /* toggle through the performance hud modes */ switch(_curPerfHudMode) { case PerformanceHudMode::Off: _curPerfHudMode = PerformanceHudMode::LatencyTiming; break; case PerformanceHudMode::LatencyTiming: _curPerfHudMode = PerformanceHudMode::RenderTiming; break; case PerformanceHudMode::RenderTiming: _curPerfHudMode = PerformanceHudMode::Off; break; } /** libovr has a bug where performance hud will block the app when using a debug hmd */ if(!_hmd->isDebugHmd()) { _hmd->setPerformanceHudMode(_curPerfHudMode); } } else if(event.key() == KeyEvent::Key::Esc) { exit(); } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::OvrExample) <|endoftext|>
<commit_before>#include <snn/network.h> namespace snn { network::network(int N) : m_N(N) , m_Ne(N * 0.8) , m_Ni(m_N - m_Ne) , m_a(N) , m_b(N) , m_c(N) , m_d(N) , m_s(N, N) , m_v(N) , m_u(N) , m_I(N) , m_fired(N) { // initialize vector a for (int i = 0; i < m_Ne; ++ i) m_a[i] = 0.02; for (int i = m_Ne; i < m_N; ++ i) m_a[i] = 0.1; // initialize vector b for (int i = 0; i < m_N; ++ i) m_b[i] = 0.2; // initialize vector c for (int i = 0; i < m_N; ++ i) m_c[i] = -65.0; // initialize vector d for (int i = 0; i < m_Ne; ++ i) m_d[i] = 8.0; for (int i = m_Ne; i < m_N; ++ i) m_d[i] = 2.0; // initialize matrix of synaptic strength for (int i = 0; i < m_N; ++ i) { for (int j = 0; j < m_Ne; ++ j) m_s(i, j) = 0.25; for (int j = m_Ne; j < m_N; ++ j) m_s(i, j) = -0.5; } // initialize vectors v and u m_v = m_c; m_u = m_b % m_v; // reserved memory for firings m_fired.reserve(m_N); } void network::generate_random_input() { std::uniform_real_distribution<double> dist(-6.5, 6.5); for (int i = 0; i < m_N; ++ i) m_I[i] = dist(m_random_engine); } void network::process_firings() { m_fired.clear(); // detect fired neurons for (int i = 0; i < m_N; ++ i) if (m_v[i] >= 30.0) m_fired.push_back(i); // reset potential of fired neurons for (int i, n = m_fired.size(); i < n; ++ i) { const int index = m_fired[i]; m_v[index] = m_c[index]; m_u[index] += m_d[index]; } // update input current if (!m_fired.empty()) for (int i = 0; i < m_N; ++ i) { double neuron_I = 0.0; for (int j = 0, n = m_fired.size(); j < n; ++ j) neuron_I += m_s.at(i, m_fired[j]); m_I[i] += neuron_I; } } void network::update_potentials() { m_v += ((0.04 * m_v + 5.0) % m_v + 140.0 - m_u + m_I); m_u += (m_a % (m_b % m_v - m_u)); } } // namespace snn <commit_msg>use half millisecond step<commit_after>#include <snn/network.h> namespace snn { network::network(int N) : m_N(N) , m_Ne(N * 0.8) , m_Ni(m_N - m_Ne) , m_a(N) , m_b(N) , m_c(N) , m_d(N) , m_s(N, N) , m_v(N) , m_u(N) , m_I(N) , m_fired(N) { // initialize vector a for (int i = 0; i < m_Ne; ++ i) m_a[i] = 0.02; for (int i = m_Ne; i < m_N; ++ i) m_a[i] = 0.1; // initialize vector b for (int i = 0; i < m_N; ++ i) m_b[i] = 0.2; // initialize vector c for (int i = 0; i < m_N; ++ i) m_c[i] = -65.0; // initialize vector d for (int i = 0; i < m_Ne; ++ i) m_d[i] = 8.0; for (int i = m_Ne; i < m_N; ++ i) m_d[i] = 2.0; // initialize matrix of synaptic strength for (int i = 0; i < m_N; ++ i) { for (int j = 0; j < m_Ne; ++ j) m_s(i, j) = 0.25; for (int j = m_Ne; j < m_N; ++ j) m_s(i, j) = -0.5; } // initialize vectors v and u m_v = m_c; m_u = m_b % m_v; // reserved memory for firings m_fired.reserve(m_N); } void network::generate_random_input() { std::uniform_real_distribution<double> dist(-6.5, 6.5); for (int i = 0; i < m_N; ++ i) m_I[i] = dist(m_random_engine); } void network::process_firings() { m_fired.clear(); // detect fired neurons for (int i = 0; i < m_N; ++ i) if (m_v[i] >= 30.0) m_fired.push_back(i); // reset potential of fired neurons for (int i, n = m_fired.size(); i < n; ++ i) { const int index = m_fired[i]; m_v[index] = m_c[index]; m_u[index] += m_d[index]; } // update input current if (!m_fired.empty()) for (int i = 0; i < m_N; ++ i) { double neuron_I = 0.0; for (int j = 0, n = m_fired.size(); j < n; ++ j) neuron_I += m_s.at(i, m_fired[j]); m_I[i] += neuron_I; } } void network::update_potentials() { for (int i = 0; i < 2; ++ i) m_v += 0.5 * ((0.04 * m_v + 5.0) % m_v + 140.0 - m_u + m_I); m_u += (m_a % (m_b % m_v - m_u)); } } // namespace snn <|endoftext|>
<commit_before> #ifdef JASP_R_INTERFACE_LIBRARY #include "jasprcpp.h" #else bool jaspRCPP_setColumnDataAsScale( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsOrdinal( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsNominal( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsNominalText( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; #endif #include "jaspColumn.h" Json::Value jaspColumn::convertToJSON() { Json::Value obj = jaspObject::convertToJSON(); obj["columnName"] = _columnName; obj["columnType"] = jaspColumnTypeToString(_columnType); return obj; } void jaspColumn::convertFromJSON_SetFields(Json::Value in) { jaspObject::convertFromJSON_SetFields(in); _columnName = in["columnName"].asString(); _columnType = jaspColumnTypeFromString(in["columnType"].asString()); _changed = false; } std::string jaspColumn::dataToString(std::string prefix) { std::stringstream out; out << prefix << "column " << _columnName << " has type " << jaspColumnTypeToString(_columnType) << " and had " << (_changed? "" : "no ") << "changes!\n"; return out.str(); } void jaspColumn::setScale(Rcpp::RObject scalarData) { _changed = jaspRCPP_setColumnDataAsScale(_columnName, scalarData);// || _columnType != jaspColumnType::scale; _columnType = jaspColumnType::scale; if(_changed) notifyParentOfChanges(); } void jaspColumn::setOrdinal(Rcpp::RObject ordinalData) { _changed = jaspRCPP_setColumnDataAsOrdinal(_columnName, ordinalData);// || _columnType != jaspColumnType::ordinal; _columnType = jaspColumnType::ordinal; if(_changed) notifyParentOfChanges(); } void jaspColumn::setNominal(Rcpp::RObject nominalData) { _changed = jaspRCPP_setColumnDataAsNominal(_columnName, nominalData);// || _columnType != jaspColumnType::nominal; _columnType = jaspColumnType::nominal; if(_changed) notifyParentOfChanges(); } void jaspColumn::setNominalText(Rcpp::RObject nominalData) { _changed = jaspRCPP_setColumnDataAsNominalText(_columnName, nominalData);// || _columnType != jaspColumnType::text; _columnType = jaspColumnType::text; if(_changed) notifyParentOfChanges(); } Json::Value jaspColumn::dataEntry() { Json::Value data(jaspObject::dataEntry()); data["columnName"] = _columnName; data["columnType"] = jaspColumnTypeToString(_columnType); data["dataChanged"] = _changed; return data; } <commit_msg>Fixes https://github.com/jasp-stats/INTERNAL-jasp/issues/326 (Cannot build jaspResults for jaspTools)<commit_after> #include "jaspColumn.h" #ifdef JASP_R_INTERFACE_LIBRARY #include "jasprcpp.h" #else bool jaspRCPP_setColumnDataAsScale( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsOrdinal( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsNominal( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; bool jaspRCPP_setColumnDataAsNominalText( std::string, Rcpp::RObject) { jaspPrint("jaspColumn does nothing in R stand-alone!"); return false; }; #endif Json::Value jaspColumn::convertToJSON() { Json::Value obj = jaspObject::convertToJSON(); obj["columnName"] = _columnName; obj["columnType"] = jaspColumnTypeToString(_columnType); return obj; } void jaspColumn::convertFromJSON_SetFields(Json::Value in) { jaspObject::convertFromJSON_SetFields(in); _columnName = in["columnName"].asString(); _columnType = jaspColumnTypeFromString(in["columnType"].asString()); _changed = false; } std::string jaspColumn::dataToString(std::string prefix) { std::stringstream out; out << prefix << "column " << _columnName << " has type " << jaspColumnTypeToString(_columnType) << " and had " << (_changed? "" : "no ") << "changes!\n"; return out.str(); } void jaspColumn::setScale(Rcpp::RObject scalarData) { _changed = jaspRCPP_setColumnDataAsScale(_columnName, scalarData);// || _columnType != jaspColumnType::scale; _columnType = jaspColumnType::scale; if(_changed) notifyParentOfChanges(); } void jaspColumn::setOrdinal(Rcpp::RObject ordinalData) { _changed = jaspRCPP_setColumnDataAsOrdinal(_columnName, ordinalData);// || _columnType != jaspColumnType::ordinal; _columnType = jaspColumnType::ordinal; if(_changed) notifyParentOfChanges(); } void jaspColumn::setNominal(Rcpp::RObject nominalData) { _changed = jaspRCPP_setColumnDataAsNominal(_columnName, nominalData);// || _columnType != jaspColumnType::nominal; _columnType = jaspColumnType::nominal; if(_changed) notifyParentOfChanges(); } void jaspColumn::setNominalText(Rcpp::RObject nominalData) { _changed = jaspRCPP_setColumnDataAsNominalText(_columnName, nominalData);// || _columnType != jaspColumnType::text; _columnType = jaspColumnType::text; if(_changed) notifyParentOfChanges(); } Json::Value jaspColumn::dataEntry() { Json::Value data(jaspObject::dataEntry()); data["columnName"] = _columnName; data["columnType"] = jaspColumnTypeToString(_columnType); data["dataChanged"] = _changed; return data; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include <windows.h> #include <windowsx.h> #include <comdef.h> #include <comip.h> #include <shlwapi.h> #include <cassert> #include <string> #include "debugutil.hpp" #include "hrtext.hpp" #include "ComDllWrapper.hpp" namespace WebmMfUtil { ComDllWrapper::ComDllWrapper(): dll_module_(NULL), clsid_(GUID_NULL), ptrfn_get_class_object_(NULL), ref_count_(0) { } ComDllWrapper::~ComDllWrapper() { if (ptr_class_factory_) { //ptr_class_factory_->LockServer(FALSE); ptr_class_factory_ = 0; } if (NULL != dll_module_) { FreeLibrary(dll_module_); dll_module_ = NULL; } } UINT ComDllWrapper::AddRef() { return InterlockedIncrement(&ref_count_); } UINT ComDllWrapper::Release() { UINT ref_count = InterlockedDecrement(&ref_count_); if (0 == ref_count) { delete this; } return ref_count; } HRESULT ComDllWrapper::Create(std::wstring dll_path, CLSID clsid, ComDllWrapper** ptr_instance) { if (!PathFileExists(dll_path.c_str())) return E_INVALIDARG; ComDllWrapper* ptr_wrapper = new (std::nothrow) ComDllWrapper(); if (NULL == ptr_wrapper) { DBGLOG("ctor failed"); return E_OUTOFMEMORY; } ptr_wrapper->dll_path_ = dll_path; ptr_wrapper->clsid_ = clsid; HRESULT hr = ptr_wrapper->LoadDll_(); if (FAILED(hr)) { DBGLOG("LoadDll_ failed"); return hr; } ptr_wrapper->AddRef(); *ptr_instance = ptr_wrapper; return hr; } HRESULT ComDllWrapper::LoadDll_() { dll_module_ = LoadLibrary(dll_path_.c_str()); if (dll_module_) { ptrfn_get_class_object_ = reinterpret_cast<DllGetClassObjFunc>( GetProcAddress(dll_module_, "DllGetClassObject")); } HRESULT hr = E_FAIL; if (dll_module_ && ptrfn_get_class_object_) { hr = ptrfn_get_class_object_(clsid_, IID_IClassFactory, reinterpret_cast<void**>(&ptr_class_factory_)); if (FAILED(hr)) { DBGLOG("DllGetClassObject failed" << HRLOG(hr)); } if (SUCCEEDED(hr) && ptr_class_factory_) { //hr = ptr_class_factory_->LockServer(TRUE); //if (FAILED(hr)) //{ // DBGLOG("LockServer failed" << HRTEXT(hr)); // return hr; //} } } return hr; } IClassFactoryPtr ComDllWrapper::GetIClassFactoryPtr() const { return ptr_class_factory_; } HRESULT ComDllWrapper::CreateInstance(GUID interface_id, void** ptr_instance) { if (!ptr_class_factory_) { return E_INVALIDARG; } return ptr_class_factory_->CreateInstance(NULL, interface_id, ptr_instance); } const wchar_t* ComDllWrapper::GetDllPath() const { return dll_path_.c_str(); } const CLSID ComDllWrapper::GetClsid() const { return clsid_; } } // WebmMfUtil namespace<commit_msg>comdllwrapper: LockServer<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include <windows.h> #include <windowsx.h> #include <comdef.h> #include <comip.h> #include <shlwapi.h> #include <cassert> #include <string> #include "debugutil.hpp" #include "hrtext.hpp" #include "ComDllWrapper.hpp" namespace WebmMfUtil { ComDllWrapper::ComDllWrapper(): dll_module_(NULL), clsid_(GUID_NULL), ptrfn_get_class_object_(NULL), ref_count_(0) { } ComDllWrapper::~ComDllWrapper() { if (ptr_class_factory_) { IClassFactory* ptr_class_factory = ptr_class_factory_.Detach(); ptr_class_factory->LockServer(FALSE); } if (NULL != dll_module_) { FreeLibrary(dll_module_); dll_module_ = NULL; } } UINT ComDllWrapper::AddRef() { return InterlockedIncrement(&ref_count_); } UINT ComDllWrapper::Release() { UINT ref_count = InterlockedDecrement(&ref_count_); if (0 == ref_count) { delete this; } return ref_count; } HRESULT ComDllWrapper::Create(std::wstring dll_path, CLSID clsid, ComDllWrapper** ptr_instance) { if (!PathFileExists(dll_path.c_str())) return E_INVALIDARG; ComDllWrapper* ptr_wrapper = new (std::nothrow) ComDllWrapper(); if (NULL == ptr_wrapper) { DBGLOG("ctor failed"); return E_OUTOFMEMORY; } ptr_wrapper->dll_path_ = dll_path; ptr_wrapper->clsid_ = clsid; HRESULT hr = ptr_wrapper->LoadDll_(); if (FAILED(hr)) { DBGLOG("LoadDll_ failed"); return hr; } ptr_wrapper->AddRef(); *ptr_instance = ptr_wrapper; return hr; } HRESULT ComDllWrapper::LoadDll_() { dll_module_ = LoadLibrary(dll_path_.c_str()); if (dll_module_) { ptrfn_get_class_object_ = reinterpret_cast<DllGetClassObjFunc>( GetProcAddress(dll_module_, "DllGetClassObject")); } HRESULT hr = E_FAIL; if (dll_module_ && ptrfn_get_class_object_) { hr = ptrfn_get_class_object_(clsid_, IID_IClassFactory, reinterpret_cast<void**>(&ptr_class_factory_)); if (FAILED(hr)) { DBGLOG("DllGetClassObject failed" << HRLOG(hr)); } if (SUCCEEDED(hr) && ptr_class_factory_) { hr = ptr_class_factory_->LockServer(TRUE); if (FAILED(hr)) { DBGLOG("LockServer failed" << HRLOG(hr)); return hr; } } } return hr; } IClassFactoryPtr ComDllWrapper::GetIClassFactoryPtr() const { return ptr_class_factory_; } HRESULT ComDllWrapper::CreateInstance(GUID interface_id, void** ptr_instance) { if (!ptr_class_factory_) { return E_INVALIDARG; } return ptr_class_factory_->CreateInstance(NULL, interface_id, ptr_instance); } const wchar_t* ComDllWrapper::GetDllPath() const { return dll_path_.c_str(); } const CLSID ComDllWrapper::GetClsid() const { return clsid_; } } // WebmMfUtil namespace<|endoftext|>
<commit_before>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::template wcmd<CC1101::SRES>(); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::template set<CC1101::IOCFG2>(0x2f); cc1101::template set<CC1101::IOCFG0>(0x2f); // fix packet length cc1101::template set<CC1101::PKTLEN>(16); // packet automation cc1101::template set<CC1101::PKTCTRL0>(0x44); // frequency configuration cc1101::template set<CC1101::FREQ2>(0x10); cc1101::template set<CC1101::FREQ1>(0xa7); cc1101::template set<CC1101::FREQ0>(0xe1); // modem configuration cc1101::template set<CC1101::MDMCFG2>(0x16); cc1101::template set<CC1101::MDMCFG1>(0xa2); // calibrate cc1101::template wcmd<CC1101::SCAL>(); while ((cc1101::template status<CC1101::MARCSTATE>() & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::template set<CC1101::PKTCTRL1>(0x2c); // main radio control state machine configuration cc1101::template set<CC1101::MCSM1>(0x3c); cc1101::template set<CC1101::MCSM0>(0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::template set<CC1101::MCSM0>(0x38); // PATABLE cc1101::template set<CC1101::PATABLE>(0x60); cc1101::release(); } <commit_msg>RF: sensor TX power increased to 12 dBm<commit_after>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::template wcmd<CC1101::SRES>(); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::template set<CC1101::IOCFG2>(0x2f); cc1101::template set<CC1101::IOCFG0>(0x2f); // fix packet length cc1101::template set<CC1101::PKTLEN>(16); // packet automation cc1101::template set<CC1101::PKTCTRL0>(0x44); // frequency configuration cc1101::template set<CC1101::FREQ2>(0x10); cc1101::template set<CC1101::FREQ1>(0xa7); cc1101::template set<CC1101::FREQ0>(0xe1); // modem configuration cc1101::template set<CC1101::MDMCFG2>(0x16); cc1101::template set<CC1101::MDMCFG1>(0xa2); // calibrate cc1101::template wcmd<CC1101::SCAL>(); while ((cc1101::template status<CC1101::MARCSTATE>() & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::template set<CC1101::PKTCTRL1>(0x2c); // main radio control state machine configuration cc1101::template set<CC1101::MCSM1>(0x3c); cc1101::template set<CC1101::MCSM0>(0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::template set<CC1101::MCSM0>(0x38); // PATABLE cc1101::template set<CC1101::PATABLE>(0xc0); cc1101::release(); } <|endoftext|>
<commit_before>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::wcmd(CC1101::SRES); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::set(CC1101::IOCFG2, 0x2f); cc1101::set(CC1101::IOCFG0, 0x2f); // fix packet length cc1101::set(CC1101::PKTLEN, 16); // packet automation cc1101::set(CC1101::PKTCTRL0, 0x44); // frequency configuration cc1101::set(CC1101::FREQ2, 0x10); cc1101::set(CC1101::FREQ1, 0xa7); cc1101::set(CC1101::FREQ0, 0xe1); // modem configuration cc1101::set(CC1101::MDMCFG4, 0x6a); cc1101::set(CC1101::MDMCFG3, 0x83); cc1101::set(CC1101::MDMCFG2, 0x13); // calibrate cc1101::wcmd(CC1101::SCAL); while ((cc1101::status(CC1101::MARCSTATE) & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::set(CC1101::PKTCTRL1, 0x2c); // main radio control state machine configuration cc1101::set(CC1101::MCSM1, 0x3c); cc1101::set(CC1101::MCSM0, 0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::set(CC1101::MCSM0, 0x38); // PATABLE cc1101::set(CC1101::PATABLE, 0xc0); cc1101::release(); } <commit_msg>radio tuned<commit_after>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::wcmd(CC1101::SRES); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::set(CC1101::IOCFG2, 0x2f); cc1101::set(CC1101::IOCFG0, 0x2f); // fix packet length cc1101::set(CC1101::PKTLEN, 16); // packet automation cc1101::set(CC1101::PKTCTRL0, 0x44); // frequency configuration cc1101::set(CC1101::FREQ2, 0x10); cc1101::set(CC1101::FREQ1, 0xa7); cc1101::set(CC1101::FREQ0, 0xe1); // modem configuration cc1101::set(CC1101::MDMCFG4, 0x3c); cc1101::set(CC1101::MDMCFG3, 0x24); cc1101::set(CC1101::MDMCFG2, 0x13); cc1101::set(CC1101::DEVIATN, 0x53); // calibrate cc1101::wcmd(CC1101::SCAL); while ((cc1101::status(CC1101::MARCSTATE) & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::set(CC1101::PKTCTRL1, 0x2c); // main radio control state machine configuration cc1101::set(CC1101::MCSM1, 0x3c); cc1101::set(CC1101::MCSM0, 0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::set(CC1101::MCSM0, 0x38); // PATABLE cc1101::set(CC1101::PATABLE, 0xc0); cc1101::release(); } <|endoftext|>
<commit_before>// Copyright (c) 2012, Sergey Zolotarev // 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER 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. #include <cstddef> #include <map> #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" using namespace jit; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; typedef std::map<AMX*, JIT*> JITMap; static JITMap jit_map; static JIT *GetJIT(AMX *amx) { JITMap::const_iterator it = jit_map.find(amx); if (it == jit_map.end()) { JIT *jit = new JIT(amx); jit_map.insert(std::make_pair(amx, jit)); return jit; } else { return it->second; } } static void DeleteJIT(AMX *amx) { JITMap::iterator it = jit_map.find(amx); if (it != jit_map.end()) { delete it->second; jit_map.erase(it); } } // This implementation of amx_GetAddr can accept ANY amx_addr, even out of the data section. static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } // amx_Exec_JIT compiles a public function (if needed) and runs the generated JIT code. static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { if (index != AMX_EXEC_CONT) { return GetJIT(amx)->CallPublicFunction(index, retval); } return AMX_ERR_NONE; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT); new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT); logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { // nothing } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { DeleteJIT(amx); return AMX_ERR_NONE; } <commit_msg>Delete unnecessary comments<commit_after>// Copyright (c) 2012, Sergey Zolotarev // 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER 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. #include <cstddef> #include <map> #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" using namespace jit; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; typedef std::map<AMX*, JIT*> JITMap; static JITMap jit_map; static JIT *GetJIT(AMX *amx) { JITMap::const_iterator it = jit_map.find(amx); if (it == jit_map.end()) { JIT *jit = new JIT(amx); jit_map.insert(std::make_pair(amx, jit)); return jit; } else { return it->second; } } static void DeleteJIT(AMX *amx) { JITMap::iterator it = jit_map.find(amx); if (it != jit_map.end()) { delete it->second; jit_map.erase(it); } } static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { if (index != AMX_EXEC_CONT) { return GetJIT(amx)->CallPublicFunction(index, retval); } return AMX_ERR_NONE; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT); new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT); logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { // nothing } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { DeleteJIT(amx); return AMX_ERR_NONE; } <|endoftext|>
<commit_before>// // HUDQuadWidget.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 12/17/13. // // #include "HUDQuadWidget.hpp" #include "Context.hpp" #include "IDownloader.hpp" #include "IImageDownloadListener.hpp" #include "TexturesHandler.hpp" #include "Camera.hpp" #include "Vector3D.hpp" #include "FloatBufferBuilderFromCartesian3D.hpp" #include "FloatBufferBuilderFromCartesian2D.hpp" #include "DirectMesh.hpp" #include "TexturedMesh.hpp" class HUDQuadWidget_ImageDownloadListener : public IImageDownloadListener { HUDQuadWidget* _quadWidget; public: HUDQuadWidget_ImageDownloadListener(HUDQuadWidget* quadWidget) : _quadWidget(quadWidget) { } void onDownload(const URL& url, IImage* image, bool expired) { _quadWidget->onImageDownload(image); } void onError(const URL& url) { _quadWidget->onImageDownloadError(url); } void onCancel(const URL& url) { // do nothing } void onCanceledDownload(const URL& url, IImage* image, bool expired) { // do nothing } }; HUDQuadWidget::~HUDQuadWidget() { delete _image; delete _mesh; } void HUDQuadWidget::initialize(const G3MContext* context) { if (!_downloadingImage && (_image == NULL)) { _downloadingImage = true; IDownloader* downloader = context->getDownloader(); downloader->requestImage(_imageURL, 1000000, // priority TimeInterval::fromDays(30), true, // readExpired new HUDQuadWidget_ImageDownloadListener(this), true); } } void HUDQuadWidget::onResizeViewportEvent(const G3MEventContext* ec, int width, int height) { delete _mesh; _mesh = NULL; } void HUDQuadWidget::onImageDownload(IImage* image) { _downloadingImage = false; _image = image; } void HUDQuadWidget::onImageDownloadError(const URL& url) { _errors.push_back("HUDQuadWidget: Error downloading \"" + url.getPath() + "\""); } RenderState HUDQuadWidget::getRenderState(const G3MRenderContext* rc) { if (!_errors.empty()) { return RenderState::error(_errors); } else if (_downloadingImage) { return RenderState::busy(); } else { return RenderState::ready(); } } Mesh* HUDQuadWidget::createMesh(const G3MRenderContext* rc) const { if (_image == NULL) { return NULL; } //#ifdef C_CODE // const TextureIDReference* texId; //#endif //#ifdef JAVA_CODE // TextureIDReference texId; //#endif const TextureIDReference* texId = rc->getTexturesHandler()->getTextureIDReference(_image, GLFormat::rgba(), _imageURL.getPath(), false); if (texId == NULL) { rc->getLogger()->logError("Can't upload texture to GPU"); return NULL; } const Camera* camera = rc->getCurrentCamera(); const int viewportWidth = camera->getWidth(); const int viewportHeight = camera->getHeight(); const Vector3D halfViewportAndPosition(viewportWidth / 2 - _x, viewportHeight / 2 - _y, 0); const double w = _width; const double h = _height; FloatBufferBuilderFromCartesian3D* vertices = FloatBufferBuilderFromCartesian3D::builderWithoutCenter(); vertices->add( Vector3D(0, h, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(0, 0, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(w, h, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(w, 0, 0).sub(halfViewportAndPosition) ); FloatBufferBuilderFromCartesian2D texCoords; texCoords.add(0, 0); texCoords.add(0, 1); texCoords.add(1, 0); texCoords.add(1, 1); DirectMesh* dm = new DirectMesh(GLPrimitive::triangleStrip(), true, vertices->getCenter(), vertices->create(), 1, 1); delete vertices; TextureMapping* texMap = new SimpleTextureMapping(texId, texCoords.create(), true, true); return new TexturedMesh(dm, true, texMap, true, true); } Mesh* HUDQuadWidget::getMesh(const G3MRenderContext* rc) { if (_mesh == NULL) { _mesh = createMesh(rc); } return _mesh; } void HUDQuadWidget::render(const G3MRenderContext* rc, GLState* glState) { Mesh* mesh = getMesh(rc); if (mesh != NULL) { mesh->render(rc, glState); } } <commit_msg>slow progress - not yet usable<commit_after>// // HUDQuadWidget.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 12/17/13. // // #include "HUDQuadWidget.hpp" #include "Context.hpp" #include "IDownloader.hpp" #include "IImageDownloadListener.hpp" #include "TexturesHandler.hpp" #include "Camera.hpp" #include "Vector3D.hpp" #include "FloatBufferBuilderFromCartesian3D.hpp" #include "FloatBufferBuilderFromCartesian2D.hpp" #include "DirectMesh.hpp" #include "TexturedMesh.hpp" class HUDQuadWidget_ImageDownloadListener : public IImageDownloadListener { private: HUDQuadWidget* _quadWidget; public: HUDQuadWidget_ImageDownloadListener(HUDQuadWidget* quadWidget) : _quadWidget(quadWidget) { } void onDownload(const URL& url, IImage* image, bool expired) { _quadWidget->onImageDownload(image); } void onError(const URL& url) { _quadWidget->onImageDownloadError(url); } void onCancel(const URL& url) { // do nothing } void onCanceledDownload(const URL& url, IImage* image, bool expired) { // do nothing } }; HUDQuadWidget::~HUDQuadWidget() { delete _image; delete _mesh; } void HUDQuadWidget::initialize(const G3MContext* context) { if (!_downloadingImage && (_image == NULL)) { _downloadingImage = true; IDownloader* downloader = context->getDownloader(); downloader->requestImage(_imageURL, 1000000, // priority TimeInterval::fromDays(30), true, // readExpired new HUDQuadWidget_ImageDownloadListener(this), true); } } void HUDQuadWidget::onResizeViewportEvent(const G3MEventContext* ec, int width, int height) { delete _mesh; _mesh = NULL; } void HUDQuadWidget::onImageDownload(IImage* image) { _downloadingImage = false; _image = image; } void HUDQuadWidget::onImageDownloadError(const URL& url) { _errors.push_back("HUDQuadWidget: Error downloading \"" + url.getPath() + "\""); } RenderState HUDQuadWidget::getRenderState(const G3MRenderContext* rc) { if (!_errors.empty()) { return RenderState::error(_errors); } else if (_downloadingImage) { return RenderState::busy(); } else { return RenderState::ready(); } } Mesh* HUDQuadWidget::createMesh(const G3MRenderContext* rc) const { if (_image == NULL) { return NULL; } //#ifdef C_CODE // const TextureIDReference* texId; //#endif //#ifdef JAVA_CODE // TextureIDReference texId; //#endif const TextureIDReference* texId = rc->getTexturesHandler()->getTextureIDReference(_image, GLFormat::rgba(), _imageURL.getPath(), false); if (texId == NULL) { rc->getLogger()->logError("Can't upload texture to GPU"); return NULL; } const Camera* camera = rc->getCurrentCamera(); const int viewportWidth = camera->getWidth(); const int viewportHeight = camera->getHeight(); const Vector3D halfViewportAndPosition(viewportWidth / 2 - _x, viewportHeight / 2 - _y, 0); const double w = _width; const double h = _height; FloatBufferBuilderFromCartesian3D* vertices = FloatBufferBuilderFromCartesian3D::builderWithoutCenter(); vertices->add( Vector3D(0, h, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(0, 0, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(w, h, 0).sub(halfViewportAndPosition) ); vertices->add( Vector3D(w, 0, 0).sub(halfViewportAndPosition) ); FloatBufferBuilderFromCartesian2D texCoords; texCoords.add(0, 0); texCoords.add(0, 1); texCoords.add(1, 0); texCoords.add(1, 1); DirectMesh* dm = new DirectMesh(GLPrimitive::triangleStrip(), true, vertices->getCenter(), vertices->create(), 1, 1); delete vertices; TextureMapping* texMap = new SimpleTextureMapping(texId, texCoords.create(), true, true); return new TexturedMesh(dm, true, texMap, true, true); } Mesh* HUDQuadWidget::getMesh(const G3MRenderContext* rc) { if (_mesh == NULL) { _mesh = createMesh(rc); } return _mesh; } void HUDQuadWidget::render(const G3MRenderContext* rc, GLState* glState) { Mesh* mesh = getMesh(rc); if (mesh != NULL) { mesh->render(rc, glState); } } <|endoftext|>
<commit_before>#include "lm/enumerate_vocab.hh" #include "lm/model.hh" #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <ctype.h> #include <sys/resource.h> #include <sys/time.h> float FloatSec(const struct timeval &tv) { return static_cast<float>(tv.tv_sec) + (static_cast<float>(tv.tv_usec) / 1000000000.0); } void PrintUsage(const char *message) { struct rusage usage; if (getrusage(RUSAGE_SELF, &usage)) { perror("getrusage"); return; } std::cerr << message; std::cerr << "user\t" << FloatSec(usage.ru_utime) << "\nsys\t" << FloatSec(usage.ru_stime) << '\n'; // Linux doesn't set memory usage :-(. std::ifstream status("/proc/self/status", std::ios::in); std::string line; while (getline(status, line)) { if (!strncmp(line.c_str(), "VmRSS:\t", 7)) { std::cerr << "rss " << (line.c_str() + 7) << '\n'; break; } } } template <class Model> void Query(const Model &model) { PrintUsage("Loading statistics:\n"); typename Model::State state, out; lm::FullScoreReturn ret; std::string word; while (std::cin) { state = model.BeginSentenceState(); float total = 0.0; bool got = false; unsigned int oov = 0; while (std::cin >> word) { got = true; lm::WordIndex vocab = model.GetVocabulary().Index(word); if (vocab == 0) ++oov; ret = model.FullScore(state, vocab, out); total += ret.prob; std::cout << word << '=' << vocab << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\n'; state = out; char c; while (true) { c = std::cin.get(); if (!std::cin) break; if (c == '\n') break; if (!isspace(c)) { std::cin.unget(); break; } } if (c == '\n') break; } if (!got && !std::cin) break; ret = model.FullScore(state, model.GetVocabulary().EndSentence(), out); total += ret.prob; std::cout << "</s>=" << model.GetVocabulary().EndSentence() << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\n'; std::cout << "Total: " << total << " OOV: " << oov << '\n'; } PrintUsage("After queries:\n"); } template <class Model> void Query(const char *name) { lm::ngram::Config config; Model model(name, config); Query(model); } int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "Pass language model name." << std::endl; return 0; } lm::ngram::ModelType model_type; if (lm::ngram::RecognizeBinary(argv[1], model_type)) { switch(model_type) { case lm::ngram::HASH_PROBING: Query<lm::ngram::ProbingModel>(argv[1]); break; case lm::ngram::HASH_SORTED: Query<lm::ngram::SortedModel>(argv[1]); break; case lm::ngram::TRIE_SORTED: Query<lm::ngram::TrieModel>(argv[1]); break; default: std::cerr << "Unrecognized kenlm model type " << model_type << std::endl; abort(); } } else { Query<lm::ngram::ProbingModel>(argv[1]); } PrintUsage("Total time including destruction:\n"); } <commit_msg>Option for null context in n-gram query, use tab for delimiter<commit_after>#include "lm/enumerate_vocab.hh" #include "lm/model.hh" #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <ctype.h> #include <sys/resource.h> #include <sys/time.h> float FloatSec(const struct timeval &tv) { return static_cast<float>(tv.tv_sec) + (static_cast<float>(tv.tv_usec) / 1000000000.0); } void PrintUsage(const char *message) { struct rusage usage; if (getrusage(RUSAGE_SELF, &usage)) { perror("getrusage"); return; } std::cerr << message; std::cerr << "user\t" << FloatSec(usage.ru_utime) << "\nsys\t" << FloatSec(usage.ru_stime) << '\n'; // Linux doesn't set memory usage :-(. std::ifstream status("/proc/self/status", std::ios::in); std::string line; while (getline(status, line)) { if (!strncmp(line.c_str(), "VmRSS:\t", 7)) { std::cerr << "rss " << (line.c_str() + 7) << '\n'; break; } } } template <class Model> void Query(const Model &model, bool sentence_context) { PrintUsage("Loading statistics:\n"); typename Model::State state, out; lm::FullScoreReturn ret; std::string word; while (std::cin) { state = sentence_context ? model.BeginSentenceState() : model.NullContextState(); float total = 0.0; bool got = false; unsigned int oov = 0; while (std::cin >> word) { got = true; lm::WordIndex vocab = model.GetVocabulary().Index(word); if (vocab == 0) ++oov; ret = model.FullScore(state, vocab, out); total += ret.prob; std::cout << word << '=' << vocab << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\t'; state = out; char c; while (true) { c = std::cin.get(); if (!std::cin) break; if (c == '\n') break; if (!isspace(c)) { std::cin.unget(); break; } } if (c == '\n') break; } if (!got && !std::cin) break; if (sentence_context) { ret = model.FullScore(state, model.GetVocabulary().EndSentence(), out); total += ret.prob; std::cout << "</s>=" << model.GetVocabulary().EndSentence() << ' ' << static_cast<unsigned int>(ret.ngram_length) << ' ' << ret.prob << '\t'; } std::cout << "Total: " << total << " OOV: " << oov << '\n'; } PrintUsage("After queries:\n"); } template <class Model> void Query(const char *name) { lm::ngram::Config config; Model model(name, config); Query(model); } int main(int argc, char *argv[]) { if (!(argc == 2 || (argc == 3 && !strcmp(argv[2], "null")))) { std::cerr << "Usage: " << argv[0] << " lm_file [null]" << std::endl; std::cerr << "Input is wrapped in <s> and </s> unless null is passed." << std::endl; return 1; } bool sentence_context = (argc == 2); lm::ngram::ModelType model_type; if (lm::ngram::RecognizeBinary(argv[1], model_type)) { switch(model_type) { case lm::ngram::HASH_PROBING: Query<lm::ngram::ProbingModel>(argv[1], sentence_context); break; case lm::ngram::TRIE_SORTED: Query<lm::ngram::TrieModel>(argv[1], sentence_context); break; case lm::ngram::HASH_SORTED: default: std::cerr << "Unrecognized kenlm model type " << model_type << std::endl; abort(); } } else { Query<lm::ngram::ProbingModel>(argv[1], sentence_context); } PrintUsage("Total time including destruction:\n"); return 0; } <|endoftext|>
<commit_before>#include "pattern_search.h" void findPattern(const string& pattern, const string& text, vector<int> *ppositions) { if (pattern.empty()) return; auto& positions = *ppositions; positions.clear(); for (size_t i = 0; i < text.size(); i++) { bool found = true; for (size_t j = 0; j < pattern.size(); j++) { if (pattern[j] != text[i + j]) { found = false; break; } } if (found) positions.push_back(i); } }<commit_msg>Fix pattern search<commit_after>#include "pattern_search.h" void findPattern(const string& pattern, const string& text, vector<int> *ppositions) { auto& positions = *ppositions; positions.clear(); if (pattern.empty()) return; for (size_t i = 0; i < text.size(); i++) { bool found = true; for (size_t j = 0; j < pattern.size(); j++) { if (pattern[j] != text[i + j]) { found = false; break; } } if (found) positions.push_back(i); } }<|endoftext|>
<commit_before>/* * Copyright (C) 2010 The Android Open Source Project * * 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 "SkPDFImage.h" #include "SkBitmap.h" #include "SkColor.h" #include "SkColorPriv.h" #include "SkPaint.h" #include "SkPackBits.h" #include "SkPDFCatalog.h" #include "SkStream.h" #include "SkString.h" #include "SkUnPreMultiply.h" namespace { SkMemoryStream* extractImageData(const SkBitmap& bitmap) { SkMemoryStream* result; switch (bitmap.getConfig()) { case SkBitmap::kIndex8_Config: result = new SkMemoryStream(bitmap.getPixels(), bitmap.getSize(), true); break; case SkBitmap::kRLE_Index8_Config: { result = new SkMemoryStream(bitmap.getSize()); const SkBitmap::RLEPixels* rle = (const SkBitmap::RLEPixels*)bitmap.getPixels(); uint8_t* dst = (uint8_t*)result->getMemoryBase(); const int width = bitmap.width(); for (int y = 0; y < bitmap.height(); y++) { SkPackBits::Unpack8(rle->packedAtY(y), width, dst); dst += width; } break; } case SkBitmap::kARGB_4444_Config: { const int width = bitmap.width(); const int rowBytes = (width * 3 + 1) / 2; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint16_t* src = bitmap.getAddr16(0, y); for (int x = 0; x < width; x += 2) { dst[0] = (SkGetPackedR4444(src[0]) << 4) | SkGetPackedG4444(src[0]); dst[1] = (SkGetPackedB4444(src[0]) << 4) | SkGetPackedR4444(src[1]); dst[2] = (SkGetPackedG4444(src[1]) << 4) | SkGetPackedB4444(src[1]); src += 2; dst += 3; } if (width & 1) { dst[0] = (SkGetPackedR4444(src[0]) << 4) | SkGetPackedG4444(src[0]); dst[1] = (SkGetPackedB4444(src[0]) << 4); } } break; } case SkBitmap::kRGB_565_Config: { const int width = bitmap.width(); const int rowBytes = width * 3; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint16_t* src = bitmap.getAddr16(0, y); for (int x = 0; x < width; x++) { dst[0] = SkGetPackedR16(src[0]); dst[1] = SkGetPackedG16(src[0]); dst[2] = SkGetPackedB16(src[0]); src++; dst += 3; } } break; } case SkBitmap::kARGB_8888_Config: { const int width = bitmap.width(); const int rowBytes = width * 3; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint32_t* src = bitmap.getAddr32(0, y); for (int x = 0; x < width; x++) { dst[0] = SkGetPackedR32(src[0]); dst[1] = SkGetPackedG32(src[0]); dst[2] = SkGetPackedB32(src[0]); src++; dst += 3; } } break; } default: SkASSERT(false); } return result; } SkPDFArray* makeIndexedColorSpace(SkColorTable* table) { SkPDFArray* result = new SkPDFArray(); result->reserve(4); SkRefPtr<SkPDFName> indexedName = new SkPDFName("Indexed"); indexedName->unref(); // SkRefPtr and new both took a reference. result->append(indexedName.get()); SkRefPtr<SkPDFName> rgbName = new SkPDFName("DeviceRGB"); rgbName->unref(); // SkRefPtr and new both took a reference. result->append(rgbName.get()); rgbName->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> countValue = new SkPDFInt(table->count() - 1); result->append(countValue.get()); // Potentially, this could be represented in fewer bytes with a stream. // Max size as a string is 1.5k. SkString index; for (int i = 0; i < table->count(); i++) { char buf[3]; SkColor color = SkUnPreMultiply::PMColorToColor((*table)[i]); buf[0] = SkGetPackedR32(color); buf[1] = SkGetPackedG32(color); buf[2] = SkGetPackedB32(color); index.append(buf, 3); } SkRefPtr<SkPDFString> indexValue = new SkPDFString(index); indexValue->unref(); // SkRefPtr and new both took a reference. result->append(indexValue.get()); return result; } }; // namespace SkPDFImage::SkPDFImage(const SkBitmap& bitmap, const SkPaint& paint) { SkBitmap::Config config = bitmap.getConfig(); // TODO(vandebo) Handle alpha and alpha only images correctly. SkASSERT(config == SkBitmap::kRGB_565_Config || config == SkBitmap::kARGB_4444_Config || config == SkBitmap::kARGB_8888_Config || config == SkBitmap::kIndex8_Config || config == SkBitmap::kRLE_Index8_Config); SkMemoryStream* image_data = extractImageData(bitmap); SkAutoUnref image_data_unref(image_data); fStream = new SkPDFStream(image_data); fStream->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFName> typeValue = new SkPDFName("XObject"); typeValue->unref(); // SkRefPtr and new both took a reference. insert("Type", typeValue.get()); SkRefPtr<SkPDFName> subTypeValue = new SkPDFName("Image"); subTypeValue->unref(); // SkRefPtr and new both took a reference. insert("Subtype", subTypeValue.get()); SkRefPtr<SkPDFInt> widthValue = new SkPDFInt(bitmap.width()); widthValue->unref(); // SkRefPtr and new both took a reference. insert("Width", widthValue.get()); SkRefPtr<SkPDFInt> heightValue = new SkPDFInt(bitmap.height()); heightValue->unref(); // SkRefPtr and new both took a reference. insert("Height", heightValue.get()); // if (!image mask) { SkRefPtr<SkPDFObject> colorSpaceValue; if (config == SkBitmap::kIndex8_Config || config == SkBitmap::kRLE_Index8_Config) { colorSpaceValue = makeIndexedColorSpace(bitmap.getColorTable()); } else { colorSpaceValue = new SkPDFName("DeviceRGB"); } colorSpaceValue->unref(); // SkRefPtr and new both took a reference. insert("ColorSpace", colorSpaceValue.get()); // } int bitsPerComp = bitmap.bytesPerPixel() * 2; if (bitsPerComp == 0) { SkASSERT(config == SkBitmap::kA1_Config); bitsPerComp = 1; } else if (bitsPerComp == 2 || (bitsPerComp == 4 && config == SkBitmap::kRGB_565_Config)) { bitsPerComp = 8; } SkRefPtr<SkPDFInt> bitsPerCompValue = new SkPDFInt(bitsPerComp); bitsPerCompValue->unref(); // SkRefPtr and new both took a reference. insert("BitsPerComponent", bitsPerCompValue.get()); if (config == SkBitmap::kRGB_565_Config) { SkRefPtr<SkPDFInt> zeroVal = new SkPDFInt(0); zeroVal->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFScalar> scale5Val = new SkPDFScalar(8.2258); // 255/2^5-1 scale5Val->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFScalar> scale6Val = new SkPDFScalar(4.0476); // 255/2^6-1 scale6Val->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFArray> decodeValue = new SkPDFArray(); decodeValue->unref(); // SkRefPtr and new both took a reference. decodeValue->reserve(6); decodeValue->append(zeroVal.get()); decodeValue->append(scale5Val.get()); decodeValue->append(zeroVal.get()); decodeValue->append(scale6Val.get()); decodeValue->append(zeroVal.get()); decodeValue->append(scale5Val.get()); insert("Decode", decodeValue.get()); } } SkPDFImage::~SkPDFImage() {} void SkPDFImage::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { if (indirect) return emitIndirectObject(stream, catalog); fStream->emitObject(stream, catalog, indirect); } size_t SkPDFImage::getOutputSize(SkPDFCatalog* catalog, bool indirect) { if (indirect) return getIndirectOutputSize(catalog); return fStream->getOutputSize(catalog, indirect); } void SkPDFImage::insert(SkPDFName* key, SkPDFObject* value) { fStream->insert(key, value); } void SkPDFImage::insert(const char key[], SkPDFObject* value) { fStream->insert(key, value); } <commit_msg>Bug fix in SkPDFImage.<commit_after>/* * Copyright (C) 2010 The Android Open Source Project * * 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 "SkPDFImage.h" #include "SkBitmap.h" #include "SkColor.h" #include "SkColorPriv.h" #include "SkPaint.h" #include "SkPackBits.h" #include "SkPDFCatalog.h" #include "SkStream.h" #include "SkString.h" #include "SkUnPreMultiply.h" namespace { SkMemoryStream* extractImageData(const SkBitmap& bitmap) { SkMemoryStream* result; bitmap.lockPixels(); switch (bitmap.getConfig()) { case SkBitmap::kIndex8_Config: result = new SkMemoryStream(bitmap.getPixels(), bitmap.getSize(), true); break; case SkBitmap::kRLE_Index8_Config: { result = new SkMemoryStream(bitmap.getSize()); const SkBitmap::RLEPixels* rle = (const SkBitmap::RLEPixels*)bitmap.getPixels(); uint8_t* dst = (uint8_t*)result->getMemoryBase(); const int width = bitmap.width(); for (int y = 0; y < bitmap.height(); y++) { SkPackBits::Unpack8(rle->packedAtY(y), width, dst); dst += width; } break; } case SkBitmap::kARGB_4444_Config: { const int width = bitmap.width(); const int rowBytes = (width * 3 + 1) / 2; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint16_t* src = bitmap.getAddr16(0, y); for (int x = 0; x < width; x += 2) { dst[0] = (SkGetPackedR4444(src[0]) << 4) | SkGetPackedG4444(src[0]); dst[1] = (SkGetPackedB4444(src[0]) << 4) | SkGetPackedR4444(src[1]); dst[2] = (SkGetPackedG4444(src[1]) << 4) | SkGetPackedB4444(src[1]); src += 2; dst += 3; } if (width & 1) { dst[0] = (SkGetPackedR4444(src[0]) << 4) | SkGetPackedG4444(src[0]); dst[1] = (SkGetPackedB4444(src[0]) << 4); } } break; } case SkBitmap::kRGB_565_Config: { const int width = bitmap.width(); const int rowBytes = width * 3; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint16_t* src = bitmap.getAddr16(0, y); for (int x = 0; x < width; x++) { dst[0] = SkGetPackedR16(src[0]); dst[1] = SkGetPackedG16(src[0]); dst[2] = SkGetPackedB16(src[0]); src++; dst += 3; } } break; } case SkBitmap::kARGB_8888_Config: { const int width = bitmap.width(); const int rowBytes = width * 3; result = new SkMemoryStream(rowBytes * bitmap.height()); uint8_t* dst = (uint8_t*)result->getMemoryBase(); for (int y = 0; y < bitmap.height(); y++) { uint32_t* src = bitmap.getAddr32(0, y); for (int x = 0; x < width; x++) { dst[0] = SkGetPackedR32(src[0]); dst[1] = SkGetPackedG32(src[0]); dst[2] = SkGetPackedB32(src[0]); src++; dst += 3; } } break; } default: SkASSERT(false); } bitmap.unlockPixels(); return result; } SkPDFArray* makeIndexedColorSpace(SkColorTable* table) { SkPDFArray* result = new SkPDFArray(); result->reserve(4); SkRefPtr<SkPDFName> indexedName = new SkPDFName("Indexed"); indexedName->unref(); // SkRefPtr and new both took a reference. result->append(indexedName.get()); SkRefPtr<SkPDFName> rgbName = new SkPDFName("DeviceRGB"); rgbName->unref(); // SkRefPtr and new both took a reference. result->append(rgbName.get()); rgbName->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> countValue = new SkPDFInt(table->count() - 1); result->append(countValue.get()); // Potentially, this could be represented in fewer bytes with a stream. // Max size as a string is 1.5k. SkString index; for (int i = 0; i < table->count(); i++) { char buf[3]; SkColor color = SkUnPreMultiply::PMColorToColor((*table)[i]); buf[0] = SkGetPackedR32(color); buf[1] = SkGetPackedG32(color); buf[2] = SkGetPackedB32(color); index.append(buf, 3); } SkRefPtr<SkPDFString> indexValue = new SkPDFString(index); indexValue->unref(); // SkRefPtr and new both took a reference. result->append(indexValue.get()); return result; } }; // namespace SkPDFImage::SkPDFImage(const SkBitmap& bitmap, const SkPaint& paint) { SkBitmap::Config config = bitmap.getConfig(); // TODO(vandebo) Handle alpha and alpha only images correctly. SkASSERT(config == SkBitmap::kRGB_565_Config || config == SkBitmap::kARGB_4444_Config || config == SkBitmap::kARGB_8888_Config || config == SkBitmap::kIndex8_Config || config == SkBitmap::kRLE_Index8_Config); SkMemoryStream* image_data = extractImageData(bitmap); SkAutoUnref image_data_unref(image_data); fStream = new SkPDFStream(image_data); fStream->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFName> typeValue = new SkPDFName("XObject"); typeValue->unref(); // SkRefPtr and new both took a reference. insert("Type", typeValue.get()); SkRefPtr<SkPDFName> subTypeValue = new SkPDFName("Image"); subTypeValue->unref(); // SkRefPtr and new both took a reference. insert("Subtype", subTypeValue.get()); SkRefPtr<SkPDFInt> widthValue = new SkPDFInt(bitmap.width()); widthValue->unref(); // SkRefPtr and new both took a reference. insert("Width", widthValue.get()); SkRefPtr<SkPDFInt> heightValue = new SkPDFInt(bitmap.height()); heightValue->unref(); // SkRefPtr and new both took a reference. insert("Height", heightValue.get()); // if (!image mask) { SkRefPtr<SkPDFObject> colorSpaceValue; if (config == SkBitmap::kIndex8_Config || config == SkBitmap::kRLE_Index8_Config) { colorSpaceValue = makeIndexedColorSpace(bitmap.getColorTable()); } else { colorSpaceValue = new SkPDFName("DeviceRGB"); } colorSpaceValue->unref(); // SkRefPtr and new both took a reference. insert("ColorSpace", colorSpaceValue.get()); // } int bitsPerComp = bitmap.bytesPerPixel() * 2; if (bitsPerComp == 0) { SkASSERT(config == SkBitmap::kA1_Config); bitsPerComp = 1; } else if (bitsPerComp == 2 || (bitsPerComp == 4 && config == SkBitmap::kRGB_565_Config)) { bitsPerComp = 8; } SkRefPtr<SkPDFInt> bitsPerCompValue = new SkPDFInt(bitsPerComp); bitsPerCompValue->unref(); // SkRefPtr and new both took a reference. insert("BitsPerComponent", bitsPerCompValue.get()); if (config == SkBitmap::kRGB_565_Config) { SkRefPtr<SkPDFInt> zeroVal = new SkPDFInt(0); zeroVal->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFScalar> scale5Val = new SkPDFScalar(8.2258); // 255/2^5-1 scale5Val->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFScalar> scale6Val = new SkPDFScalar(4.0476); // 255/2^6-1 scale6Val->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFArray> decodeValue = new SkPDFArray(); decodeValue->unref(); // SkRefPtr and new both took a reference. decodeValue->reserve(6); decodeValue->append(zeroVal.get()); decodeValue->append(scale5Val.get()); decodeValue->append(zeroVal.get()); decodeValue->append(scale6Val.get()); decodeValue->append(zeroVal.get()); decodeValue->append(scale5Val.get()); insert("Decode", decodeValue.get()); } } SkPDFImage::~SkPDFImage() {} void SkPDFImage::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { if (indirect) return emitIndirectObject(stream, catalog); fStream->emitObject(stream, catalog, indirect); } size_t SkPDFImage::getOutputSize(SkPDFCatalog* catalog, bool indirect) { if (indirect) return getIndirectOutputSize(catalog); return fStream->getOutputSize(catalog, indirect); } void SkPDFImage::insert(SkPDFName* key, SkPDFObject* value) { fStream->insert(key, value); } void SkPDFImage::insert(const char key[], SkPDFObject* value) { fStream->insert(key, value); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> struct Node { Node* left; Node* right; Node* p; int v; }; Node* search(Node* tree, int value) { Node* c = tree; while (c != nullptr && c->v != value) { if (value < c->v) { c = c->left; } else { c = c->right; } } return c; } Node* min(Node* tree) { if (tree == nullptr) { return nullptr; } while (tree->left != nullptr) { tree = tree->left; } return tree; } Node* max(Node* tree) { if (tree == nullptr) { return nullptr; } while (tree->right != nullptr) { tree = tree->right; } return tree; } Node* successor(Node* node) { if (node == nullptr) { return nullptr; } Node* successor = node->right; if (successor != nullptr) { while (successor->left != nullptr) { successor = successor->left; } } else { successor = node->p; while (successor != nullptr && successor->right == node) { node = successor; successor = node->p; } } return successor; } void insert(Node** root, Node* newNode) { if (newNode == nullptr) { return; } if (root == nullptr || *root == nullptr) { *root = newNode; newNode->p = nullptr; return; } Node* current = *root; Node* temp = current; while (current != nullptr) { temp = current; if (newNode->v < current->v) { current = current->left; } else { current = current->right; } }; newNode->p = temp; if (newNode->v < temp->v) { temp->left = newNode; } else { temp->right = newNode; } } int main() { Node* tree = nullptr; std::vector<int> input = { 15, 6, 18, 3, 7, 17, 20, 2, 4, 13, 9 }; for (auto iter = input.begin(); iter != input.end(); ++iter) { Node* n = new Node(); n->v = *iter; insert(&tree, n); } // Search Node* s = search(tree, 15); std::cout << "search result : " << s->v << std::endl; // Min Node* minNode = min(tree); std::cout << "min result : " << minNode->v << std::endl; // Max Node* maxNode = max(tree); std::cout << "max result : " << maxNode->v << std::endl; // Successor Node* successorNode = successor(s); std::cout << "successor of " << s->v << " is " << successorNode->v << std::endl; // Release allocated memories of the tree. Node* c = tree; Node* p = nullptr; while (c != nullptr) { p = c; if (c->left != nullptr) { c = c->left; } else if (c->right != nullptr) { c = c->right; } else { p = c->p; if (p == nullptr) { delete c; c = nullptr; continue; } if (c->v < p->v) { p->left = nullptr; } else { p->right = nullptr; } delete c; c = p; } } return 0; } <commit_msg>Fixed a bug for BST implementation.<commit_after>#include <iostream> #include <vector> struct Node { Node* left; Node* right; Node* p; int v; }; Node* search(Node* tree, int value) { Node* c = tree; while (c != nullptr && c->v != value) { if (value < c->v) { c = c->left; } else { c = c->right; } } return c; } Node* min(Node* tree) { if (tree == nullptr) { return nullptr; } while (tree->left != nullptr) { tree = tree->left; } return tree; } Node* max(Node* tree) { if (tree == nullptr) { return nullptr; } while (tree->right != nullptr) { tree = tree->right; } return tree; } Node* successor(Node* node) { if (node == nullptr) { return nullptr; } Node* successor = node->right; if (successor != nullptr) { while (successor->left != nullptr) { successor = successor->left; } } else { successor = node->p; while (successor != nullptr && successor->right == node) { node = successor; successor = node->p; } } return successor; } void insert(Node** root, Node* newNode) { if (newNode == nullptr || root == nullptr) { return; } if (*root == nullptr) { *root = newNode; newNode->p = nullptr; return; } Node* current = *root; Node* temp = current; while (current != nullptr) { temp = current; if (newNode->v < current->v) { current = current->left; } else { current = current->right; } }; newNode->p = temp; if (newNode->v < temp->v) { temp->left = newNode; } else { temp->right = newNode; } } int main() { Node* tree = nullptr; std::vector<int> input = { 15, 6, 18, 3, 7, 17, 20, 2, 4, 13, 9 }; for (auto iter = input.begin(); iter != input.end(); ++iter) { Node* n = new Node(); n->v = *iter; insert(&tree, n); } // Search Node* s = search(tree, 15); std::cout << "search result : " << s->v << std::endl; // Min Node* minNode = min(tree); std::cout << "min result : " << minNode->v << std::endl; // Max Node* maxNode = max(tree); std::cout << "max result : " << maxNode->v << std::endl; // Successor Node* successorNode = successor(s); std::cout << "successor of " << s->v << " is " << successorNode->v << std::endl; // Release allocated memories of the tree. Node* c = tree; Node* p = nullptr; while (c != nullptr) { p = c; if (c->left != nullptr) { c = c->left; } else if (c->right != nullptr) { c = c->right; } else { p = c->p; if (p == nullptr) { delete c; c = nullptr; continue; } if (c->v < p->v) { p->left = nullptr; } else { p->right = nullptr; } delete c; c = p; } } return 0; } <|endoftext|>
<commit_before>#include "phase_unfolder.hpp" #include <iostream> #include <map> namespace vg { PhaseUnfolder::PhaseUnfolder(const xg::XG& xg_index, const gbwt::GBWT& gbwt_index, vg::id_t next_node) : xg_index(xg_index), gbwt_index(gbwt_index), mapping(next_node) { } void PhaseUnfolder::unfold(VG& graph, bool show_progress) { std::list<VG> components = this->complement_components(graph, show_progress); size_t haplotype_paths = 0; VG unfolded; for (VG& component : components) { haplotype_paths += this->unfold_component(component, graph, unfolded); } if (show_progress) { std::cerr << "Unfolded graph: " << unfolded.node_count() << " nodes, " << unfolded.edge_count() << " edges on " << haplotype_paths << " paths" << std::endl; } graph.extend(unfolded); } void PhaseUnfolder::write_mapping(const std::string& filename) const { std::ofstream out(filename, std::ios_base::binary); if (!out) { std::cerr << "[PhaseUnfolder]: cannot create mapping file " << filename << std::endl; return; } this->mapping.serialize(out); out.close(); } void PhaseUnfolder::read_mapping(const std::string& filename) { std::ifstream in(filename, std::ios_base::binary); if (!in) { std::cerr << "[PhaseUnfolder]: cannot open mapping file " << filename << std::endl; return; } this->mapping.load(in); in.close(); } vg::id_t PhaseUnfolder::get_mapping(vg::id_t node) const { return this->mapping(node); } std::list<VG> PhaseUnfolder::complement_components(VG& graph, bool show_progress) { VG complement; // Add missing edges supported by XG paths. for (size_t path_rank = 1; path_rank <= this->xg_index.max_path_rank(); path_rank++) { const xg::XGPath& path = this->xg_index.get_path(this->xg_index.path_name(path_rank)); size_t path_length = path.ids.size(); if (path_length == 0) { continue; } gbwt::node_type prev = gbwt::Node::encode(path.node(0), path.is_reverse(0)); for (size_t i = 1; i < path_length; i++) { gbwt::node_type curr = gbwt::Node::encode(path.node(i), path.is_reverse(i)); Edge candidate = xg::make_edge(gbwt::Node::id(prev), gbwt::Node::is_reverse(prev), gbwt::Node::id(curr), gbwt::Node::is_reverse(curr)); if (!graph.has_edge(candidate)) { complement.add_node(this->xg_index.node(candidate.from())); complement.add_node(this->xg_index.node(candidate.to())); complement.add_edge(candidate); } prev = curr; } } // Add missing edges supported by GBWT threads. for (gbwt::comp_type comp = 1; comp < this->gbwt_index.effective(); comp++) { gbwt::node_type gbwt_node = this->gbwt_index.toNode(comp); std::vector<gbwt::edge_type> outgoing = this->gbwt_index.edges(gbwt_node); for (gbwt::edge_type outedge : outgoing) { if (outedge.first == gbwt::ENDMARKER) { continue; } Edge candidate = xg::make_edge(gbwt::Node::id(gbwt_node), gbwt::Node::is_reverse(gbwt_node), gbwt::Node::id(outedge.first), gbwt::Node::is_reverse(outedge.first)); if (!graph.has_edge(candidate)) { complement.add_node(this->xg_index.node(candidate.from())); complement.add_node(this->xg_index.node(candidate.to())); complement.add_edge(candidate); } } } std::list<VG> components; complement.disjoint_subgraphs(components); if (show_progress) { std::cerr << "Complement graph: " << complement.node_count() << " nodes, " << complement.edge_count() << " edges in " << components.size() << " components" << std::endl; } return components; } size_t PhaseUnfolder::unfold_component(VG& component, VG& graph, VG& unfolded) { // Find the border nodes shared between the component and the graph. component.for_each_node([&](Node* node) { if (graph.has_node(node->id())) { this->border.insert(node->id()); } }); // Generate the paths starting from each border node. for (vg::id_t start_node : this->border) { this->generate_paths(component, start_node); this->generate_threads(component, start_node); } size_t haplotype_paths = this->paths.size(); // Unfold the generated paths. We merge duplicated nodes by shared // prefixes in the first half of the path and by shared suffixes in // the second half. Needless duplication would otherwise make GCSA2 // index construction too expensive. std::map<path_type, vg::id_t> node_by_prefix, node_by_suffix; for (const path_type& path : this->paths) { Node prev = this->xg_index.node(gbwt::Node::id(path.front())); unfolded.add_node(prev); for (size_t i = 1; i < path.size(); i++) { Node curr = this->xg_index.node(gbwt::Node::id(path[i])); bool is_prefix = (i < (path.size() + 1) / 2); bool is_suffix = !is_prefix & (i + 1 < path.size()); if (is_prefix) { auto iter = node_by_prefix.emplace(path_type(path.begin(), path.begin() + i + 1), 0).first; if (iter->second == 0) { // No cached node with the same prefix. iter->second = this->mapping.insert(curr.id()); } curr.set_id(iter->second); } else if (is_suffix) { auto iter = node_by_suffix.emplace(path_type(path.begin() + i, path.end()), 0).first; if (iter->second == 0) { // No cached node with the same suffix. iter->second = this->mapping.insert(curr.id()); } curr.set_id(iter->second); } unfolded.add_node(curr); Edge edge = xg::make_edge(prev.id(), gbwt::Node::is_reverse(path[i - 1]), curr.id(), gbwt::Node::is_reverse(path[i])); unfolded.add_edge(edge); prev = curr; } } this->border.clear(); this->paths.clear(); return haplotype_paths; } // TODO: Also generate paths backwards. void PhaseUnfolder::generate_paths(VG& component, vg::id_t from) { static int component_id = 0; for (size_t path_rank = 1; path_rank <= this->xg_index.max_path_rank(); path_rank++) { const xg::XGPath& path = this->xg_index.get_path(this->xg_index.path_name(path_rank)); size_t path_length = path.ids.size(); std::vector<size_t> occurrences = this->xg_index.node_ranks_in_path(from, path_rank); for (size_t occurrence : occurrences) { gbwt::node_type prev = gbwt::Node::encode(path.node(occurrence), path.is_reverse(occurrence)); path_type buffer { prev }; bool found_border = false; for (size_t i = occurrence + 1; i < path_length; i++) { gbwt::node_type curr = gbwt::Node::encode(path.node(i), path.is_reverse(i)); Edge candidate = xg::make_edge(gbwt::Node::id(prev), gbwt::Node::is_reverse(prev), gbwt::Node::id(curr), gbwt::Node::is_reverse(curr)); if (!component.has_edge(candidate)) { break; } buffer.push_back(curr); if (this->border.find(gbwt::Node::id(curr)) != this->border.end()) { this->insert_path(buffer); // Insert a border-to-border path. found_border = true; break; } prev = curr; } if (!found_border) { this->insert_path(buffer); // Insert a maximal path. } } } } void PhaseUnfolder::generate_threads(VG& component, vg::id_t from) { this->create_state(from, false); this->create_state(from, true); while (!this->states.empty()) { state_type state = this->states.top(); this->states.pop(); vg::id_t node = gbwt::Node::id(state.second.back()); bool is_reverse = gbwt::Node::is_reverse(state.second.back()); std::vector<Edge*> edges = component.edges_of(component.get_node(node)); bool was_extended = false; for (Edge* edge : edges) { if (edge->from() == node && edge->from_start() == is_reverse) { was_extended = this->extend_state(state, edge->to(), edge->to_end()); } else if (edge->to() == node && edge->to_end() != is_reverse) { was_extended = this->extend_state(state, edge->from(), !edge->from_start()); } } if (!was_extended || this->border.find(node) != this->border.end()) { this->insert_path(state.second); } } } void PhaseUnfolder::create_state(vg::id_t node, bool is_reverse) { search_type search = this->gbwt_index.find(gbwt::Node::encode(node, is_reverse)); if (search.empty()) { return; } this->states.push(std::make_pair(search, path_type {search.node})); } bool PhaseUnfolder::extend_state(state_type state, vg::id_t node, bool is_reverse) { state.first = this->gbwt_index.extend(state.first, gbwt::Node::encode(node, is_reverse)); if (state.first.empty()) { return false; } state.second.push_back(state.first.node); this->states.push(state); return true; } void PhaseUnfolder::insert_path(const path_type& path) { if (path.size() < 2) { return; } path_type reverse_complement(path.size(), 0); for (size_t i = 0; i < path.size(); i++) { reverse_complement[path.size() - 1 - i] = gbwt::Node::reverse(path[i]); } this->paths.insert(std::min(path, reverse_complement)); } } <commit_msg>Also unfold the reverse reference<commit_after>#include "phase_unfolder.hpp" #include <iostream> #include <map> namespace vg { PhaseUnfolder::PhaseUnfolder(const xg::XG& xg_index, const gbwt::GBWT& gbwt_index, vg::id_t next_node) : xg_index(xg_index), gbwt_index(gbwt_index), mapping(next_node) { } void PhaseUnfolder::unfold(VG& graph, bool show_progress) { std::list<VG> components = this->complement_components(graph, show_progress); size_t haplotype_paths = 0; VG unfolded; for (VG& component : components) { haplotype_paths += this->unfold_component(component, graph, unfolded); } if (show_progress) { std::cerr << "Unfolded graph: " << unfolded.node_count() << " nodes, " << unfolded.edge_count() << " edges on " << haplotype_paths << " paths" << std::endl; } graph.extend(unfolded); } void PhaseUnfolder::write_mapping(const std::string& filename) const { std::ofstream out(filename, std::ios_base::binary); if (!out) { std::cerr << "[PhaseUnfolder]: cannot create mapping file " << filename << std::endl; return; } this->mapping.serialize(out); out.close(); } void PhaseUnfolder::read_mapping(const std::string& filename) { std::ifstream in(filename, std::ios_base::binary); if (!in) { std::cerr << "[PhaseUnfolder]: cannot open mapping file " << filename << std::endl; return; } this->mapping.load(in); in.close(); } vg::id_t PhaseUnfolder::get_mapping(vg::id_t node) const { return this->mapping(node); } std::list<VG> PhaseUnfolder::complement_components(VG& graph, bool show_progress) { VG complement; // Add missing edges supported by XG paths. for (size_t path_rank = 1; path_rank <= this->xg_index.max_path_rank(); path_rank++) { const xg::XGPath& path = this->xg_index.get_path(this->xg_index.path_name(path_rank)); size_t path_length = path.ids.size(); if (path_length == 0) { continue; } gbwt::node_type prev = gbwt::Node::encode(path.node(0), path.is_reverse(0)); for (size_t i = 1; i < path_length; i++) { gbwt::node_type curr = gbwt::Node::encode(path.node(i), path.is_reverse(i)); Edge candidate = xg::make_edge(gbwt::Node::id(prev), gbwt::Node::is_reverse(prev), gbwt::Node::id(curr), gbwt::Node::is_reverse(curr)); if (!graph.has_edge(candidate)) { complement.add_node(this->xg_index.node(candidate.from())); complement.add_node(this->xg_index.node(candidate.to())); complement.add_edge(candidate); } prev = curr; } } // Add missing edges supported by GBWT threads. for (gbwt::comp_type comp = 1; comp < this->gbwt_index.effective(); comp++) { gbwt::node_type gbwt_node = this->gbwt_index.toNode(comp); std::vector<gbwt::edge_type> outgoing = this->gbwt_index.edges(gbwt_node); for (gbwt::edge_type outedge : outgoing) { if (outedge.first == gbwt::ENDMARKER) { continue; } Edge candidate = xg::make_edge(gbwt::Node::id(gbwt_node), gbwt::Node::is_reverse(gbwt_node), gbwt::Node::id(outedge.first), gbwt::Node::is_reverse(outedge.first)); if (!graph.has_edge(candidate)) { complement.add_node(this->xg_index.node(candidate.from())); complement.add_node(this->xg_index.node(candidate.to())); complement.add_edge(candidate); } } } std::list<VG> components; complement.disjoint_subgraphs(components); if (show_progress) { std::cerr << "Complement graph: " << complement.node_count() << " nodes, " << complement.edge_count() << " edges in " << components.size() << " components" << std::endl; } return components; } size_t PhaseUnfolder::unfold_component(VG& component, VG& graph, VG& unfolded) { // Find the border nodes shared between the component and the graph. component.for_each_node([&](Node* node) { if (graph.has_node(node->id())) { this->border.insert(node->id()); } }); // Generate the paths starting from each border node. for (vg::id_t start_node : this->border) { this->generate_paths(component, start_node); this->generate_threads(component, start_node); } size_t haplotype_paths = this->paths.size(); // Unfold the generated paths. We merge duplicated nodes by shared // prefixes in the first half of the path and by shared suffixes in // the second half. Needless duplication would otherwise make GCSA2 // index construction too expensive. std::map<path_type, vg::id_t> node_by_prefix, node_by_suffix; for (const path_type& path : this->paths) { Node prev = this->xg_index.node(gbwt::Node::id(path.front())); unfolded.add_node(prev); for (size_t i = 1; i < path.size(); i++) { Node curr = this->xg_index.node(gbwt::Node::id(path[i])); bool is_prefix = (i < (path.size() + 1) / 2); bool is_suffix = !is_prefix & (i + 1 < path.size()); if (is_prefix) { auto iter = node_by_prefix.emplace(path_type(path.begin(), path.begin() + i + 1), 0).first; if (iter->second == 0) { // No cached node with the same prefix. iter->second = this->mapping.insert(curr.id()); } curr.set_id(iter->second); } else if (is_suffix) { auto iter = node_by_suffix.emplace(path_type(path.begin() + i, path.end()), 0).first; if (iter->second == 0) { // No cached node with the same suffix. iter->second = this->mapping.insert(curr.id()); } curr.set_id(iter->second); } unfolded.add_node(curr); Edge edge = xg::make_edge(prev.id(), gbwt::Node::is_reverse(path[i - 1]), curr.id(), gbwt::Node::is_reverse(path[i])); unfolded.add_edge(edge); prev = curr; } } this->border.clear(); this->paths.clear(); return haplotype_paths; } void PhaseUnfolder::generate_paths(VG& component, vg::id_t from) { static int component_id = 0; for (size_t path_rank = 1; path_rank <= this->xg_index.max_path_rank(); path_rank++) { const xg::XGPath& path = this->xg_index.get_path(this->xg_index.path_name(path_rank)); size_t path_length = path.ids.size(); std::vector<size_t> occurrences = this->xg_index.node_ranks_in_path(from, path_rank); for (size_t occurrence : occurrences) { // Forward. { gbwt::node_type prev = gbwt::Node::encode(path.node(occurrence), path.is_reverse(occurrence)); path_type buffer { prev }; for (size_t i = occurrence + 1; i < path_length; i++) { gbwt::node_type curr = gbwt::Node::encode(path.node(i), path.is_reverse(i)); Edge candidate = xg::make_edge(gbwt::Node::id(prev), gbwt::Node::is_reverse(prev), gbwt::Node::id(curr), gbwt::Node::is_reverse(curr)); if (!component.has_edge(candidate)) { break; // Found a maximal path. } buffer.push_back(curr); if (this->border.find(gbwt::Node::id(curr)) != this->border.end()) { break; // Found a border-to-border path. } prev = curr; } this->insert_path(buffer); } // Backward. { gbwt::node_type prev = gbwt::Node::encode(path.node(occurrence), !path.is_reverse(occurrence)); path_type buffer { prev }; bool found_border = false; for (size_t i = occurrence; i > 0 ; i--) { gbwt::node_type curr = gbwt::Node::encode(path.node(i - 1), !path.is_reverse(i - 1)); Edge candidate = xg::make_edge(gbwt::Node::id(prev), gbwt::Node::is_reverse(prev), gbwt::Node::id(curr), gbwt::Node::is_reverse(curr)); if (!component.has_edge(candidate)) { break; // Found a maximal path. } buffer.push_back(curr); if (this->border.find(gbwt::Node::id(curr)) != this->border.end()) { break; // Found a border-to-border path. } prev = curr; } this->insert_path(buffer); } } } } void PhaseUnfolder::generate_threads(VG& component, vg::id_t from) { this->create_state(from, false); this->create_state(from, true); while (!this->states.empty()) { state_type state = this->states.top(); this->states.pop(); vg::id_t node = gbwt::Node::id(state.second.back()); bool is_reverse = gbwt::Node::is_reverse(state.second.back()); std::vector<Edge*> edges = component.edges_of(component.get_node(node)); bool was_extended = false; for (Edge* edge : edges) { if (edge->from() == node && edge->from_start() == is_reverse) { was_extended = this->extend_state(state, edge->to(), edge->to_end()); } else if (edge->to() == node && edge->to_end() != is_reverse) { was_extended = this->extend_state(state, edge->from(), !edge->from_start()); } } if (!was_extended || this->border.find(node) != this->border.end()) { this->insert_path(state.second); } } } void PhaseUnfolder::create_state(vg::id_t node, bool is_reverse) { search_type search = this->gbwt_index.find(gbwt::Node::encode(node, is_reverse)); if (search.empty()) { return; } this->states.push(std::make_pair(search, path_type {search.node})); } bool PhaseUnfolder::extend_state(state_type state, vg::id_t node, bool is_reverse) { state.first = this->gbwt_index.extend(state.first, gbwt::Node::encode(node, is_reverse)); if (state.first.empty()) { return false; } state.second.push_back(state.first.node); this->states.push(state); return true; } void PhaseUnfolder::insert_path(const path_type& path) { if (path.size() < 2) { return; } path_type reverse_complement(path.size(), 0); for (size_t i = 0; i < path.size(); i++) { reverse_complement[path.size() - 1 - i] = gbwt::Node::reverse(path[i]); } this->paths.insert(std::min(path, reverse_complement)); } } <|endoftext|>
<commit_before>#include <unordered_map> #include <string> #include "imgui.h" #include "app_config.h" #include "console_log.h" typedef void(*PFN_EXECUTE_COMMAND)(const std::string &); class CGuiConsole { public: static inline CGuiConsole& singleton() { static CGuiConsole s_console; return s_console; } void draw() { ImGui::SetNextWindowSize(ImVec2(m_width, m_height), ImGuiCond_Always); if (!ImGui::Begin("console", 0, m_flags)) { ImGui::End(); return; } const auto &style = ImGui::GetStyle(); float progress_bar_height = 4; ImGui::SetCursorPosX(style.WindowPadding.x * 0.5f); ImGui::ProgressBar(0, ImVec2(ImGui::GetWindowWidth() - style.WindowPadding.x, progress_bar_height), ""); ImGui::Separator(); // BEGIN log ImGui::BeginChild("console_log", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing() - progress_bar_height - style.ItemSpacing.y), false, ImGuiWindowFlags_HorizontalScrollbar); CConsoleLogger *logger = LOGGER_GET(CConsoleLogger); for (auto &str : *logger) { draw_log(str); } ImGui::EndChild(); // END log // BEGIN input ImGui::Separator(); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); if (ImGui::InputText("", m_input_beg, m_input_max, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory, [] (ImGuiTextEditCallbackData *ctx) -> int { ((CGuiConsole*)ctx)->on_input_end(); return 0; }, (void*)this)) { if (!m_input_beg[0]) return; logger->output(m_input_buf); std::string cmd_name = strtok(m_input_beg, " "); if (cmd_name == "help") { for (auto &it : m_commands) log_info("- %s\t\t%s", it.first.c_str(), it.second.second.c_str()); log_info("- help\t\tshow help"); } else { auto iter = m_commands.find(cmd_name); if (iter == m_commands.end()) log_error("Unkonwn command"); else iter->second.first(m_input_beg + cmd_name.size() + 1); } m_input_beg[0] = 0; } ImGui::PopItemWidth(); // Demonstrate keeping auto focus on the input box if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget // END input ImGui::End(); // END console } void on_input_end() { } void draw_log(const std::string &str) { static const std::pair<std::string, ImVec4> s_tag_color[] = { std::make_pair(std::string("# "), ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), std::make_pair(std::string("[ERROR]") , ImVec4(1.0f, 0.4f, 0.4f, 1.0f)), std::make_pair(std::string("[WARNING]"), ImVec4(1.0f, 1.0f, 0.0f, 1.0f)), }; for (auto &tag : s_tag_color) { if (!str.compare(0, tag.first.size(), tag.first)) { ImGui::PushStyleColor(ImGuiCol_Text, tag.second); ImGui::TextUnformatted(str.c_str()); ImGui::PopStyleColor(); return; } } ImGui::TextUnformatted(str.c_str()); } bool add_command(const char *cmd_name, PFN_EXECUTE_COMMAND func, const char *desc) { if (!func || !cmd_name || *cmd_name == 0) return false; auto &ret = m_commands.emplace(std::make_pair(cmd_name, std::make_pair(func, desc))); if (!ret.second) return false; return true; } private: int m_width, m_height; ImGuiWindowFlags m_flags; static constexpr size_t INPUT_BUFF_SIZE = 256; char m_input_buf[INPUT_BUFF_SIZE]; char *m_input_beg; size_t m_input_max; std::unordered_map<std::string, std::pair<PFN_EXECUTE_COMMAND, std::string>> m_commands; CGuiConsole() { m_width = int(AppConfig::window_width * 0.382f), m_height = int(AppConfig::window_height); m_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_ShowBorders; const char *prompt = "# "; size_t prompt_len = strlen(prompt); strncpy(m_input_buf, prompt, INPUT_BUFF_SIZE); m_input_beg = m_input_buf + prompt_len; m_input_max = INPUT_BUFF_SIZE - prompt_len; } }; bool console_command(const char *cmd_name, PFN_EXECUTE_COMMAND func, const char *desc) { auto &console = CGuiConsole::singleton(); return console.add_command(cmd_name, func, desc); } void show_console() { auto &console = CGuiConsole::singleton(); console.draw(); } <commit_msg>fix bugs<commit_after>#include <unordered_map> #include <string> #include "imgui.h" #include "app_config.h" #include "console_log.h" typedef void(*PFN_EXECUTE_COMMAND)(const std::string &); class CGuiConsole { public: static inline CGuiConsole& singleton() { static CGuiConsole s_console; return s_console; } void draw() { ImGui::SetNextWindowSize(ImVec2(m_width, m_height), ImGuiCond_Always); if (!ImGui::Begin("console", 0, m_flags)) { ImGui::End(); return; } const auto &style = ImGui::GetStyle(); float progress_bar_height = 4; ImGui::SetCursorPosX(style.WindowPadding.x * 0.5f); ImGui::ProgressBar(0, ImVec2(ImGui::GetWindowWidth() - style.WindowPadding.x, progress_bar_height), ""); ImGui::Separator(); // BEGIN log ImGui::BeginChild("console_log", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing() - progress_bar_height - style.ItemSpacing.y), false, ImGuiWindowFlags_HorizontalScrollbar); CConsoleLogger *logger = LOGGER_GET(CConsoleLogger); for (auto &str : *logger) { draw_log(str); } ImGui::EndChild(); // END log // BEGIN input ImGui::Separator(); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); if (ImGui::InputText("", m_input_beg, m_input_max, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory, [] (ImGuiTextEditCallbackData *ctx) -> int { ((CGuiConsole*)ctx)->on_input_end(); return 0; }, (void*)this)) { if (m_input_beg[0]) { logger->output(m_input_buf); process_input(); } m_input_beg[0] = 0; } ImGui::PopItemWidth(); // Demonstrate keeping auto focus on the input box if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget // END input ImGui::End(); // END console } void on_input_end() { } void process_input() { std::string cmd_name = strtok(m_input_beg, " "); if (cmd_name == "help") { for (auto &it : m_commands) log_info("- %s\t\t%s", it.first.c_str(), it.second.second.c_str()); log_info("- help\t\tshow help"); return; } auto iter = m_commands.find(cmd_name); if (iter == m_commands.end()) { log_error("Unkonwn command"); return; } iter->second.first(m_input_beg + cmd_name.size() + 1); } void draw_log(const std::string &str) { static const std::pair<std::string, ImVec4> s_tag_color[] = { std::make_pair(std::string("# "), ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), std::make_pair(std::string("[ERROR]") , ImVec4(1.0f, 0.4f, 0.4f, 1.0f)), std::make_pair(std::string("[WARNING]"), ImVec4(1.0f, 1.0f, 0.0f, 1.0f)), }; for (auto &tag : s_tag_color) { if (!str.compare(0, tag.first.size(), tag.first)) { ImGui::PushStyleColor(ImGuiCol_Text, tag.second); ImGui::TextUnformatted(str.c_str()); ImGui::PopStyleColor(); return; } } ImGui::TextUnformatted(str.c_str()); } bool add_command(const char *cmd_name, PFN_EXECUTE_COMMAND func, const char *desc) { if (!func || !cmd_name || *cmd_name == 0) return false; auto &ret = m_commands.emplace(std::make_pair(cmd_name, std::make_pair(func, desc))); if (!ret.second) return false; return true; } private: int m_width, m_height; ImGuiWindowFlags m_flags; static constexpr size_t INPUT_BUFF_SIZE = 256; char m_input_buf[INPUT_BUFF_SIZE]; char *m_input_beg; size_t m_input_max; std::unordered_map<std::string, std::pair<PFN_EXECUTE_COMMAND, std::string>> m_commands; CGuiConsole() { m_width = int(AppConfig::window_width * 0.382f), m_height = int(AppConfig::window_height); m_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_ShowBorders; const char *prompt = "# "; size_t prompt_len = strlen(prompt); strncpy(m_input_buf, prompt, INPUT_BUFF_SIZE); m_input_beg = m_input_buf + prompt_len; m_input_max = INPUT_BUFF_SIZE - prompt_len; } }; bool console_command(const char *cmd_name, PFN_EXECUTE_COMMAND func, const char *desc) { auto &console = CGuiConsole::singleton(); return console.add_command(cmd_name, func, desc); } void show_console() { auto &console = CGuiConsole::singleton(); console.draw(); } <|endoftext|>
<commit_before>/** * Copyright (c) 2004 David Faure <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "compactionjob.h" #include "kmfolder.h" #include "broadcaststatus.h" using KPIM::BroadcastStatus; #include "kmfoldermbox.h" #include "kmfoldermaildir.h" #include <kdebug.h> #include <klocale.h> #include <QFile> #include <QFileInfo> #include <QDir> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> using namespace KMail; // Look at this number of messages in each slotDoWork call #define COMPACTIONJOB_NRMESSAGES 100 // And wait this number of milliseconds before calling it again #define COMPACTIONJOB_TIMERINTERVAL 100 MboxCompactionJob::MboxCompactionJob( KMFolder* folder, bool immediate ) : ScheduledJob( folder, immediate ), mTimer( this ), mTmpFile( 0 ), mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false ) { } MboxCompactionJob::~MboxCompactionJob() { } void MboxCompactionJob::kill() { Q_ASSERT( mCancellable ); // We must close the folder if we opened it and got interrupted if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() ) { mSrcFolder->storage()->close( "mboxcompact" ); } if ( mTmpFile ) { fclose( mTmpFile ); } mTmpFile = 0; if ( !mTempName.isEmpty() ) { QFile::remove( mTempName ); } FolderJob::kill(); } QString MboxCompactionJob::realLocation() const { QString location = mSrcFolder->location(); QFileInfo inf( location ); if (inf.isSymLink()) { KUrl u; u.setPath( location ); // follow (and resolve) symlinks so that the final ::rename() always works // KUrl gives us support for absolute and relative links transparently. return KUrl( u, inf.readLink() ).path(); } return location; } int MboxCompactionJob::executeNow( bool silent ) { mSilent = silent; FolderStorage *storage = mSrcFolder->storage(); KMFolderMbox *mbox = static_cast<KMFolderMbox *>( storage ); if ( !storage->compactable() ) { kDebug(5006) << storage->location() <<" compaction skipped."; if ( !mSilent ) { QString str = i18n( "For safety reasons, compaction has been disabled for %1", mbox->label() ); BroadcastStatus::instance()->setStatusMsg( str ); } return 0; } kDebug(5006) <<"Compacting" << mSrcFolder->idString(); if ( KMFolderIndex::IndexOk != mbox->indexStatus() ) { kDebug(5006) <<"Critical error:" << storage->location() << "has been modified by an external application while KMail was running."; // exit(1); backed out due to broken nfs } const QFileInfo pathInfo( realLocation() ); // Use /dir/.mailboxname.compacted so that it's hidden, and doesn't show up after restarting kmail // (e.g. due to an unfortunate crash while compaction is happening) mTempName = pathInfo.path() + "/." + pathInfo.fileName() + ".compacted"; mode_t old_umask = umask( 077 ); mTmpFile = fopen( QFile::encodeName( mTempName ), "w" ); umask( old_umask ); if (!mTmpFile) { kWarning(5006) <<"Couldn't start compacting" << mSrcFolder->label() << ":" << strerror( errno ) << "while creating" << mTempName; return errno; } mOpeningFolder = true; // Ignore open-notifications while opening the folder storage->open( "mboxcompact" ); mOpeningFolder = false; mFolderOpen = true; mOffset = 0; mCurrentIndex = 0; kDebug(5006) <<"MboxCompactionJob: starting to compact folder" << mSrcFolder->location() << "into" << mTempName; connect( &mTimer, SIGNAL( timeout() ), SLOT( slotDoWork() ) ); if ( !mImmediate ) { mTimer.start( COMPACTIONJOB_TIMERINTERVAL ); } slotDoWork(); return mErrorCode; } void MboxCompactionJob::slotDoWork() { // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction. KMFolderMbox *mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() ); bool bDone = false; int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES; int rc = mbox->compact( mCurrentIndex, nbMessages, mTmpFile, mOffset /*in-out*/, bDone /*out*/ ); if ( !mImmediate ) mCurrentIndex += COMPACTIONJOB_NRMESSAGES; if ( rc || bDone ) // error, or finished done( rc ); } void MboxCompactionJob::done( int rc ) { mTimer.stop(); mCancellable = false; KMFolderMbox *mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() ); if ( !rc ) { rc = fflush( mTmpFile ); } if ( !rc ) { rc = fsync( fileno( mTmpFile ) ); } rc |= fclose( mTmpFile ); QString str; if ( !rc ) { bool autoCreate = mbox->autoCreateIndex(); QString box( realLocation() ); ::rename( QFile::encodeName( mTempName ), QFile::encodeName( box ) ); mbox->writeIndex(); mbox->writeConfig(); mbox->setAutoCreateIndex( false ); mbox->close( "mboxcompact", true ); mbox->setAutoCreateIndex( autoCreate ); mbox->setNeedsCompacting( false ); // We are clean now str = i18n( "Folder \"%1\" successfully compacted", mSrcFolder->label() ); kDebug(5006) << str; } else { mbox->close( "mboxcompact" ); str = i18n( "Error occurred while compacting \"%1\". Compaction aborted.", mSrcFolder->label() ); kDebug(5006) <<"Error occurred while compacting" << mbox->location(); kDebug(5006) <<"Compaction aborted."; QFile::remove( mTempName ); } mErrorCode = rc; if ( !mSilent ) BroadcastStatus::instance()->setStatusMsg( str ); mFolderOpen = false; deleteLater(); // later, because of the "return mErrorCode" } //// MaildirCompactionJob::MaildirCompactionJob( KMFolder* folder, bool immediate ) : ScheduledJob( folder, immediate ), mTimer( this ), mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false ) { } MaildirCompactionJob::~MaildirCompactionJob() { } void MaildirCompactionJob::kill() { Q_ASSERT( mCancellable ); // We must close the folder if we opened it and got interrupted if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() ) { mSrcFolder->storage()->close( "maildircompact" ); } FolderJob::kill(); } int MaildirCompactionJob::executeNow( bool silent ) { mSilent = silent; KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); kDebug(5006) <<"Compacting" << mSrcFolder->idString(); mOpeningFolder = true; // Ignore open-notifications while opening the folder storage->open( "maildircompact" ); mOpeningFolder = false; mFolderOpen = true; QString subdirNew( storage->location() + "/new/" ); QDir d( subdirNew ); mEntryList = d.entryList(); mCurrentIndex = 0; kDebug(5006) <<"MaildirCompactionJob: starting to compact in folder" << mSrcFolder->location(); connect( &mTimer, SIGNAL( timeout() ), SLOT( slotDoWork() ) ); if ( !mImmediate ) { mTimer.start( COMPACTIONJOB_TIMERINTERVAL ); } slotDoWork(); return mErrorCode; } void MaildirCompactionJob::slotDoWork() { // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction. KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); bool bDone = false; int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES; int rc = storage->compact( mCurrentIndex, nbMessages, mEntryList, bDone /*out*/ ); if ( !mImmediate ) mCurrentIndex += COMPACTIONJOB_NRMESSAGES; if ( rc || bDone ) // error, or finished done( rc ); } void MaildirCompactionJob::done( int rc ) { KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); mTimer.stop(); mCancellable = false; QString str; if ( !rc ) { str = i18n( "Folder \"%1\" successfully compacted", mSrcFolder->label() ); } else { str = i18n( "Error occurred while compacting \"%1\". Compaction aborted.", mSrcFolder->label() ); } mErrorCode = rc; storage->setNeedsCompacting( false ); storage->close( "maildircompact" ); if ( storage->isOpened() ) { storage->updateIndex(); } if ( !mSilent ) { BroadcastStatus::instance()->setStatusMsg( str ); } mFolderOpen = false; deleteLater(); // later, because of the "return mErrorCode" } ScheduledJob *ScheduledCompactionTask::run() { if ( !folder() || !folder()->needsCompacting() ) return 0; switch( folder()->storage()->folderType() ) { case KMFolderTypeMbox: return new MboxCompactionJob( folder(), isImmediate() ); case KMFolderTypeCachedImap: case KMFolderTypeMaildir: return new MaildirCompactionJob( folder(), isImmediate() ); default: // imap, search, unknown... return 0; } } #include "compactionjob.moc" <commit_msg>Need unistd for fsync()<commit_after>/** * Copyright (c) 2004 David Faure <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "compactionjob.h" #include "kmfolder.h" #include "broadcaststatus.h" using KPIM::BroadcastStatus; #include "kmfoldermbox.h" #include "kmfoldermaildir.h" #include <kdebug.h> #include <klocale.h> #include <QFile> #include <QFileInfo> #include <QDir> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> using namespace KMail; // Look at this number of messages in each slotDoWork call #define COMPACTIONJOB_NRMESSAGES 100 // And wait this number of milliseconds before calling it again #define COMPACTIONJOB_TIMERINTERVAL 100 MboxCompactionJob::MboxCompactionJob( KMFolder* folder, bool immediate ) : ScheduledJob( folder, immediate ), mTimer( this ), mTmpFile( 0 ), mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false ) { } MboxCompactionJob::~MboxCompactionJob() { } void MboxCompactionJob::kill() { Q_ASSERT( mCancellable ); // We must close the folder if we opened it and got interrupted if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() ) { mSrcFolder->storage()->close( "mboxcompact" ); } if ( mTmpFile ) { fclose( mTmpFile ); } mTmpFile = 0; if ( !mTempName.isEmpty() ) { QFile::remove( mTempName ); } FolderJob::kill(); } QString MboxCompactionJob::realLocation() const { QString location = mSrcFolder->location(); QFileInfo inf( location ); if (inf.isSymLink()) { KUrl u; u.setPath( location ); // follow (and resolve) symlinks so that the final ::rename() always works // KUrl gives us support for absolute and relative links transparently. return KUrl( u, inf.readLink() ).path(); } return location; } int MboxCompactionJob::executeNow( bool silent ) { mSilent = silent; FolderStorage *storage = mSrcFolder->storage(); KMFolderMbox *mbox = static_cast<KMFolderMbox *>( storage ); if ( !storage->compactable() ) { kDebug(5006) << storage->location() <<" compaction skipped."; if ( !mSilent ) { QString str = i18n( "For safety reasons, compaction has been disabled for %1", mbox->label() ); BroadcastStatus::instance()->setStatusMsg( str ); } return 0; } kDebug(5006) <<"Compacting" << mSrcFolder->idString(); if ( KMFolderIndex::IndexOk != mbox->indexStatus() ) { kDebug(5006) <<"Critical error:" << storage->location() << "has been modified by an external application while KMail was running."; // exit(1); backed out due to broken nfs } const QFileInfo pathInfo( realLocation() ); // Use /dir/.mailboxname.compacted so that it's hidden, and doesn't show up after restarting kmail // (e.g. due to an unfortunate crash while compaction is happening) mTempName = pathInfo.path() + "/." + pathInfo.fileName() + ".compacted"; mode_t old_umask = umask( 077 ); mTmpFile = fopen( QFile::encodeName( mTempName ), "w" ); umask( old_umask ); if (!mTmpFile) { kWarning(5006) <<"Couldn't start compacting" << mSrcFolder->label() << ":" << strerror( errno ) << "while creating" << mTempName; return errno; } mOpeningFolder = true; // Ignore open-notifications while opening the folder storage->open( "mboxcompact" ); mOpeningFolder = false; mFolderOpen = true; mOffset = 0; mCurrentIndex = 0; kDebug(5006) <<"MboxCompactionJob: starting to compact folder" << mSrcFolder->location() << "into" << mTempName; connect( &mTimer, SIGNAL( timeout() ), SLOT( slotDoWork() ) ); if ( !mImmediate ) { mTimer.start( COMPACTIONJOB_TIMERINTERVAL ); } slotDoWork(); return mErrorCode; } void MboxCompactionJob::slotDoWork() { // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction. KMFolderMbox *mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() ); bool bDone = false; int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES; int rc = mbox->compact( mCurrentIndex, nbMessages, mTmpFile, mOffset /*in-out*/, bDone /*out*/ ); if ( !mImmediate ) mCurrentIndex += COMPACTIONJOB_NRMESSAGES; if ( rc || bDone ) // error, or finished done( rc ); } void MboxCompactionJob::done( int rc ) { mTimer.stop(); mCancellable = false; KMFolderMbox *mbox = static_cast<KMFolderMbox *>( mSrcFolder->storage() ); if ( !rc ) { rc = fflush( mTmpFile ); } if ( !rc ) { rc = fsync( fileno( mTmpFile ) ); } rc |= fclose( mTmpFile ); QString str; if ( !rc ) { bool autoCreate = mbox->autoCreateIndex(); QString box( realLocation() ); ::rename( QFile::encodeName( mTempName ), QFile::encodeName( box ) ); mbox->writeIndex(); mbox->writeConfig(); mbox->setAutoCreateIndex( false ); mbox->close( "mboxcompact", true ); mbox->setAutoCreateIndex( autoCreate ); mbox->setNeedsCompacting( false ); // We are clean now str = i18n( "Folder \"%1\" successfully compacted", mSrcFolder->label() ); kDebug(5006) << str; } else { mbox->close( "mboxcompact" ); str = i18n( "Error occurred while compacting \"%1\". Compaction aborted.", mSrcFolder->label() ); kDebug(5006) <<"Error occurred while compacting" << mbox->location(); kDebug(5006) <<"Compaction aborted."; QFile::remove( mTempName ); } mErrorCode = rc; if ( !mSilent ) BroadcastStatus::instance()->setStatusMsg( str ); mFolderOpen = false; deleteLater(); // later, because of the "return mErrorCode" } //// MaildirCompactionJob::MaildirCompactionJob( KMFolder* folder, bool immediate ) : ScheduledJob( folder, immediate ), mTimer( this ), mCurrentIndex( 0 ), mFolderOpen( false ), mSilent( false ) { } MaildirCompactionJob::~MaildirCompactionJob() { } void MaildirCompactionJob::kill() { Q_ASSERT( mCancellable ); // We must close the folder if we opened it and got interrupted if ( mFolderOpen && mSrcFolder && mSrcFolder->storage() ) { mSrcFolder->storage()->close( "maildircompact" ); } FolderJob::kill(); } int MaildirCompactionJob::executeNow( bool silent ) { mSilent = silent; KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); kDebug(5006) <<"Compacting" << mSrcFolder->idString(); mOpeningFolder = true; // Ignore open-notifications while opening the folder storage->open( "maildircompact" ); mOpeningFolder = false; mFolderOpen = true; QString subdirNew( storage->location() + "/new/" ); QDir d( subdirNew ); mEntryList = d.entryList(); mCurrentIndex = 0; kDebug(5006) <<"MaildirCompactionJob: starting to compact in folder" << mSrcFolder->location(); connect( &mTimer, SIGNAL( timeout() ), SLOT( slotDoWork() ) ); if ( !mImmediate ) { mTimer.start( COMPACTIONJOB_TIMERINTERVAL ); } slotDoWork(); return mErrorCode; } void MaildirCompactionJob::slotDoWork() { // No need to worry about mSrcFolder==0 here. The FolderStorage deletes the jobs on destruction. KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); bool bDone = false; int nbMessages = mImmediate ? -1 /*all*/ : COMPACTIONJOB_NRMESSAGES; int rc = storage->compact( mCurrentIndex, nbMessages, mEntryList, bDone /*out*/ ); if ( !mImmediate ) mCurrentIndex += COMPACTIONJOB_NRMESSAGES; if ( rc || bDone ) // error, or finished done( rc ); } void MaildirCompactionJob::done( int rc ) { KMFolderMaildir *storage = static_cast<KMFolderMaildir *>( mSrcFolder->storage() ); mTimer.stop(); mCancellable = false; QString str; if ( !rc ) { str = i18n( "Folder \"%1\" successfully compacted", mSrcFolder->label() ); } else { str = i18n( "Error occurred while compacting \"%1\". Compaction aborted.", mSrcFolder->label() ); } mErrorCode = rc; storage->setNeedsCompacting( false ); storage->close( "maildircompact" ); if ( storage->isOpened() ) { storage->updateIndex(); } if ( !mSilent ) { BroadcastStatus::instance()->setStatusMsg( str ); } mFolderOpen = false; deleteLater(); // later, because of the "return mErrorCode" } ScheduledJob *ScheduledCompactionTask::run() { if ( !folder() || !folder()->needsCompacting() ) return 0; switch( folder()->storage()->folderType() ) { case KMFolderTypeMbox: return new MboxCompactionJob( folder(), isImmediate() ); case KMFolderTypeCachedImap: case KMFolderTypeMaildir: return new MaildirCompactionJob( folder(), isImmediate() ); default: // imap, search, unknown... return 0; } } #include "compactionjob.moc" <|endoftext|>
<commit_before> // Player.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "Player.h" #include "MainFrm.h" #include "PlayerDoc.h" #include "PlayerView.h" #include "PlayerViewD2D.h" #include "I420Effect.h" #include "AsyncGetUrlUnderMouseCursor.h" #include <boost/log/sinks/debug_output_backend.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/core/core.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/expressions.hpp> #include <boost/log/trivial.hpp> #ifdef _DEBUG #define new DEBUG_NEW #endif //#define USE_DIRECT2D_VIEW namespace { void init_logging() { namespace expr = boost::log::expressions; boost::log::add_common_attributes(); auto core = boost::log::core::get(); // Create the sink. The backend requires synchronization in the frontend. auto sink(boost::make_shared<boost::log::sinks::synchronous_sink<boost::log::sinks::debug_output_backend>>()); sink->set_formatter(expr::stream << expr::if_(expr::has_attr("Severity")) [ expr::stream << '[' << expr::attr< boost::log::trivial::severity_level >("Severity") << ']' ] << expr::if_(expr::has_attr("Channel")) [ expr::stream << '[' << expr::attr< std::string >("Channel") << ']' ] << expr::smessage << '\n'); // Set the special filter to the frontend // in order to skip the sink when no debugger is available //sink->set_filter(expr::is_debugger_present()); core->add_sink(sink); } } // namespace // CPlayerApp BEGIN_MESSAGE_MAP(CPlayerApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CPlayerApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) ON_THREAD_MESSAGE(WM_ON_ASYNC_URL, &CPlayerApp::OnAsyncUrl) END_MESSAGE_MAP() // CPlayerApp construction CPlayerApp::CPlayerApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("Player.AppID.NoVersion")); // Place all significant initialization in InitInstance init_logging(); } // The one and only CPlayerApp object CPlayerApp theApp; // CPlayerApp initialization BOOL CPlayerApp::InitInstance() { CPane::m_bHandleMinSize = true; // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrls); __super::InitInstance(); AfxOleInit(); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) { AsyncGetUrlUnderMouseCursor(); } #ifdef USE_DIRECT2D_VIEW if (AfxGetD2DState()->GetDirect2dFactory() == NULL) { return FALSE; } HRESULT hr_create = I420Effect::Register(static_cast<ID2D1Factory1*>(AfxGetD2DState()->GetDirect2dFactory())); if (FAILED(hr_create)) { return FALSE; } #endif // USE_DIRECT2D_VIEW EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("FFMPEG Player")); LoadStdProfileSettings(_AFX_MRU_MAX_COUNT); // Load standard INI file options (including MRU) // MFC Feature Pack InitContextMenuManager(); InitShellManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()-> SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CPlayerDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window #ifdef USE_DIRECT2D_VIEW RUNTIME_CLASS(CPlayerViewD2D)); #else RUNTIME_CLASS(CPlayerView)); #endif if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } // CPlayerApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; CString m_videoProperties; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_VIDEO_PROPERTIES, m_videoProperties); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() CPlayerDoc* CPlayerApp::GetPlayerDocument() { POSITION pos1 = GetFirstDocTemplatePosition(); if (CDocTemplate* templ = GetNextDocTemplate(pos1)) { POSITION pos2 = templ->GetFirstDocPosition(); return dynamic_cast<CPlayerDoc*>(templ->GetNextDoc(pos2)); } return nullptr; } // App command to run the dialog void CPlayerApp::OnAppAbout() { CAboutDlg aboutDlg; if (CPlayerDoc* doc = GetPlayerDocument()) { const auto properties = doc->getFrameDecoder()->getProperties(); for (const auto& prop : properties) { if (!aboutDlg.m_videoProperties.IsEmpty()) aboutDlg.m_videoProperties += '\n'; aboutDlg.m_videoProperties += prop.c_str(); } } aboutDlg.DoModal(); } void CPlayerApp::OnAsyncUrl(WPARAM wParam, LPARAM) { CComBSTR url; url.Attach((BSTR)wParam); if (CPlayerDoc* doc = GetPlayerDocument()) { doc->OnAsyncUrl(CString(url)); } } // CPlayerApp message handlers <commit_msg>semi-transparent about box<commit_after> // Player.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "Player.h" #include "MainFrm.h" #include "PlayerDoc.h" #include "PlayerView.h" #include "PlayerViewD2D.h" #include "I420Effect.h" #include "AsyncGetUrlUnderMouseCursor.h" #include <boost/log/sinks/debug_output_backend.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/core/core.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/expressions.hpp> #include <boost/log/trivial.hpp> #ifdef _DEBUG #define new DEBUG_NEW #endif //#define USE_DIRECT2D_VIEW namespace { void init_logging() { namespace expr = boost::log::expressions; boost::log::add_common_attributes(); auto core = boost::log::core::get(); // Create the sink. The backend requires synchronization in the frontend. auto sink(boost::make_shared<boost::log::sinks::synchronous_sink<boost::log::sinks::debug_output_backend>>()); sink->set_formatter(expr::stream << expr::if_(expr::has_attr("Severity")) [ expr::stream << '[' << expr::attr< boost::log::trivial::severity_level >("Severity") << ']' ] << expr::if_(expr::has_attr("Channel")) [ expr::stream << '[' << expr::attr< std::string >("Channel") << ']' ] << expr::smessage << '\n'); // Set the special filter to the frontend // in order to skip the sink when no debugger is available //sink->set_filter(expr::is_debugger_present()); core->add_sink(sink); } } // namespace // CPlayerApp BEGIN_MESSAGE_MAP(CPlayerApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CPlayerApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) ON_THREAD_MESSAGE(WM_ON_ASYNC_URL, &CPlayerApp::OnAsyncUrl) END_MESSAGE_MAP() // CPlayerApp construction CPlayerApp::CPlayerApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("Player.AppID.NoVersion")); // Place all significant initialization in InitInstance init_logging(); } // The one and only CPlayerApp object CPlayerApp theApp; // CPlayerApp initialization BOOL CPlayerApp::InitInstance() { CPane::m_bHandleMinSize = true; // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrls); __super::InitInstance(); AfxOleInit(); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) { AsyncGetUrlUnderMouseCursor(); } #ifdef USE_DIRECT2D_VIEW if (AfxGetD2DState()->GetDirect2dFactory() == NULL) { return FALSE; } HRESULT hr_create = I420Effect::Register(static_cast<ID2D1Factory1*>(AfxGetD2DState()->GetDirect2dFactory())); if (FAILED(hr_create)) { return FALSE; } #endif // USE_DIRECT2D_VIEW EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("FFMPEG Player")); LoadStdProfileSettings(_AFX_MRU_MAX_COUNT); // Load standard INI file options (including MRU) // MFC Feature Pack InitContextMenuManager(); InitShellManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()-> SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CPlayerDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window #ifdef USE_DIRECT2D_VIEW RUNTIME_CLASS(CPlayerViewD2D)); #else RUNTIME_CLASS(CPlayerView)); #endif if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } // CPlayerApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); BOOL OnInitDialog() override; // Dialog Data enum { IDD = IDD_ABOUTBOX }; CString m_videoProperties; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } BOOL CAboutDlg::OnInitDialog() { ModifyStyleEx(0, WS_EX_LAYERED); SetLayeredWindowAttributes(0, (255 * 75) / 100, LWA_ALPHA); return __super::OnInitDialog(); } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_VIDEO_PROPERTIES, m_videoProperties); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() CPlayerDoc* CPlayerApp::GetPlayerDocument() { POSITION pos1 = GetFirstDocTemplatePosition(); if (CDocTemplate* templ = GetNextDocTemplate(pos1)) { POSITION pos2 = templ->GetFirstDocPosition(); return dynamic_cast<CPlayerDoc*>(templ->GetNextDoc(pos2)); } return nullptr; } // App command to run the dialog void CPlayerApp::OnAppAbout() { CAboutDlg aboutDlg; if (CPlayerDoc* doc = GetPlayerDocument()) { const auto properties = doc->getFrameDecoder()->getProperties(); for (const auto& prop : properties) { if (!aboutDlg.m_videoProperties.IsEmpty()) aboutDlg.m_videoProperties += '\n'; aboutDlg.m_videoProperties += prop.c_str(); } } aboutDlg.DoModal(); } void CPlayerApp::OnAsyncUrl(WPARAM wParam, LPARAM) { CComBSTR url; url.Attach((BSTR)wParam); if (CPlayerDoc* doc = GetPlayerDocument()) { doc->OnAsyncUrl(CString(url)); } } // CPlayerApp message handlers <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "DivNode.h" #include "SDLDisplayEngine.h" #include "Player.h" #include "NodeDefinition.h" #include "../base/Point.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/StringHelper.h" #include "../base/FileHelper.h" #include "../base/MathHelper.h" #include <iostream> #include <sstream> using namespace std; using namespace boost; namespace avg { NodeDefinition DivNode::createDefinition() { string sChildArray[] = {"image", "div", "canvas", "words", "video", "camera", "panoimage", "sound", "line", "rect", "curve", "polyline", "polygon", "circle"}; vector<string> sChildren = vectorFromCArray( sizeof(sChildArray) / sizeof(*sChildArray), sChildArray); return NodeDefinition("div", Node::buildNode<DivNode>) .extendDefinition(AreaNode::createDefinition()) .addChildren(sChildren) .addArg(Arg<bool>("crop", true, false, offsetof(DivNode, m_bCrop))) .addArg(Arg<string>("elementoutlinecolor", "", false, offsetof(DivNode, m_sElementOutlineColor))) .addArg(Arg<string>("mediadir", "", false, offsetof(DivNode, m_sMediaDir))); } DivNode::DivNode(const ArgList& Args, bool) { Args.setMembers(this); setElementOutlineColor(m_sElementOutlineColor); } DivNode::~DivNode() { } void DivNode::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine) { AreaNode::setRenderingEngines(pDisplayEngine, pAudioEngine); for (int i = 0; i<(int)m_Children.size(); ++i) { m_Children[i]->setRenderingEngines(pDisplayEngine, pAudioEngine); } } void DivNode::connect() { AreaNode::connect(); for (int i = 0; i< (int)m_Children.size(); ++i) { m_Children[i]->connect(); } } void DivNode::disconnect() { for (int i = 0; i< (int)m_Children.size(); ++i) { m_Children[i]->disconnect(); } AreaNode::disconnect(); } bool DivNode::getCrop() const { return m_bCrop; } void DivNode::setCrop(bool bCrop) { m_bCrop = bCrop; } const std::string& DivNode::getElementOutlineColor() const { return m_sElementOutlineColor; } void DivNode::setElementOutlineColor(const std::string& sColor) { m_sElementOutlineColor = sColor; if (sColor == "") { m_ElementOutlineColor = Pixel32(0,0,0,0); } else { m_ElementOutlineColor = colorStringToColor(m_sElementOutlineColor); } } const string& DivNode::getMediaDir() const { return m_sMediaDir; } void DivNode::setMediaDir(const string& sMediaDir) { m_sMediaDir = sMediaDir; checkReload(); } int DivNode::getNumChildren() { return int(m_Children.size()); } const NodePtr& DivNode::getChild(unsigned i) { if (i >= m_Children.size()) { stringstream s; s << "Index " << i << " is out of range in DivNode::getChild()"; throw(Exception(AVG_ERR_OUT_OF_RANGE, s.str())); } return m_Children[i]; } void DivNode::appendChild(NodePtr pNewNode) { insertChild(pNewNode, unsigned(m_Children.size())); } void DivNode::insertChildBefore(NodePtr pNewNode, NodePtr pOldChild) { if (!pOldChild) { throw Exception(AVG_ERR_NO_NODE, getID()+"::insertChildBefore called without a node."); } unsigned i = indexOf(pOldChild); insertChild(pNewNode, i); } void DivNode::insertChild(NodePtr pNewNode, unsigned i) { if (!pNewNode) { throw Exception(AVG_ERR_NO_NODE, getID()+"::insertChild called without a node."); } if (!isChildTypeAllowed(pNewNode->getTypeStr())) { throw(Exception(AVG_ERR_ALREADY_CONNECTED, "Can't insert a node of type "+pNewNode->getTypeStr()+ " into a node of type "+getTypeStr()+".")); } if (pNewNode->getState() == NS_CONNECTED || pNewNode->getState() == NS_CANRENDER) { throw(Exception(AVG_ERR_ALREADY_CONNECTED, "Can't connect node with id "+pNewNode->getID()+ ": already connected.")); } if (i>m_Children.size()) { throw(Exception(AVG_ERR_OUT_OF_RANGE, pNewNode->getID()+"::insertChild: index out of bounds.")); } std::vector<NodePtr>::iterator Pos = m_Children.begin()+i; if (getState() == NS_CONNECTED || getState() == NS_CANRENDER) { Player::get()->registerNode(pNewNode); } m_Children.insert(Pos, pNewNode); DivNodePtr Ptr = boost::dynamic_pointer_cast<DivNode>(getThis()); pNewNode->setParent(Ptr, getState()); if (getState() == NS_CANRENDER) { pNewNode->setRenderingEngines(getDisplayEngine(), getAudioEngine()); } } void DivNode::removeChild(NodePtr pNode) { int i = indexOf(pNode); pNode->removeParent(); m_Children.erase(m_Children.begin()+i); } void DivNode::removeChild(unsigned i) { if (i>m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::removeChild: index "+toString(i)+" out of bounds.")); } NodePtr pNode = getChild(i); pNode->removeParent(); m_Children.erase(m_Children.begin()+i); } void DivNode::reorderChild(NodePtr pNode, unsigned j) { if (j > m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::reorderChild: index "+toString(j)+" out of bounds.")); } int i = indexOf(pNode); m_Children.erase(m_Children.begin()+i); std::vector<NodePtr>::iterator Pos = m_Children.begin()+j; m_Children.insert(Pos, pNode); } void DivNode::reorderChild(unsigned i, unsigned j) { if (i>m_Children.size()-1 || j > m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::reorderChild: index out of bounds.")); } NodePtr pNode = getChild(i); m_Children.erase(m_Children.begin()+i); std::vector<NodePtr>::iterator Pos = m_Children.begin()+j; m_Children.insert(Pos, pNode); } int DivNode::indexOf(NodePtr pChild) { if (!pChild) { throw Exception(AVG_ERR_NO_NODE, getID()+"::indexOf called without a node."); } for (int i = 0; i< (int)m_Children.size(); ++i) { if (m_Children[i] == pChild) { return i; } } throw(Exception(AVG_ERR_OUT_OF_RANGE, "indexOf: node '"+pChild->getID()+"' is not a child of node '" +getID()+"'")); } NodePtr DivNode::getElementByPos(const DPoint & pos) { if (pos.x >= 0 && pos.y >= 0 && pos.x < getSize().x && pos.y < getSize().y && reactsToMouseEvents()) { for (int i=getNumChildren()-1; i>=0; i--) { // TODO: Move coordinate handling to Node (& get rid of AreaNode entirely?) AreaNodePtr pCurChild = dynamic_pointer_cast<AreaNode>(getChild(i)); NodePtr pFoundNode; DPoint relPos; if (pCurChild) { relPos = pCurChild->toLocal(pos); pFoundNode = pCurChild->getElementByPos(relPos); } else { pFoundNode = getChild(i)->getElementByPos(pos); } if (pFoundNode) { return pFoundNode; } } // Pos isn't in any of the children. if (getSize() != DPoint(10000, 10000)) { // Explicit width/height given for div. return getThis(); } else { // Explicit width/height not given: div itself doesn't react. return NodePtr(); } } else { return NodePtr(); } } void DivNode::preRender() { Node::preRender(); for (int i=0; i<getNumChildren(); i++) { getChild(i)->preRender(); } } void DivNode::render(const DRect& rect) { DPoint Viewport = getSize(); if (getCrop()) { DRect ClipRect(0, 0, Viewport.x, Viewport.y); getDisplayEngine()->pushClipRect(ClipRect); } for (int i=0; i<getNumChildren(); i++) { getDisplayEngine()->pushShader(); getChild(i)->maybeRender(rect); getDisplayEngine()->popShader(); } if (getCrop()) { getDisplayEngine()->popClipRect(); } } void DivNode::renderOutlines(VertexArrayPtr pVA, Pixel32 color) { Pixel32 effColor = color; if (m_ElementOutlineColor != Pixel32(0,0,0,0)) { effColor = m_ElementOutlineColor; effColor.setA(128); } if (effColor != Pixel32(0,0,0,0)) { DPoint size = getSize(); if (size == DPoint(10000, 10000)) { DPoint p0 = getAbsPos(DPoint(-4, 0.5)); DPoint p1 = getAbsPos(DPoint(5, 0.5)); DPoint p2 = getAbsPos(DPoint(0.5, -4)); DPoint p3 = getAbsPos(DPoint(0.5, 5)); pVA->addLineData(effColor, p0, p1, 1); pVA->addLineData(effColor, p2, p3, 1); } else { DPoint p0 = getAbsPos(DPoint(0.5, 0.5)); DPoint p1 = getAbsPos(DPoint(size.x+0.5,0.5)); DPoint p2 = getAbsPos(DPoint(size.x+0.5,size.y+0.5)); DPoint p3 = getAbsPos(DPoint(0.5,size.y+0.5)); pVA->addLineData(effColor, p0, p1, 1); pVA->addLineData(effColor, p1, p2, 1); pVA->addLineData(effColor, p2, p3, 1); pVA->addLineData(effColor, p3, p0, 1); } } for (int i=0; i<getNumChildren(); i++) { getChild(i)->renderOutlines(pVA, effColor); } } string DivNode::getEffectiveMediaDir() { string sMediaDir = m_sMediaDir; if (!isAbsPath(sMediaDir)) { if (getParent()) { sMediaDir = getParent()->getEffectiveMediaDir()+m_sMediaDir; } else { sMediaDir = Player::get()->getRootMediaDir()+m_sMediaDir; } } if (sMediaDir[sMediaDir.length()-1] != '/') { sMediaDir += '/'; } return sMediaDir; } void DivNode::checkReload() { for(int i=0; i<getNumChildren(); ++i) { getChild(i)->checkReload(); } } string DivNode::dump(int indent) { string dumpStr = AreaNode::dump () + "\n"; vector<NodePtr>::iterator it; for (it=m_Children.begin(); it<m_Children.end(); it++) { dumpStr += (*it)->dump(indent+2)+"\n"; } return dumpStr; } IntPoint DivNode::getMediaSize() { return IntPoint(10000,10000); } bool DivNode::isChildTypeAllowed(const string& sType) { return getDefinition()->isChildAllowed(sType); } } <commit_msg>div nodes without size now pass events to children at negative coordinates.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "DivNode.h" #include "SDLDisplayEngine.h" #include "Player.h" #include "NodeDefinition.h" #include "../base/Point.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/StringHelper.h" #include "../base/FileHelper.h" #include "../base/MathHelper.h" #include <iostream> #include <sstream> using namespace std; using namespace boost; namespace avg { NodeDefinition DivNode::createDefinition() { string sChildArray[] = {"image", "div", "canvas", "words", "video", "camera", "panoimage", "sound", "line", "rect", "curve", "polyline", "polygon", "circle"}; vector<string> sChildren = vectorFromCArray( sizeof(sChildArray) / sizeof(*sChildArray), sChildArray); return NodeDefinition("div", Node::buildNode<DivNode>) .extendDefinition(AreaNode::createDefinition()) .addChildren(sChildren) .addArg(Arg<bool>("crop", true, false, offsetof(DivNode, m_bCrop))) .addArg(Arg<string>("elementoutlinecolor", "", false, offsetof(DivNode, m_sElementOutlineColor))) .addArg(Arg<string>("mediadir", "", false, offsetof(DivNode, m_sMediaDir))); } DivNode::DivNode(const ArgList& Args, bool) { Args.setMembers(this); setElementOutlineColor(m_sElementOutlineColor); } DivNode::~DivNode() { } void DivNode::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine) { AreaNode::setRenderingEngines(pDisplayEngine, pAudioEngine); for (int i = 0; i<(int)m_Children.size(); ++i) { m_Children[i]->setRenderingEngines(pDisplayEngine, pAudioEngine); } } void DivNode::connect() { AreaNode::connect(); for (int i = 0; i< (int)m_Children.size(); ++i) { m_Children[i]->connect(); } } void DivNode::disconnect() { for (int i = 0; i< (int)m_Children.size(); ++i) { m_Children[i]->disconnect(); } AreaNode::disconnect(); } bool DivNode::getCrop() const { return m_bCrop; } void DivNode::setCrop(bool bCrop) { m_bCrop = bCrop; } const std::string& DivNode::getElementOutlineColor() const { return m_sElementOutlineColor; } void DivNode::setElementOutlineColor(const std::string& sColor) { m_sElementOutlineColor = sColor; if (sColor == "") { m_ElementOutlineColor = Pixel32(0,0,0,0); } else { m_ElementOutlineColor = colorStringToColor(m_sElementOutlineColor); } } const string& DivNode::getMediaDir() const { return m_sMediaDir; } void DivNode::setMediaDir(const string& sMediaDir) { m_sMediaDir = sMediaDir; checkReload(); } int DivNode::getNumChildren() { return int(m_Children.size()); } const NodePtr& DivNode::getChild(unsigned i) { if (i >= m_Children.size()) { stringstream s; s << "Index " << i << " is out of range in DivNode::getChild()"; throw(Exception(AVG_ERR_OUT_OF_RANGE, s.str())); } return m_Children[i]; } void DivNode::appendChild(NodePtr pNewNode) { insertChild(pNewNode, unsigned(m_Children.size())); } void DivNode::insertChildBefore(NodePtr pNewNode, NodePtr pOldChild) { if (!pOldChild) { throw Exception(AVG_ERR_NO_NODE, getID()+"::insertChildBefore called without a node."); } unsigned i = indexOf(pOldChild); insertChild(pNewNode, i); } void DivNode::insertChild(NodePtr pNewNode, unsigned i) { if (!pNewNode) { throw Exception(AVG_ERR_NO_NODE, getID()+"::insertChild called without a node."); } if (!isChildTypeAllowed(pNewNode->getTypeStr())) { throw(Exception(AVG_ERR_ALREADY_CONNECTED, "Can't insert a node of type "+pNewNode->getTypeStr()+ " into a node of type "+getTypeStr()+".")); } if (pNewNode->getState() == NS_CONNECTED || pNewNode->getState() == NS_CANRENDER) { throw(Exception(AVG_ERR_ALREADY_CONNECTED, "Can't connect node with id "+pNewNode->getID()+ ": already connected.")); } if (i>m_Children.size()) { throw(Exception(AVG_ERR_OUT_OF_RANGE, pNewNode->getID()+"::insertChild: index out of bounds.")); } std::vector<NodePtr>::iterator Pos = m_Children.begin()+i; if (getState() == NS_CONNECTED || getState() == NS_CANRENDER) { Player::get()->registerNode(pNewNode); } m_Children.insert(Pos, pNewNode); DivNodePtr Ptr = boost::dynamic_pointer_cast<DivNode>(getThis()); pNewNode->setParent(Ptr, getState()); if (getState() == NS_CANRENDER) { pNewNode->setRenderingEngines(getDisplayEngine(), getAudioEngine()); } } void DivNode::removeChild(NodePtr pNode) { int i = indexOf(pNode); pNode->removeParent(); m_Children.erase(m_Children.begin()+i); } void DivNode::removeChild(unsigned i) { if (i>m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::removeChild: index "+toString(i)+" out of bounds.")); } NodePtr pNode = getChild(i); pNode->removeParent(); m_Children.erase(m_Children.begin()+i); } void DivNode::reorderChild(NodePtr pNode, unsigned j) { if (j > m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::reorderChild: index "+toString(j)+" out of bounds.")); } int i = indexOf(pNode); m_Children.erase(m_Children.begin()+i); std::vector<NodePtr>::iterator Pos = m_Children.begin()+j; m_Children.insert(Pos, pNode); } void DivNode::reorderChild(unsigned i, unsigned j) { if (i>m_Children.size()-1 || j > m_Children.size()-1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, getID()+"::reorderChild: index out of bounds.")); } NodePtr pNode = getChild(i); m_Children.erase(m_Children.begin()+i); std::vector<NodePtr>::iterator Pos = m_Children.begin()+j; m_Children.insert(Pos, pNode); } int DivNode::indexOf(NodePtr pChild) { if (!pChild) { throw Exception(AVG_ERR_NO_NODE, getID()+"::indexOf called without a node."); } for (int i = 0; i< (int)m_Children.size(); ++i) { if (m_Children[i] == pChild) { return i; } } throw(Exception(AVG_ERR_OUT_OF_RANGE, "indexOf: node '"+pChild->getID()+"' is not a child of node '" +getID()+"'")); } NodePtr DivNode::getElementByPos(const DPoint & pos) { if (reactsToMouseEvents() && ((getSize() == DPoint(10000, 10000) || (pos.x >= 0 && pos.y >= 0 && pos.x < getSize().x && pos.y < getSize().y)))) { for (int i=getNumChildren()-1; i>=0; i--) { // TODO: Move coordinate handling to Node (& get rid of AreaNode entirely?) AreaNodePtr pCurChild = dynamic_pointer_cast<AreaNode>(getChild(i)); NodePtr pFoundNode; DPoint relPos; if (pCurChild) { relPos = pCurChild->toLocal(pos); pFoundNode = pCurChild->getElementByPos(relPos); } else { pFoundNode = getChild(i)->getElementByPos(pos); } if (pFoundNode) { return pFoundNode; } } // Pos isn't in any of the children. if (getSize() == DPoint(10000, 10000)) { // Explicit width/height not given: div itself doesn't react. return NodePtr(); } else { // Explicit width/height given for div. return getThis(); } } else { return NodePtr(); } } void DivNode::preRender() { Node::preRender(); for (int i=0; i<getNumChildren(); i++) { getChild(i)->preRender(); } } void DivNode::render(const DRect& rect) { DPoint Viewport = getSize(); if (getCrop()) { DRect ClipRect(0, 0, Viewport.x, Viewport.y); getDisplayEngine()->pushClipRect(ClipRect); } for (int i=0; i<getNumChildren(); i++) { getDisplayEngine()->pushShader(); getChild(i)->maybeRender(rect); getDisplayEngine()->popShader(); } if (getCrop()) { getDisplayEngine()->popClipRect(); } } void DivNode::renderOutlines(VertexArrayPtr pVA, Pixel32 color) { Pixel32 effColor = color; if (m_ElementOutlineColor != Pixel32(0,0,0,0)) { effColor = m_ElementOutlineColor; effColor.setA(128); } if (effColor != Pixel32(0,0,0,0)) { DPoint size = getSize(); if (size == DPoint(10000, 10000)) { DPoint p0 = getAbsPos(DPoint(-4, 0.5)); DPoint p1 = getAbsPos(DPoint(5, 0.5)); DPoint p2 = getAbsPos(DPoint(0.5, -4)); DPoint p3 = getAbsPos(DPoint(0.5, 5)); pVA->addLineData(effColor, p0, p1, 1); pVA->addLineData(effColor, p2, p3, 1); } else { DPoint p0 = getAbsPos(DPoint(0.5, 0.5)); DPoint p1 = getAbsPos(DPoint(size.x+0.5,0.5)); DPoint p2 = getAbsPos(DPoint(size.x+0.5,size.y+0.5)); DPoint p3 = getAbsPos(DPoint(0.5,size.y+0.5)); pVA->addLineData(effColor, p0, p1, 1); pVA->addLineData(effColor, p1, p2, 1); pVA->addLineData(effColor, p2, p3, 1); pVA->addLineData(effColor, p3, p0, 1); } } for (int i=0; i<getNumChildren(); i++) { getChild(i)->renderOutlines(pVA, effColor); } } string DivNode::getEffectiveMediaDir() { string sMediaDir = m_sMediaDir; if (!isAbsPath(sMediaDir)) { if (getParent()) { sMediaDir = getParent()->getEffectiveMediaDir()+m_sMediaDir; } else { sMediaDir = Player::get()->getRootMediaDir()+m_sMediaDir; } } if (sMediaDir[sMediaDir.length()-1] != '/') { sMediaDir += '/'; } return sMediaDir; } void DivNode::checkReload() { for(int i=0; i<getNumChildren(); ++i) { getChild(i)->checkReload(); } } string DivNode::dump(int indent) { string dumpStr = AreaNode::dump () + "\n"; vector<NodePtr>::iterator it; for (it=m_Children.begin(); it<m_Children.end(); it++) { dumpStr += (*it)->dump(indent+2)+"\n"; } return dumpStr; } IntPoint DivNode::getMediaSize() { return IntPoint(10000,10000); } bool DivNode::isChildTypeAllowed(const string& sType) { return getDefinition()->isChildAllowed(sType); } } <|endoftext|>
<commit_before>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/common/NativeProcessProtocol.h" #include "llvm/Testing/Support/Error.h" #include "gmock/gmock.h" using namespace lldb_private; using namespace lldb; using namespace testing; namespace { class MockDelegate : public NativeProcessProtocol::NativeDelegate { public: MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process)); MOCK_METHOD2(ProcessStateChanged, void(NativeProcessProtocol *Process, StateType State)); MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process)); }; class MockProcess : public NativeProcessProtocol { public: MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch, lldb::pid_t Pid = 1) : NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {} MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions)); MOCK_METHOD0(Halt, Status()); MOCK_METHOD0(Detach, Status()); MOCK_METHOD1(Signal, Status(int Signo)); MOCK_METHOD0(Kill, Status()); MOCK_METHOD3(AllocateMemory, Status(size_t Size, uint32_t Permissions, addr_t &Addr)); MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr)); MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t()); MOCK_METHOD0(UpdateThreads, size_t()); MOCK_CONST_METHOD0(GetAuxvData, llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>()); MOCK_METHOD2(GetLoadedModuleFileSpec, Status(const char *ModulePath, FileSpec &Spec)); MOCK_METHOD2(GetFileLoadAddress, Status(const llvm::StringRef &FileName, addr_t &Addr)); const ArchSpec &GetArchitecture() const override { return Arch; } Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size, bool Hardware) override { if (Hardware) return SetHardwareBreakpoint(Addr, Size); else return SetSoftwareBreakpoint(Addr, Size); } // Redirect base class Read/Write Memory methods to functions whose signatures // are more mock-friendly. Status ReadMemory(addr_t Addr, void *Buf, size_t Size, size_t &BytesRead) override; Status WriteMemory(addr_t Addr, const void *Buf, size_t Size, size_t &BytesWritten) override; MOCK_METHOD2(ReadMemory, llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size)); MOCK_METHOD2(WriteMemory, llvm::Expected<size_t>(addr_t Addr, llvm::ArrayRef<uint8_t> Data)); using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode; llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr, size_t Size); private: ArchSpec Arch; }; class FakeMemory { public: FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {} llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size); llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk); private: std::vector<uint8_t> Data; }; } // namespace Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size, size_t &BytesRead) { auto ExpectedMemory = ReadMemory(Addr, Size); if (!ExpectedMemory) { BytesRead = 0; return Status(ExpectedMemory.takeError()); } BytesRead = ExpectedMemory->size(); assert(BytesRead <= Size); std::memcpy(Buf, ExpectedMemory->data(), BytesRead); return Status(); } Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size, size_t &BytesWritten) { auto ExpectedBytes = WriteMemory( Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size)); if (!ExpectedBytes) { BytesWritten = 0; return Status(ExpectedBytes.takeError()); } BytesWritten = *ExpectedBytes; return Status(); } llvm::Expected<std::vector<uint8_t>> MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) { std::vector<uint8_t> Data(Size, 0); size_t BytesRead; Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap( Addr, Data.data(), Data.size(), BytesRead); if (ST.Fail()) return ST.ToError(); Data.resize(BytesRead); return std::move(Data); } llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr, size_t Size) { if (Addr >= Data.size()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Address out of range."); Size = std::min(Size, Data.size() - (size_t)Addr); auto Begin = std::next(Data.begin(), Addr); return std::vector<uint8_t>(Begin, std::next(Begin, Size)); } llvm::Expected<size_t> FakeMemory::Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk) { if (Addr >= Data.size()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Address out of range."); size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr); std::copy_n(Chunk.begin(), Size, &Data[Addr]); return Size; } TEST(NativeProcessProtocolTest, SetBreakpoint) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1))); EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Succeeded()); } TEST(NativeProcessProtocolTest, SetBreakpointFailRead) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1))); EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux")); FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; EXPECT_CALL(Process, ReadMemory(_, _)) .WillRepeatedly(Invoke(&M, &FakeMemory::Read)); EXPECT_CALL(Process, WriteMemory(_, _)) .WillRepeatedly(Invoke(&M, &FakeMemory::Write)); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(), llvm::Succeeded()); EXPECT_THAT_EXPECTED( Process.ReadMemoryWithoutTrap(0, 10), llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6), llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4), llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2), llvm::HasValue(std::vector<uint8_t>{6, 7})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2), llvm::HasValue(std::vector<uint8_t>{4, 5})); } <commit_msg>NativeProcessProtocolTest: fix -Winconsistent-missing-override warning<commit_after>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/common/NativeProcessProtocol.h" #include "llvm/Testing/Support/Error.h" #include "gmock/gmock.h" using namespace lldb_private; using namespace lldb; using namespace testing; namespace { class MockDelegate : public NativeProcessProtocol::NativeDelegate { public: MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process)); MOCK_METHOD2(ProcessStateChanged, void(NativeProcessProtocol *Process, StateType State)); MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process)); }; // NB: This class doesn't use the override keyword to avoid // -Winconsistent-missing-override warnings from the compiler. The // inconsistency comes from the overriding definitions in the MOCK_*** macros. class MockProcess : public NativeProcessProtocol { public: MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch, lldb::pid_t Pid = 1) : NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {} MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions)); MOCK_METHOD0(Halt, Status()); MOCK_METHOD0(Detach, Status()); MOCK_METHOD1(Signal, Status(int Signo)); MOCK_METHOD0(Kill, Status()); MOCK_METHOD3(AllocateMemory, Status(size_t Size, uint32_t Permissions, addr_t &Addr)); MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr)); MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t()); MOCK_METHOD0(UpdateThreads, size_t()); MOCK_CONST_METHOD0(GetAuxvData, llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>()); MOCK_METHOD2(GetLoadedModuleFileSpec, Status(const char *ModulePath, FileSpec &Spec)); MOCK_METHOD2(GetFileLoadAddress, Status(const llvm::StringRef &FileName, addr_t &Addr)); const ArchSpec &GetArchitecture() const /*override*/ { return Arch; } Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size, bool Hardware) /*override*/ { if (Hardware) return SetHardwareBreakpoint(Addr, Size); else return SetSoftwareBreakpoint(Addr, Size); } // Redirect base class Read/Write Memory methods to functions whose signatures // are more mock-friendly. Status ReadMemory(addr_t Addr, void *Buf, size_t Size, size_t &BytesRead) /*override*/; Status WriteMemory(addr_t Addr, const void *Buf, size_t Size, size_t &BytesWritten) /*override*/; MOCK_METHOD2(ReadMemory, llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size)); MOCK_METHOD2(WriteMemory, llvm::Expected<size_t>(addr_t Addr, llvm::ArrayRef<uint8_t> Data)); using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode; llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr, size_t Size); private: ArchSpec Arch; }; class FakeMemory { public: FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {} llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size); llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk); private: std::vector<uint8_t> Data; }; } // namespace Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size, size_t &BytesRead) { auto ExpectedMemory = ReadMemory(Addr, Size); if (!ExpectedMemory) { BytesRead = 0; return Status(ExpectedMemory.takeError()); } BytesRead = ExpectedMemory->size(); assert(BytesRead <= Size); std::memcpy(Buf, ExpectedMemory->data(), BytesRead); return Status(); } Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size, size_t &BytesWritten) { auto ExpectedBytes = WriteMemory( Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size)); if (!ExpectedBytes) { BytesWritten = 0; return Status(ExpectedBytes.takeError()); } BytesWritten = *ExpectedBytes; return Status(); } llvm::Expected<std::vector<uint8_t>> MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) { std::vector<uint8_t> Data(Size, 0); size_t BytesRead; Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap( Addr, Data.data(), Data.size(), BytesRead); if (ST.Fail()) return ST.ToError(); Data.resize(BytesRead); return std::move(Data); } llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr, size_t Size) { if (Addr >= Data.size()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Address out of range."); Size = std::min(Size, Data.size() - (size_t)Addr); auto Begin = std::next(Data.begin(), Addr); return std::vector<uint8_t>(Begin, std::next(Begin, Size)); } llvm::Expected<size_t> FakeMemory::Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk) { if (Addr >= Data.size()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Address out of range."); size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr); std::copy_n(Chunk.begin(), Size, &Data[Addr]); return Size; } TEST(NativeProcessProtocolTest, SetBreakpoint) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1))); EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Succeeded()); } TEST(NativeProcessProtocolTest, SetBreakpointFailRead) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux")); auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1)); InSequence S; EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb}))); EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1))); EXPECT_CALL(Process, ReadMemory(0x47, 1)) .WillOnce(Return(ByMove( llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo")))); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(), llvm::Failed()); } TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) { NiceMock<MockDelegate> DummyDelegate; MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux")); FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; EXPECT_CALL(Process, ReadMemory(_, _)) .WillRepeatedly(Invoke(&M, &FakeMemory::Read)); EXPECT_CALL(Process, WriteMemory(_, _)) .WillRepeatedly(Invoke(&M, &FakeMemory::Write)); EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(), llvm::Succeeded()); EXPECT_THAT_EXPECTED( Process.ReadMemoryWithoutTrap(0, 10), llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6), llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4), llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2), llvm::HasValue(std::vector<uint8_t>{6, 7})); EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2), llvm::HasValue(std::vector<uint8_t>{4, 5})); } <|endoftext|>