text
stringlengths
54
60.6k
<commit_before>// // sequence.cpp // express // // Created by Adam Roberts on 1/24/12. // Copyright 2012 Adam Roberts. All rights reserved. // #include "sequence.h" #include <cassert> #include <boost/math/distributions/normal.hpp> using namespace std; using namespace boost::math; SequenceFwd::SequenceFwd(): _ref_seq(NULL), _len(0), _prob(0){} SequenceFwd::SequenceFwd(const std::string& seq, bool rev, bool prob) : _ref_seq(NULL), _len(seq.length()), _prob(prob) { if (prob) { _est_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, 0.001); _obs_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, HUGE_VAL); _exp_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, HUGE_VAL); } set(seq, rev); } SequenceFwd::SequenceFwd(const SequenceFwd& other) : _ref_seq(NULL), _obs_seq(other._obs_seq), _exp_seq(other._exp_seq), _len(other.length()), _prob(other._prob) { if (other._ref_seq) { char* ref_seq = new char[_len]; std::copy(other._ref_seq, other._ref_seq + _len, ref_seq); _ref_seq = ref_seq; } } SequenceFwd& SequenceFwd::operator=(const SequenceFwd& other) { if (other._ref_seq) { _len = other.length(); char* ref_seq = new char[_len]; std::copy(other._ref_seq, other._ref_seq + _len, ref_seq); _ref_seq = ref_seq; _obs_seq = other._obs_seq; _exp_seq = other._exp_seq; _prob = other._prob; } return *this; } SequenceFwd::~SequenceFwd() { if (_ref_seq) delete _ref_seq; } void SequenceFwd::set(const std::string& seq, bool rev) { if (_ref_seq) delete _ref_seq; char* ref_seq = new char[seq.length()]; for(size_t i = 0; i < seq.length(); i++) { ref_seq[i] = (rev) ? complement(ctoi(seq[seq.length()-1-i])) : ctoi(seq[i]); if (_prob) { _est_seq.increment(i, ref_seq[i], log(2)); } } _ref_seq = ref_seq; _len = seq.length(); } size_t SequenceFwd::operator[](const size_t index) const { assert(index < _len); if (_prob) { return _est_seq.mode(index); } return _ref_seq[index]; } size_t SequenceFwd::get_ref(const size_t index) const { assert(index < _len); //assert(_ref_seq[index] == operator[](index)); return _ref_seq[index]; } float SequenceFwd::get_prob(const size_t index, const size_t nuc) const { assert(_prob); return _est_seq(index, nuc); } float SequenceFwd::get_obs(const size_t index, const size_t nuc) const { assert(index < _len); return _obs_seq(index,nuc,false); } float SequenceFwd::get_exp(const size_t index, const size_t nuc) const { assert(index < _len); return _exp_seq(index,nuc,false); } void SequenceFwd::update_est(const size_t index, const size_t nuc, float mass) { assert(_prob); _est_seq.increment(index, nuc, mass); } void SequenceFwd::update_obs(const size_t index, const size_t nuc, float mass) { assert(_prob); _obs_seq.increment(index, nuc, mass); } void SequenceFwd::update_exp(const size_t index, const size_t nuc, float mass) { assert(_prob); _exp_seq.increment(index, nuc, mass); } void SequenceFwd::calc_p_vals(vector<double>& p_vals) const { p_vals = vector<double>(_len, 1); for (size_t i = 0; i < _len; ++i) { double N = sexp(_obs_seq.total(i)); if (N==0) continue; size_t ref_nuc = get_ref(i); double p_val = HUGE_VAL; vector<double> cdfs(4); for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { if (nuc == ref_nuc) continue; double p = sexp(_exp_seq(i,nuc)); double obs_n = sexp(_obs_seq(i,nuc,false)); normal norm (N*p, sqrt(N*p*(1-p))); cdfs[nuc] = cdf(norm, obs_n); } for (size_t nuc1 = 0; nuc1 < NUM_NUCS; ++nuc1) { if (nuc1 == ref_nuc) continue; double term = log(1-cdfs[nuc1]); for(size_t nuc2 = 0; nuc2 < NUM_NUCS; ++nuc2) { if (nuc2 == nuc1 || nuc2 == ref_nuc) continue; term += log(cdfs[nuc2]); } p_val = log_sum(p_val, term); } p_vals[i] = sexp(p_val); } } /* void SequenceFwd::calc_p_vals(vector<double>& p_vals) const { p_vals = vector<double>(_len, 1.0); boost::math::chi_squared_distribution<double> chisq(3); double obs_n,exp_n; for (size_t i = 0; i < _len; ++i) { if (_obs_seq.total(i)==HUGE_VAL) continue; double S = 0; for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { obs_n = sexp(_obs_seq(i,nuc,false)); exp_n = sexp(_exp_seq(i,nuc,false)); S += (obs_n-exp_n)*(obs_n-exp_n)/exp_n; } p_vals[i] -= boost::math::cdf(chisq,S); } } */ void SequenceRev::calc_p_vals(vector<double>& p_vals) const { vector<double> temp; _seq->calc_p_vals(temp); p_vals = vector<double>(length()); for(size_t i = 0; i < length(); i++) { p_vals[i] = temp[length()-i-1]; } }<commit_msg>Switched p-val calculation to binomial/normal<commit_after>// // sequence.cpp // express // // Created by Adam Roberts on 1/24/12. // Copyright 2012 Adam Roberts. All rights reserved. // #include "sequence.h" #include <cassert> #include <boost/math/distributions/normal.hpp> using namespace std; using namespace boost::math; SequenceFwd::SequenceFwd(): _ref_seq(NULL), _len(0), _prob(0){} SequenceFwd::SequenceFwd(const std::string& seq, bool rev, bool prob) : _ref_seq(NULL), _len(seq.length()), _prob(prob) { if (prob) { _est_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, 0.001); _obs_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, HUGE_VAL); _exp_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, HUGE_VAL); } set(seq, rev); } SequenceFwd::SequenceFwd(const SequenceFwd& other) : _ref_seq(NULL), _obs_seq(other._obs_seq), _exp_seq(other._exp_seq), _len(other.length()), _prob(other._prob) { if (other._ref_seq) { char* ref_seq = new char[_len]; std::copy(other._ref_seq, other._ref_seq + _len, ref_seq); _ref_seq = ref_seq; } } SequenceFwd& SequenceFwd::operator=(const SequenceFwd& other) { if (other._ref_seq) { _len = other.length(); char* ref_seq = new char[_len]; std::copy(other._ref_seq, other._ref_seq + _len, ref_seq); _ref_seq = ref_seq; _obs_seq = other._obs_seq; _exp_seq = other._exp_seq; _prob = other._prob; } return *this; } SequenceFwd::~SequenceFwd() { if (_ref_seq) delete _ref_seq; } void SequenceFwd::set(const std::string& seq, bool rev) { if (_ref_seq) delete _ref_seq; char* ref_seq = new char[seq.length()]; for(size_t i = 0; i < seq.length(); i++) { ref_seq[i] = (rev) ? complement(ctoi(seq[seq.length()-1-i])) : ctoi(seq[i]); if (_prob) { _est_seq.increment(i, ref_seq[i], log(2)); } } _ref_seq = ref_seq; _len = seq.length(); } size_t SequenceFwd::operator[](const size_t index) const { assert(index < _len); if (_prob) { return _est_seq.mode(index); } return _ref_seq[index]; } size_t SequenceFwd::get_ref(const size_t index) const { assert(index < _len); //assert(_ref_seq[index] == operator[](index)); return _ref_seq[index]; } float SequenceFwd::get_prob(const size_t index, const size_t nuc) const { assert(_prob); return _est_seq(index, nuc); } float SequenceFwd::get_obs(const size_t index, const size_t nuc) const { assert(index < _len); return _obs_seq(index,nuc,false); } float SequenceFwd::get_exp(const size_t index, const size_t nuc) const { assert(index < _len); return _exp_seq(index,nuc,false); } void SequenceFwd::update_est(const size_t index, const size_t nuc, float mass) { assert(_prob); _est_seq.increment(index, nuc, mass); } void SequenceFwd::update_obs(const size_t index, const size_t nuc, float mass) { assert(_prob); _obs_seq.increment(index, nuc, mass); } void SequenceFwd::update_exp(const size_t index, const size_t nuc, float mass) { assert(_prob); _exp_seq.increment(index, nuc, mass); } void SequenceFwd::calc_p_vals(vector<double>& p_vals) const { p_vals = vector<double>(_len, 1.0); for (size_t i = 0; i < _len; ++i) { double N = sexp(_obs_seq.total(i)); if (N==0) continue; size_t ref_nuc = get_ref(i); double max_obs = 0; for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { if (nuc == ref_nuc) continue; double obs_n = sexp(_obs_seq(i,nuc,false)); max_obs = max(max_obs,obs_n); } double p_val = HUGE_VAL; for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { if (nuc == ref_nuc) continue; double obs_n = sexp(_obs_seq(i,nuc,false)); double exp_p = sexp(_exp_seq(i, nuc)); normal norm(N*exp_p, N*exp_p*(1-exp_p)); p_val = log_sum(p_val, log(cdf(norm, obs_n))); } p_vals[i] -= sexp(p_val); } } /* void SequenceFwd::calc_p_vals(vector<double>& p_vals) const { p_vals = vector<double>(_len, 1); for (size_t i = 0; i < _len; ++i) { double N = sexp(_obs_seq.total(i)); if (N==0) continue; size_t ref_nuc = get_ref(i); double p_val = HUGE_VAL; vector<double> cdfs(4); for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { if (nuc == ref_nuc) continue; double p = sexp(_exp_seq(i,nuc)); double obs_n = sexp(_obs_seq(i,nuc,false)); normal norm (N*p, sqrt(N*p*(1-p))); cdfs[nuc] = cdf(norm, obs_n); } for (size_t nuc1 = 0; nuc1 < NUM_NUCS; ++nuc1) { if (nuc1 == ref_nuc) continue; double term = log(1-cdfs[nuc1]); for(size_t nuc2 = 0; nuc2 < NUM_NUCS; ++nuc2) { if (nuc2 == nuc1 || nuc2 == ref_nuc) continue; term += log(cdfs[nuc2]); } p_val = log_sum(p_val, term); } p_vals[i] = sexp(p_val); } } */ /* void SequenceFwd::calc_p_vals(vector<double>& p_vals) const { p_vals = vector<double>(_len, 1.0); boost::math::chi_squared_distribution<double> chisq(3); double obs_n,exp_n; for (size_t i = 0; i < _len; ++i) { if (_obs_seq.total(i)==HUGE_VAL) continue; double S = 0; for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) { obs_n = sexp(_obs_seq(i,nuc,false)); exp_n = sexp(_exp_seq(i,nuc,false)); S += (obs_n-exp_n)*(obs_n-exp_n)/exp_n; } p_vals[i] -= boost::math::cdf(chisq,S); } } */ void SequenceRev::calc_p_vals(vector<double>& p_vals) const { vector<double> temp; _seq->calc_p_vals(temp); p_vals = vector<double>(length()); for(size_t i = 0; i < length(); i++) { p_vals[i] = temp[length()-i-1]; } }<|endoftext|>
<commit_before>#include <stdexcept> #include <algorithm> #include <map> #include "file_io.hpp" using namespace std; FastaStream& operator>>(FastaStream& stream, MSA& msa) { /* open the file */ auto file = pll_fasta_open(stream.fname().c_str(), pll_map_fasta); if (!file) throw runtime_error{"Cannot open file " + stream.fname()}; char * sequence = NULL; char * header = NULL; long sequence_length; long header_length; long sequence_number; /* read sequences and make sure they are all of the same length */ int sites = 0; /* read the rest */ while (pll_fasta_getnext(file, &header, &header_length, &sequence, &sequence_length, &sequence_number)) { if (!sites) { /* first sequence, init the MSA object */ if (sequence_length == -1 || sequence_length == 0) throw runtime_error{"Unable to read MSA file"}; sites = sequence_length; msa = MSA(sites); } else { if (sequence_length != sites) throw runtime_error{"MSA file does not contain equal size sequences"}; } /*trim trailing whitespace from the sequence label */ std::string label(header); label.erase(label.find_last_not_of(" \n\r\t")+1); msa.append(sequence, label); free(sequence); free(header); } if (pll_errno != PLL_ERROR_FILE_EOF) throw runtime_error{"Error while reading file: " + stream.fname()}; pll_fasta_close(file); libpll_reset_error(); return stream; } PhylipStream& operator>>(PhylipStream& stream, MSA& msa) { pll_phylip_t * fd = pll_phylip_open(stream.fname().c_str(), pll_map_phylip); if (!fd) throw runtime_error(pll_errmsg); pll_msa_t * pll_msa = stream.interleaved() ? pll_phylip_parse_interleaved(fd) : pll_phylip_parse_sequential(fd); pll_phylip_close(fd); if (pll_msa) { msa = MSA(pll_msa); pll_msa_destroy(pll_msa); } else throw runtime_error{"Unable to parse PHYLIP file: " + stream.fname()}; return stream; } PhylipStream& operator<<(PhylipStream& stream, const MSA& msa) { auto retval = pllmod_msa_save_phylip(msa.pll_msa(), stream.fname().c_str()); if (!retval) throw runtime_error{pll_errmsg}; return stream; } PhylipStream& operator<<(PhylipStream& stream, const PartitionedMSAView& msa) { ofstream fs(stream.fname()); auto taxa = msa.taxon_count(); auto sites = msa.total_sites(); fs << taxa << " " << sites << endl; for (size_t i = 0; i < taxa; ++i) { fs << msa.taxon_name(i) << " "; for (size_t p = 0; p < msa.part_count(); ++p) { fs << msa.part_sequence(i, p, true); } fs << endl; } return stream; } PhylipStream& operator<<(PhylipStream& stream, const PartitionedMSA& msa) { PartitionedMSAView msa_view(msa); return stream; } PhylipStream& operator<<(PhylipStream& stream, const BootstrapMSA& bs_msa) { ofstream fs(stream.fname()); const auto& msa = std::get<0>(bs_msa); const auto& bsrep = std::get<1>(bs_msa); auto taxa = msa.taxon_count(); auto sites = msa.total_sites(); fs << taxa << " " << sites << endl; for (size_t i = 0; i < taxa; ++i) { fs << msa.taxon_names().at(i) << " "; for (size_t p = 0; p < msa.part_count(); ++p) { const auto& w = bsrep.site_weights.at(p); const auto& m = msa.part_info(p).msa(); const auto& seq = m.at(i); assert(w.size() == seq.size()); size_t wsum = 0; for (size_t j = 0; j < seq.length(); ++j) { wsum += w[j]; for (size_t k = 0; k < w[j]; ++k) fs << seq[j]; } assert(wsum == m.num_sites()); } fs << endl; } return stream; } CATGStream& operator>>(CATGStream& stream, MSA& msa) { ifstream fs; fs.open(stream.fname()); /* read alignment dimensions */ size_t taxa_count, site_count; try { fs >> taxa_count >> site_count; } catch(exception& e) { LOG_DEBUG << e.what() << endl; taxa_count = site_count = 0; } if (!taxa_count || !site_count) throw runtime_error("Invalid alignment dimensions!"); LOG_DEBUG << "CATG: taxa: " << taxa_count << ", sites: " << site_count << endl; string dummy(site_count, '*'); /* read taxa names */ try { string taxon_name; for (size_t i = 0; i < taxa_count; ++i) { fs >> taxon_name; msa.append(dummy, taxon_name); LOG_DEBUG << "CATG: taxon " << i << ": " << taxon_name << endl; } } catch (exception& e) { LOG_DEBUG << e.what() << endl; } if (msa.size() != taxa_count) throw runtime_error("Wrong number of taxon labels!"); /* this is mapping for DNA: CATG -> ACGT, for other datatypes we assume 1:1 mapping */ std::vector<size_t> state_map({1, 0, 3, 2}); string cons_str, prob_str; /* read alignment, remember that the matrix is transposed! */ for (size_t i = 0; i < msa.num_sites(); ++i) { /* read consensus sequences */ fs >> cons_str; LOG_DEBUG << "CATG: site " << i << " consesus seq: " << cons_str << endl; if (cons_str.length() != msa.size()) throw runtime_error("Wrong length of consensus sequence for site " + to_string(i+1) + "!"); std::vector<double> probs; for (size_t j = 0; j < msa.size(); ++j) { msa[j][i] = cons_str[j]; fs >> prob_str; if (msa.states() == 0) { auto states = std::count_if(prob_str.cbegin(), prob_str.cend(), [](char c) -> bool { return c == ','; }) + 1; msa.states(states); /* see above: for datatypes other than DNA we assume 1:1 mapping */ if (states != 4) state_map.clear(); LOG_DEBUG << "CATG: number of states: " << states << endl; } auto site_probs = msa.probs(j, i); istringstream ss(prob_str); size_t k = 0; for (string token; getline(ss, token, ','); ++k) { if (state_map.empty()) site_probs[k] = stod(token); else site_probs[state_map[k]] = stod(token); } if (k != msa.states()) throw runtime_error("Wrong number of state probabilities for site " + to_string(i+1) + "!"); } } #ifdef CATG_DEBUG { PhylipStream ps("catgout.phy"); ps << msa; } #endif return stream; } MSA msa_load_from_file(const std::string &filename, const FileFormat format) { MSA msa; typedef pair<FileFormat, string> FormatNamePair; static vector<FormatNamePair> msa_formats = { {FileFormat::iphylip, "IPHYLIP"}, {FileFormat::phylip, "PHYLIP"}, {FileFormat::fasta, "FASTA"}, {FileFormat::catg, "CATG"}, {FileFormat::vcf, "VCF"}, {FileFormat::binary, "RAxML-binary"} }; auto fmt_begin = msa_formats.cbegin(); auto fmt_end = msa_formats.cend(); if (!sysutil_file_exists(filename)) throw runtime_error("File not found: " + filename); if (format != FileFormat::autodetect) { fmt_begin = std::find_if(msa_formats.begin(), msa_formats.end(), [format](const FormatNamePair& p) { return p.first == format; }); assert(fmt_begin != msa_formats.cend()); fmt_end = fmt_begin + 1; } for (; fmt_begin != fmt_end; fmt_begin++) { try { switch (fmt_begin->first) { case FileFormat::fasta: { FastaStream s(filename); s >> msa; return msa; break; } case FileFormat::iphylip: { PhylipStream s(filename, true); s >> msa; return msa; break; } case FileFormat::phylip: { PhylipStream s(filename, false); s >> msa; return msa; break; } case FileFormat::catg: { CATGStream s(filename); s >> msa; return msa; break; } default: throw runtime_error("Unsupported MSA file format!"); } } catch(exception &e) { libpll_reset_error(); if (format == FileFormat::autodetect) LOG_DEBUG << "Failed to load as " << fmt_begin->second << ": " << e.what() << endl; else throw runtime_error("Error loading MSA: " + string(e.what())); } } throw runtime_error("Error loading MSA: cannot parse any format supported by RAxML-NG!"); } <commit_msg>more informative error messages in case of PHYLIP/FASTA formatting issues<commit_after>#include <stdexcept> #include <algorithm> #include <map> #include "file_io.hpp" using namespace std; FastaStream& operator>>(FastaStream& stream, MSA& msa) { /* open the file */ auto file = pll_fasta_open(stream.fname().c_str(), pll_map_fasta); if (!file) libpll_check_error("Unable to parse FASTA file"); char * sequence = NULL; char * header = NULL; long sequence_length; long header_length; long sequence_number; /* read sequences and make sure they are all of the same length */ int sites = 0; /* read the rest */ while (pll_fasta_getnext(file, &header, &header_length, &sequence, &sequence_length, &sequence_number)) { if (!sites) { /* first sequence, init the MSA object */ if (sequence_length == -1 || sequence_length == 0) throw runtime_error{"Unable to parse FASTA file"}; sites = sequence_length; msa = MSA(sites); } else { if (sequence_length != sites) throw runtime_error{"FASTA file does not contain equal size sequences"}; } if (!header_length) { throw runtime_error{"FASTA file contains empty sequence label: " + to_string(msa.size() + 1) }; } if (!sequence_length) { throw runtime_error{"FASTA file contains empty sequence:" + string(header) }; } /*trim trailing whitespace from the sequence label */ std::string label(header); label.erase(label.find_last_not_of(" \n\r\t")+1); msa.append(sequence, label); free(sequence); free(header); } if (pll_errno != PLL_ERROR_FILE_EOF) libpll_check_error("Error parsing FASTA file: " + stream.fname() + "\n"); pll_fasta_close(file); libpll_reset_error(); return stream; } PhylipStream& operator>>(PhylipStream& stream, MSA& msa) { pll_phylip_t * fd = pll_phylip_open(stream.fname().c_str(), pll_map_phylip); if (!fd) throw runtime_error(pll_errmsg); pll_msa_t * pll_msa = stream.interleaved() ? pll_phylip_parse_interleaved(fd) : pll_phylip_parse_sequential(fd); pll_phylip_close(fd); if (pll_msa) { msa = MSA(pll_msa); pll_msa_destroy(pll_msa); } else libpll_check_error("Unable to parse PHYLIP file: " + stream.fname() + "\n"); return stream; } PhylipStream& operator<<(PhylipStream& stream, const MSA& msa) { auto retval = pllmod_msa_save_phylip(msa.pll_msa(), stream.fname().c_str()); if (!retval) throw runtime_error{pll_errmsg}; return stream; } PhylipStream& operator<<(PhylipStream& stream, const PartitionedMSAView& msa) { ofstream fs(stream.fname()); auto taxa = msa.taxon_count(); auto sites = msa.total_sites(); fs << taxa << " " << sites << endl; for (size_t i = 0; i < taxa; ++i) { fs << msa.taxon_name(i) << " "; for (size_t p = 0; p < msa.part_count(); ++p) { fs << msa.part_sequence(i, p, true); } fs << endl; } return stream; } PhylipStream& operator<<(PhylipStream& stream, const PartitionedMSA& msa) { PartitionedMSAView msa_view(msa); return stream; } PhylipStream& operator<<(PhylipStream& stream, const BootstrapMSA& bs_msa) { ofstream fs(stream.fname()); const auto& msa = std::get<0>(bs_msa); const auto& bsrep = std::get<1>(bs_msa); auto taxa = msa.taxon_count(); auto sites = msa.total_sites(); fs << taxa << " " << sites << endl; for (size_t i = 0; i < taxa; ++i) { fs << msa.taxon_names().at(i) << " "; for (size_t p = 0; p < msa.part_count(); ++p) { const auto& w = bsrep.site_weights.at(p); const auto& m = msa.part_info(p).msa(); const auto& seq = m.at(i); assert(w.size() == seq.size()); size_t wsum = 0; for (size_t j = 0; j < seq.length(); ++j) { wsum += w[j]; for (size_t k = 0; k < w[j]; ++k) fs << seq[j]; } assert(wsum == m.num_sites()); } fs << endl; } return stream; } CATGStream& operator>>(CATGStream& stream, MSA& msa) { ifstream fs; fs.open(stream.fname()); /* read alignment dimensions */ size_t taxa_count, site_count; try { fs >> taxa_count >> site_count; } catch(exception& e) { LOG_DEBUG << e.what() << endl; taxa_count = site_count = 0; } if (!taxa_count || !site_count) throw runtime_error("Invalid alignment dimensions!"); LOG_DEBUG << "CATG: taxa: " << taxa_count << ", sites: " << site_count << endl; string dummy(site_count, '*'); /* read taxa names */ try { string taxon_name; for (size_t i = 0; i < taxa_count; ++i) { fs >> taxon_name; msa.append(dummy, taxon_name); LOG_DEBUG << "CATG: taxon " << i << ": " << taxon_name << endl; } } catch (exception& e) { LOG_DEBUG << e.what() << endl; } if (msa.size() != taxa_count) throw runtime_error("Wrong number of taxon labels!"); /* this is mapping for DNA: CATG -> ACGT, for other datatypes we assume 1:1 mapping */ std::vector<size_t> state_map({1, 0, 3, 2}); string cons_str, prob_str; /* read alignment, remember that the matrix is transposed! */ for (size_t i = 0; i < msa.num_sites(); ++i) { /* read consensus sequences */ fs >> cons_str; LOG_DEBUG << "CATG: site " << i << " consesus seq: " << cons_str << endl; if (cons_str.length() != msa.size()) throw runtime_error("Wrong length of consensus sequence for site " + to_string(i+1) + "!"); std::vector<double> probs; for (size_t j = 0; j < msa.size(); ++j) { msa[j][i] = cons_str[j]; fs >> prob_str; if (msa.states() == 0) { auto states = std::count_if(prob_str.cbegin(), prob_str.cend(), [](char c) -> bool { return c == ','; }) + 1; msa.states(states); /* see above: for datatypes other than DNA we assume 1:1 mapping */ if (states != 4) state_map.clear(); LOG_DEBUG << "CATG: number of states: " << states << endl; } auto site_probs = msa.probs(j, i); istringstream ss(prob_str); size_t k = 0; for (string token; getline(ss, token, ','); ++k) { if (state_map.empty()) site_probs[k] = stod(token); else site_probs[state_map[k]] = stod(token); } if (k != msa.states()) throw runtime_error("Wrong number of state probabilities for site " + to_string(i+1) + "!"); } } #ifdef CATG_DEBUG { PhylipStream ps("catgout.phy"); ps << msa; } #endif return stream; } MSA msa_load_from_file(const std::string &filename, const FileFormat format) { MSA msa; typedef pair<FileFormat, string> FormatNamePair; static vector<FormatNamePair> msa_formats = { {FileFormat::iphylip, "IPHYLIP"}, {FileFormat::phylip, "PHYLIP"}, {FileFormat::fasta, "FASTA"}, {FileFormat::catg, "CATG"}, {FileFormat::vcf, "VCF"}, {FileFormat::binary, "RAxML-binary"} }; auto fmt_begin = msa_formats.cbegin(); auto fmt_end = msa_formats.cend(); if (!sysutil_file_exists(filename)) throw runtime_error("File not found: " + filename); if (format != FileFormat::autodetect) { fmt_begin = std::find_if(msa_formats.begin(), msa_formats.end(), [format](const FormatNamePair& p) { return p.first == format; }); assert(fmt_begin != msa_formats.cend()); fmt_end = fmt_begin + 1; } for (; fmt_begin != fmt_end; fmt_begin++) { try { switch (fmt_begin->first) { case FileFormat::fasta: { FastaStream s(filename); s >> msa; return msa; break; } case FileFormat::iphylip: { PhylipStream s(filename, true); s >> msa; return msa; break; } case FileFormat::phylip: { PhylipStream s(filename, false); s >> msa; return msa; break; } case FileFormat::catg: { CATGStream s(filename); s >> msa; return msa; break; } default: throw runtime_error("Unsupported MSA file format!"); } } catch(exception &e) { libpll_reset_error(); if (format == FileFormat::autodetect) LOG_DEBUG << "Failed to load as " << fmt_begin->second << ": " << e.what() << endl; else throw runtime_error("Error loading MSA: " + string(e.what())); } } throw runtime_error("Error loading MSA: cannot parse any format supported by RAxML-NG!\n" "Please re-run with --msa-format <FORMAT> and/or --log debug to get more information."); } <|endoftext|>
<commit_before>#include <coffee/core/plat/environment/osx/sysinfo.h> #include <sys/types.h> #include <sys/sysctl.h> namespace Coffee{ namespace Environment{ namespace Mac{ /* * OS X has a sexy API for retrieving hardware information. Big thumbs up! */ static CString _GetSysctlString(const cstring mod_string) { CString target; size_t len = 0; sysctlbyname(mod_string, nullptr, &len, nullptr, 0); if(len > 0) { target.resize(len+1); sysctlbyname(mod_string, &target[0], &len, nullptr, 0); target.resize(Mem::Search::ChrFind(&target[0], '\0') - &target[0]); } return target; } CString MacSysInfo::GetSystemVersion() { FILE* out = popen("sw_vers -productVersion","r"); if(out) { char buf[16]; char* ptr = fgets(buf, sizeof(buf),out); pclose(out); CString output = ptr; output.resize(Mem::Search::ChrFind((cstring)ptr,'\n')-ptr); return output; }else return "0.0"; } HWDeviceInfo MacSysInfo::DeviceName() { static const cstring mod_string = "hw.model"; static const cstring typ_string = "kern.ostype"; static const cstring rel_string = "kern.osrelease"; CString target = _GetSysctlString(mod_string); CString kern = _GetSysctlString(typ_string);; CString osrel = _GetSysctlString(rel_string);; return HWDeviceInfo("Apple", target, kern + " " + osrel); } HWDeviceInfo MacSysInfo::Processor() { static const cstring ven_string = "machdep.cpu.vendor"; static const cstring brd_string = "machdep.cpu.brand_string"; static const cstring mcc_string = "machdep.cpu.microcode_version"; CString vendor = _GetSysctlString(ven_string); CString brand = _GetSysctlString(brd_string); CString microcode = _GetSysctlString(mcc_string); return HWDeviceInfo(vendor, brand, microcode); } bigscalar MacSysInfo::ProcessorFrequency() { // static const cstring frq_string = "machdep.tsc.frequency"; static const cstring frq_string = "hw.cpufrequency"; CString freq_s = _GetSysctlString(frq_string); return Mem::Convert::strtoscalar(freq_s.data()) / (1024. * 1024. * 1024.); } CoreCnt MacSysInfo::CpuCount() { static const cstring cpu_string = "hw.packages"; CString c = _GetSysctlString(cpu_string); return Mem::Convert::strtouint(c.data()); } CoreCnt MacSysInfo::CoreCount() { static const cstring cre_string = "machdep.cpu.core_count"; CString c = _GetSysctlString(cre_string); return Mem::Convert::strtouint(c.data()); } MemUnit MacSysInfo::MemTotal() { static const cstring mtl_string = "hw.memsize"; CString c = _GetSysctlString(mtl_string); return Mem::Convert::strtouint(c.data()); } MemUnit MacSysInfo::MemAvailable() { return MemTotal(); } bool MacSysInfo::HasFPU() { static const cstring fpu_string = "hw.optional.floatingpoint"; CString fpu_s = _GetSysctlString(fpu_string); return fpu_s == "1"; } bool MacSysInfo::HasHyperThreading() { static const cstring thd_string = "machdep.cpu.thread_count"; CString c = _GetSysctlString(cre_string); CoreCnt thr_count = Mem::Convert::strtouint(c.data()); return thr_count == CoreCount(); } } } } <commit_msg> - Fix string reference<commit_after>#include <coffee/core/plat/environment/osx/sysinfo.h> #include <sys/types.h> #include <sys/sysctl.h> namespace Coffee{ namespace Environment{ namespace Mac{ /* * OS X has a sexy API for retrieving hardware information. Big thumbs up! */ static CString _GetSysctlString(const cstring mod_string) { CString target; size_t len = 0; sysctlbyname(mod_string, nullptr, &len, nullptr, 0); if(len > 0) { target.resize(len+1); sysctlbyname(mod_string, &target[0], &len, nullptr, 0); target.resize(Mem::Search::ChrFind(&target[0], '\0') - &target[0]); } return target; } CString MacSysInfo::GetSystemVersion() { FILE* out = popen("sw_vers -productVersion","r"); if(out) { char buf[16]; char* ptr = fgets(buf, sizeof(buf),out); pclose(out); CString output = ptr; output.resize(Mem::Search::ChrFind((cstring)ptr,'\n')-ptr); return output; }else return "0.0"; } HWDeviceInfo MacSysInfo::DeviceName() { static const cstring mod_string = "hw.model"; static const cstring typ_string = "kern.ostype"; static const cstring rel_string = "kern.osrelease"; CString target = _GetSysctlString(mod_string); CString kern = _GetSysctlString(typ_string);; CString osrel = _GetSysctlString(rel_string);; return HWDeviceInfo("Apple", target, kern + " " + osrel); } HWDeviceInfo MacSysInfo::Processor() { static const cstring ven_string = "machdep.cpu.vendor"; static const cstring brd_string = "machdep.cpu.brand_string"; static const cstring mcc_string = "machdep.cpu.microcode_version"; CString vendor = _GetSysctlString(ven_string); CString brand = _GetSysctlString(brd_string); CString microcode = _GetSysctlString(mcc_string); return HWDeviceInfo(vendor, brand, microcode); } bigscalar MacSysInfo::ProcessorFrequency() { // static const cstring frq_string = "machdep.tsc.frequency"; static const cstring frq_string = "hw.cpufrequency"; CString freq_s = _GetSysctlString(frq_string); return Mem::Convert::strtoscalar(freq_s.data()) / (1024. * 1024. * 1024.); } CoreCnt MacSysInfo::CpuCount() { static const cstring cpu_string = "hw.packages"; CString c = _GetSysctlString(cpu_string); return Mem::Convert::strtouint(c.data()); } CoreCnt MacSysInfo::CoreCount() { static const cstring cre_string = "machdep.cpu.core_count"; CString c = _GetSysctlString(cre_string); return Mem::Convert::strtouint(c.data()); } MemUnit MacSysInfo::MemTotal() { static const cstring mtl_string = "hw.memsize"; CString c = _GetSysctlString(mtl_string); return Mem::Convert::strtouint(c.data()); } MemUnit MacSysInfo::MemAvailable() { return MemTotal(); } bool MacSysInfo::HasFPU() { static const cstring fpu_string = "hw.optional.floatingpoint"; CString fpu_s = _GetSysctlString(fpu_string); return fpu_s == "1"; } bool MacSysInfo::HasHyperThreading() { static const cstring thd_string = "machdep.cpu.thread_count"; CString c = _GetSysctlString(thd_string); CoreCnt thr_count = Mem::Convert::strtouint(c.data()); return thr_count == CoreCount(); } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, 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. */ #include "libtorrent/config.hpp" #if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (*RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack), 0); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <commit_msg>fix msvc-8 debug build<commit_after>/* Copyright (c) 2007, 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. */ #include "libtorrent/config.hpp" #if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } // visual studio 9 and up appears to support this #elif defined WIN32 && _MSC_VER >= 1500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (*RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack), 0); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016, The Bifrost Authors. All rights reserved. * Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost Authors 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 ``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. */ #pragma once #include <bifrost/common.h> #include <stdexcept> class BFexception : public std::runtime_error { BFstatus _status; public: BFexception(BFstatus stat, const char* msg="") : std::runtime_error(std::string(bfGetStatusString(stat))+ ": "+msg), _status(stat) {} BFstatus status() const { return _status; } }; namespace { inline bool should_report_error(BFstatus err) { return (err != BF_STATUS_END_OF_DATA && err != BF_STATUS_WOULD_BLOCK); } } #include <iostream> using std::cout; using std::endl; #if defined(BF_DEBUG) && BF_DEBUG #define BF_REPORT_ERROR(err) do { \ if( bfGetDebugEnabled() && \ should_report_error(err) ) { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " error " << err << ": " \ << bfGetStatusString(err) << std::endl; \ } \ } while(0) #define BF_DEBUG_PRINT(x) do { \ if( bfGetDebugEnabled() ) { \ std::cout << __FILE__ << ":" << __LINE__ \ << " " #x << " = " << (x) << std::endl; \ } \ } while(0) #define BF_REPORT_PREDFAIL(pred, err) do { \ if( bfGetDebugEnabled() && \ should_report_error(err) ) { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " Condition failed: " \ << #pred << std::endl; \ } \ } while(0) #else #define BF_REPORT_ERROR(err) #define BF_DEBUG_PRINT(x) #define BF_REPORT_PREDFAIL(pred, err) #endif // BF_DEBUG #define BF_REPORT_INTERNAL_ERROR(msg) do { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " internal error: " \ << msg << std::endl; \ } while(0) #define BF_FAIL(msg, err) do { \ BF_REPORT_PREDFAIL(msg, err); \ BF_REPORT_ERROR(err); \ return (err); \ } while(0) #define BF_FAIL_EXCEPTION(msg, err) do { \ BF_REPORT_PREDFAIL(msg, err); \ BF_REPORT_ERROR(err); \ throw BFexception(err); \ } while(0) #define BF_ASSERT(pred, err) do { \ if( !(pred) ) { \ BF_REPORT_PREDFAIL(pred, err); \ BF_REPORT_ERROR(err); \ return (err); \ } \ } while(0) #define BF_TRY_ELSE(code, onfail) do { \ try { code; } \ catch( BFexception const& err ) { \ onfail; \ BF_REPORT_ERROR(err.status()); \ return err.status(); \ } \ catch(std::bad_alloc const& err) { \ onfail; \ BF_REPORT_ERROR(BF_STATUS_MEM_ALLOC_FAILED); \ return BF_STATUS_MEM_ALLOC_FAILED; \ } \ catch(std::exception const& err) { \ onfail; \ BF_REPORT_INTERNAL_ERROR(err.what()); \ return BF_STATUS_INTERNAL_ERROR; \ } \ catch(...) { \ onfail; \ BF_REPORT_INTERNAL_ERROR("FOREIGN EXCEPTION"); \ return BF_STATUS_INTERNAL_ERROR; \ } \ } while(0) #define BF_NO_OP (void)0 #define BF_TRY(code) BF_TRY_ELSE(code, BF_NO_OP) #define BF_TRY_RETURN(code) BF_TRY(code); return BF_STATUS_SUCCESS #define BF_TRY_RETURN_ELSE(code, onfail) BF_TRY_ELSE(code, onfail); return BF_STATUS_SUCCESS #define BF_ASSERT_EXCEPTION(pred, err) \ do { \ if( !(pred) ) { \ BF_REPORT_PREDFAIL(pred, err); \ BF_REPORT_ERROR(err); \ throw BFexception(err); \ } \ } while(0) #define BF_CHECK(call) do { \ BFstatus status = call; \ if( status != BF_STATUS_SUCCESS ) { \ BF_REPORT_ERROR(status); \ return status; \ } \ } while(0) #define BF_CHECK_EXCEPTION(call) do { \ BFstatus status = call; \ if( status != BF_STATUS_SUCCESS ) { \ BF_REPORT_ERROR(status); \ throw BFexception(status); \ } \ } while(0) class NoDebugScope { bool _enabled_before; public: NoDebugScope(NoDebugScope const&) = delete; NoDebugScope& operator=(NoDebugScope const&) = delete; NoDebugScope() : _enabled_before(bfGetDebugEnabled()) { bfSetDebugEnabled(false); } ~NoDebugScope() { bfSetDebugEnabled(_enabled_before); } }; // Disables debug-printing in the current scope #define BF_DISABLE_DEBUG() NoDebugScope _bf_no_debug_scope <commit_msg>Missing include according to clang.<commit_after>/* * Copyright (c) 2016, The Bifrost Authors. All rights reserved. * Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost Authors 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 ``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. */ #pragma once #include <bifrost/common.h> #include <string> #include <stdexcept> class BFexception : public std::runtime_error { BFstatus _status; public: BFexception(BFstatus stat, const char* msg="") : std::runtime_error(std::string(bfGetStatusString(stat))+ ": "+msg), _status(stat) {} BFstatus status() const { return _status; } }; namespace { inline bool should_report_error(BFstatus err) { return (err != BF_STATUS_END_OF_DATA && err != BF_STATUS_WOULD_BLOCK); } } #include <iostream> using std::cout; using std::endl; #if defined(BF_DEBUG) && BF_DEBUG #define BF_REPORT_ERROR(err) do { \ if( bfGetDebugEnabled() && \ should_report_error(err) ) { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " error " << err << ": " \ << bfGetStatusString(err) << std::endl; \ } \ } while(0) #define BF_DEBUG_PRINT(x) do { \ if( bfGetDebugEnabled() ) { \ std::cout << __FILE__ << ":" << __LINE__ \ << " " #x << " = " << (x) << std::endl; \ } \ } while(0) #define BF_REPORT_PREDFAIL(pred, err) do { \ if( bfGetDebugEnabled() && \ should_report_error(err) ) { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " Condition failed: " \ << #pred << std::endl; \ } \ } while(0) #else #define BF_REPORT_ERROR(err) #define BF_DEBUG_PRINT(x) #define BF_REPORT_PREDFAIL(pred, err) #endif // BF_DEBUG #define BF_REPORT_INTERNAL_ERROR(msg) do { \ std::cerr << __FILE__ << ":" << __LINE__ \ << " internal error: " \ << msg << std::endl; \ } while(0) #define BF_FAIL(msg, err) do { \ BF_REPORT_PREDFAIL(msg, err); \ BF_REPORT_ERROR(err); \ return (err); \ } while(0) #define BF_FAIL_EXCEPTION(msg, err) do { \ BF_REPORT_PREDFAIL(msg, err); \ BF_REPORT_ERROR(err); \ throw BFexception(err); \ } while(0) #define BF_ASSERT(pred, err) do { \ if( !(pred) ) { \ BF_REPORT_PREDFAIL(pred, err); \ BF_REPORT_ERROR(err); \ return (err); \ } \ } while(0) #define BF_TRY_ELSE(code, onfail) do { \ try { code; } \ catch( BFexception const& err ) { \ onfail; \ BF_REPORT_ERROR(err.status()); \ return err.status(); \ } \ catch(std::bad_alloc const& err) { \ onfail; \ BF_REPORT_ERROR(BF_STATUS_MEM_ALLOC_FAILED); \ return BF_STATUS_MEM_ALLOC_FAILED; \ } \ catch(std::exception const& err) { \ onfail; \ BF_REPORT_INTERNAL_ERROR(err.what()); \ return BF_STATUS_INTERNAL_ERROR; \ } \ catch(...) { \ onfail; \ BF_REPORT_INTERNAL_ERROR("FOREIGN EXCEPTION"); \ return BF_STATUS_INTERNAL_ERROR; \ } \ } while(0) #define BF_NO_OP (void)0 #define BF_TRY(code) BF_TRY_ELSE(code, BF_NO_OP) #define BF_TRY_RETURN(code) BF_TRY(code); return BF_STATUS_SUCCESS #define BF_TRY_RETURN_ELSE(code, onfail) BF_TRY_ELSE(code, onfail); return BF_STATUS_SUCCESS #define BF_ASSERT_EXCEPTION(pred, err) \ do { \ if( !(pred) ) { \ BF_REPORT_PREDFAIL(pred, err); \ BF_REPORT_ERROR(err); \ throw BFexception(err); \ } \ } while(0) #define BF_CHECK(call) do { \ BFstatus status = call; \ if( status != BF_STATUS_SUCCESS ) { \ BF_REPORT_ERROR(status); \ return status; \ } \ } while(0) #define BF_CHECK_EXCEPTION(call) do { \ BFstatus status = call; \ if( status != BF_STATUS_SUCCESS ) { \ BF_REPORT_ERROR(status); \ throw BFexception(status); \ } \ } while(0) class NoDebugScope { bool _enabled_before; public: NoDebugScope(NoDebugScope const&) = delete; NoDebugScope& operator=(NoDebugScope const&) = delete; NoDebugScope() : _enabled_before(bfGetDebugEnabled()) { bfSetDebugEnabled(false); } ~NoDebugScope() { bfSetDebugEnabled(_enabled_before); } }; // Disables debug-printing in the current scope #define BF_DISABLE_DEBUG() NoDebugScope _bf_no_debug_scope <|endoftext|>
<commit_before>#include "joedb/io/merge.h" #include "joedb/interpreter/Database.h" ///////////////////////////////////////////////////////////////////////////// void joedb::merge(Database &merged, const Database &db) ///////////////////////////////////////////////////////////////////////////// { std::map<Table_Id, Record_Id> offset; // // First loop over tables to fill the offset map // for (auto table: merged.get_tables()) { const Table_Id table_id = table.first; const Record_Id last_record_id = merged.get_last_record_id(table_id); offset[table_id] = last_record_id; } // // Second loop to copy data, with added offset // for (auto table: merged.get_tables()) { const Table_Id table_id = table.first; const Record_Id last_record_id = db.get_last_record_id(table_id); const Compact_Freedom_Keeper &freedom_keeper = db.get_freedom(table_id); // TODO: use vector insertions for better performance for (Record_Id record_id = 1; record_id <= last_record_id; record_id++) if (freedom_keeper.is_used(record_id)) { const Record_Id merged_record_id = record_id + offset[table_id]; merged.insert_into(table_id, merged_record_id); for (const auto &field: db.get_fields(table_id)) { const Field_Id field_id = field.first; const Type &type = db.get_field_type(table_id, field_id); switch (type.get_type_id()) { case Type::Type_Id::null: break; case Type::Type_Id::reference: { Record_Id referenced = db.get_reference(table_id, record_id, field_id); if (referenced > 0) referenced += offset[type.get_table_id()]; merged.update_reference ( table_id, merged_record_id, field_id, referenced ); } break; #define TYPE_MACRO(type, return_type, type_id, R, W)\ case Type::Type_Id::type_id:\ {\ merged.update_##type_id\ (\ table_id,\ merged_record_id,\ field_id,\ db.get_##type_id(table_id, record_id, field_id)\ );\ }\ break; #define TYPE_MACRO_NO_REFERENCE #include "joedb/TYPE_MACRO.h" } } } } } <commit_msg>fix bug<commit_after>#include "joedb/io/merge.h" #include "joedb/interpreter/Database.h" ///////////////////////////////////////////////////////////////////////////// void joedb::merge(Database &merged, const Database &db) ///////////////////////////////////////////////////////////////////////////// { std::map<Table_Id, Record_Id> offset; // // First loop over tables to fill the offset map // for (auto table: merged.get_tables()) { const Table_Id table_id = table.first; const Record_Id last_record_id = merged.get_last_record_id(table_id); offset[table_id] = last_record_id; } // // Second loop to copy data, with added offset // for (auto table: merged.get_tables()) { const Table_Id table_id = table.first; const Record_Id last_record_id = db.get_last_record_id(table_id); const Compact_Freedom_Keeper &freedom_keeper = db.get_freedom(table_id); // TODO: use vector insertions for better performance for (Record_Id record_id = 1; record_id <= last_record_id; record_id++) if (freedom_keeper.is_used(record_id + 1)) { const Record_Id merged_record_id = record_id + offset[table_id]; merged.insert_into(table_id, merged_record_id); for (const auto &field: db.get_fields(table_id)) { const Field_Id field_id = field.first; const Type &type = db.get_field_type(table_id, field_id); switch (type.get_type_id()) { case Type::Type_Id::null: break; case Type::Type_Id::reference: { Record_Id referenced = db.get_reference(table_id, record_id, field_id); if (referenced > 0) referenced += offset[type.get_table_id()]; merged.update_reference ( table_id, merged_record_id, field_id, referenced ); } break; #define TYPE_MACRO(type, return_type, type_id, R, W)\ case Type::Type_Id::type_id:\ {\ merged.update_##type_id\ (\ table_id,\ merged_record_id,\ field_id,\ db.get_##type_id(table_id, record_id, field_id)\ );\ }\ break; #define TYPE_MACRO_NO_REFERENCE #include "joedb/TYPE_MACRO.h" } } } } } <|endoftext|>
<commit_before>/* nobleNote, a note taking application * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>, Fabian Deuchler <Taiko000@gmail.com> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'. */ #include "backup.h" #include <QDirIterator> #include <QMessageBox> #include <QSettings> #include <QtConcurrentMap> #include <QAbstractItemModel> Backup::Backup(QWidget *parent): QDialog(parent){ setupUi(this); setAttribute(Qt::WA_DeleteOnClose); splitter = new QSplitter(groupBox); gridLayout_2->addWidget(splitter); treeWidget = new QTreeWidget(splitter); treeWidget->setAlternatingRowColors(true); treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); treeWidget->setSortingEnabled(true); treeWidget->sortByColumn(0,Qt::AscendingOrder); treeWidget->setHeaderLabel(tr("Backups of deleted notes")); treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); treeWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); // TODO flickcharm here frame = new QFrame(splitter); gridLayout3 = new QGridLayout(frame); label = new QLabel(frame); label->setText(tr("Preview of the selected backup")); gridLayout3->addWidget(label, 0, 0, 1, 1); textEdit = new QTextEdit(frame); textEdit->setReadOnly(true); gridLayout3->addWidget(textEdit, 1, 0, 1, 1); getNotes(); //Searches for notes and backups. For the backups with no notes it will create the trees children. connect(treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(showPreview())); connect(deleteButton, SIGNAL(clicked(bool)), this, SLOT(deleteBackup())); connect(restoreButton, SIGNAL(clicked(bool)), this, SLOT(restoreBackup())); } void Backup::getNoteUuidList() { QFutureIterator<QString> it(future1->future()); while(it.hasNext()) noteUuidList << it.next(); } void Backup::getNotes() { noteFiles.clear(); //remove old files //get note files QDirIterator itFiles(QSettings().value("root_path").toString(), QDirIterator::Subdirectories); while(itFiles.hasNext()){ QString filePath = itFiles.next(); if(itFiles.fileInfo().isFile()) noteFiles << filePath; } progressReceiver1 = new ProgressReceiver(this); progressDialog1 = new QProgressDialog(this); progressDialog1->setLabelText(QString(tr("Indexing notes..."))); getUuid.p = progressReceiver1; future1 = new QFutureWatcher<QString>(this); future1->setFuture(QtConcurrent::mapped(noteFiles, getUuid)); QObject::connect(progressReceiver1,SIGNAL(valueChanged(int)),progressDialog1, SLOT(setValue(int))); QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList())); QObject::connect(future1, SIGNAL(finished()), this, SLOT(setupBackups())); QObject::connect(future1, SIGNAL(finished()), progressDialog1, SLOT(reset())); QObject::connect(progressDialog1, SIGNAL(canceled()), future1, SLOT(cancel())); progressDialog1->show(); } void Backup::setupBackups() { backupFiles.clear(); //remove old files //get backup uuids QDir backupDir(QSettings().value("backup_dir_path").toString()); backupFiles = backupDir.entryInfoList(QDir::Files, QDir::Name); foreach(QString uuid, noteUuidList) { if(backupFiles.contains(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid.mid(1,36)))) { backupFiles.removeOne(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid.mid(1,36))); backupFiles.removeOne(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid)); } } if(backupFiles.isEmpty()) { textEdit->clear(); return; } progressReceiver2 = new ProgressReceiver(this); progressDialog2 = new QProgressDialog(this); progressDialog2->setLabelText(QString(tr("Indexing backup data..."))); setupBackup.p = progressReceiver2; backupDataHash = new QHash<QString,QStringList>; setupBackup.hash = backupDataHash; future2 = new QFutureWatcher<void>(this); future2->setFuture(QtConcurrent::map(backupFiles, setupBackup)); QObject::connect(progressReceiver2,SIGNAL(valueChanged(int)),progressDialog2, SLOT(setValue(int))); QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupChildren())); QObject::connect(future2, SIGNAL(finished()), progressDialog2, SLOT(reset())); QObject::connect(progressDialog2, SIGNAL(canceled()), future2, SLOT(cancel())); progressDialog2->show(); } void Backup::setupChildren() { QHash<QString,QStringList> hash = *backupDataHash; foreach(QString key, hash.keys()) { QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget); item->setText(0,hash[key].first()); //title item->setData(0,Qt::UserRole,hash[key]); //title, path and content } } void Backup::showPreview() { if(treeWidget->currentItem() == NULL) //Prevents program crush { textEdit->clear(); return; } if(!treeWidget->currentItem()->isSelected()) { if(treeWidget->selectedItems().count() != 1) textEdit->clear(); else textEdit->setText(treeWidget->selectedItems().first()->data(0,Qt::UserRole).toStringList().last()); } else textEdit->setText(treeWidget->currentItem()->data(0,Qt::UserRole).toStringList().last()); } void Backup::restoreBackup() { if(treeWidget->selectedItems().isEmpty()) return; foreach(QTreeWidgetItem *item, treeWidget->selectedItems()) { QStringList dataList = item->data(0,Qt::UserRole).toStringList(); QString title = dataList.takeFirst(); if(!QFile(dataList.first()).exists()) return; else { if(!QDir(QSettings().value("root_path").toString()+"/restored notes").exists()) QDir().mkpath(QSettings().value("root_path").toString()+"/restored notes"); QFile(dataList.first()).copy(QSettings().value("root_path").toString()+"/restored notes/"+title); } delete item; } } void Backup::deleteBackup() { if(treeWidget->selectedItems().isEmpty()) return; QStringList files; QList<QTreeWidgetItem*> itemList = treeWidget->selectedItems(); foreach(QTreeWidgetItem *item, itemList) { QStringList dataList = item->data(0,Qt::UserRole).toStringList(); dataList.takeFirst(); //removing title from the list files << dataList.first(); } QString backupsToBeDeleted; foreach(QString str, files) backupsToBeDeleted += (str+"\n"); if(QMessageBox::warning(this,tr("Deleting backups and file entries"), tr("Do you really want to delete the backups and entries for the " "following files?\n\n%1\nYou won't be able to restore them!").arg( backupsToBeDeleted),QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes) return; foreach(QString file, files) { if(QFile(file).exists()) QFile(file).remove(); QString uuid = file; uuid.remove(QSettings().value("backup_dir_path").toString() + "/"); QSettings().remove("Notes/" + QUuid(uuid).toString() + "_size"); QSettings().remove("Notes/" + QUuid(uuid).toString() + "_cursor_position"); } foreach(QTreeWidgetItem *item, itemList) delete item; } <commit_msg>minor fixes<commit_after>/* nobleNote, a note taking application * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>, Fabian Deuchler <Taiko000@gmail.com> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'. */ #include "backup.h" #include <QDirIterator> #include <QMessageBox> #include <QSettings> #include <QtConcurrentMap> #include <QAbstractItemModel> Backup::Backup(QWidget *parent): QDialog(parent){ setupUi(this); setAttribute(Qt::WA_DeleteOnClose); splitter = new QSplitter(groupBox); gridLayout_2->addWidget(splitter); treeWidget = new QTreeWidget(splitter); treeWidget->setAlternatingRowColors(true); treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); treeWidget->setSortingEnabled(true); treeWidget->sortByColumn(0,Qt::AscendingOrder); treeWidget->setHeaderLabel(tr("Deleted notes")); treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); treeWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); // TODO flickcharm here frame = new QFrame(splitter); gridLayout3 = new QGridLayout(frame); label = new QLabel(frame); label->setText(tr("Preview of the selected note")); gridLayout3->addWidget(label, 0, 0, 1, 1); textEdit = new QTextEdit(frame); textEdit->setReadOnly(true); gridLayout3->addWidget(textEdit, 1, 0, 1, 1); getNotes(); //Searches for notes and backups. For the backups with no notes it will create the trees children. connect(treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(showPreview())); connect(deleteButton, SIGNAL(clicked(bool)), this, SLOT(deleteBackup())); connect(restoreButton, SIGNAL(clicked(bool)), this, SLOT(restoreBackup())); } void Backup::getNoteUuidList() { QFutureIterator<QString> it(future1->future()); while(it.hasNext()) noteUuidList << it.next(); } void Backup::getNotes() { noteFiles.clear(); //remove old files //get note files QDirIterator itFiles(QSettings().value("root_path").toString(), QDirIterator::Subdirectories); while(itFiles.hasNext()){ QString filePath = itFiles.next(); if(itFiles.fileInfo().isFile()) noteFiles << filePath; } progressReceiver1 = new ProgressReceiver(this); progressDialog1 = new QProgressDialog(this); progressDialog1->setLabelText(QString(tr("Indexing notes..."))); getUuid.p = progressReceiver1; future1 = new QFutureWatcher<QString>(this); future1->setFuture(QtConcurrent::mapped(noteFiles, getUuid)); QObject::connect(progressReceiver1,SIGNAL(valueChanged(int)),progressDialog1, SLOT(setValue(int))); QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList())); QObject::connect(future1, SIGNAL(finished()), this, SLOT(setupBackups())); QObject::connect(future1, SIGNAL(finished()), progressDialog1, SLOT(reset())); QObject::connect(progressDialog1, SIGNAL(canceled()), future1, SLOT(cancel())); progressDialog1->show(); } void Backup::setupBackups() { backupFiles.clear(); //remove old files //get backup uuids QDir backupDir(QSettings().value("backup_dir_path").toString()); backupFiles = backupDir.entryInfoList(QDir::Files, QDir::Name); foreach(QString uuid, noteUuidList) { if(backupFiles.contains(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid.mid(1,36)))) { backupFiles.removeOne(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid.mid(1,36))); backupFiles.removeOne(QFileInfo(QSettings().value("backup_dir_path").toString() + "/" + uuid)); } } if(backupFiles.isEmpty()) { textEdit->clear(); return; } progressReceiver2 = new ProgressReceiver(this); progressDialog2 = new QProgressDialog(this); progressDialog2->setLabelText(QString(tr("Indexing trash..."))); setupBackup.p = progressReceiver2; backupDataHash = new QHash<QString,QStringList>; setupBackup.hash = backupDataHash; future2 = new QFutureWatcher<void>(this); future2->setFuture(QtConcurrent::map(backupFiles, setupBackup)); QObject::connect(progressReceiver2,SIGNAL(valueChanged(int)),progressDialog2, SLOT(setValue(int))); QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupChildren())); QObject::connect(future2, SIGNAL(finished()), progressDialog2, SLOT(reset())); QObject::connect(progressDialog2, SIGNAL(canceled()), future2, SLOT(cancel())); progressDialog2->show(); } void Backup::setupChildren() { QHash<QString,QStringList> hash = *backupDataHash; foreach(QString key, hash.keys()) { QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget); item->setText(0,hash[key].first()); //title item->setData(0,Qt::UserRole,hash[key]); //title, path and content } } void Backup::showPreview() { if(treeWidget->currentItem() == NULL) //Prevents program crush { textEdit->clear(); return; } if(!treeWidget->currentItem()->isSelected()) { if(treeWidget->selectedItems().count() != 1) textEdit->clear(); else textEdit->setText(treeWidget->selectedItems().first()->data(0,Qt::UserRole).toStringList().last()); } else textEdit->setText(treeWidget->currentItem()->data(0,Qt::UserRole).toStringList().last()); } void Backup::restoreBackup() { if(treeWidget->selectedItems().isEmpty()) return; foreach(QTreeWidgetItem *item, treeWidget->selectedItems()) { QStringList dataList = item->data(0,Qt::UserRole).toStringList(); QString title = dataList.takeFirst(); if(!QFile(dataList.first()).exists()) return; else { if(!QDir(QSettings().value("root_path").toString()+"/restored notes").exists()) QDir().mkpath(QSettings().value("root_path").toString()+"/restored notes"); QFile(dataList.first()).copy(QSettings().value("root_path").toString()+"/restored notes/"+title); } delete item; } } void Backup::deleteBackup() { if(treeWidget->selectedItems().isEmpty()) return; QStringList files; QList<QTreeWidgetItem*> itemList = treeWidget->selectedItems(); foreach(QTreeWidgetItem *item, itemList) { QStringList dataList = item->data(0,Qt::UserRole).toStringList(); dataList.takeFirst(); //removing title from the list files << dataList.first(); } QString backupsToBeDeleted; foreach(QString str, files) backupsToBeDeleted += (str+"\n"); if(QMessageBox::warning(this,tr("Deleting backups and file entries"), tr("Do you really want to delete the backups and entries for the " "following files?\n\n%1\nYou won't be able to restore them!").arg( backupsToBeDeleted),QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes) return; foreach(QString file, files) { if(QFile(file).exists()) QFile(file).remove(); QString uuid = file; uuid.remove(QSettings().value("backup_dir_path").toString() + "/"); QSettings().remove("Notes/" + QUuid(uuid).toString() + "_size"); QSettings().remove("Notes/" + QUuid(uuid).toString() + "_cursor_position"); } foreach(QTreeWidgetItem *item, itemList) delete item; } <|endoftext|>
<commit_before>/* * Banjax is an ATS plugin that: * enforce regex bans * store logs in a mysql db * run SVM on the log result * send a ban request to swabber in case of banning. * * Copyright (c) 2013 eQualit.ie under GNU AGPL v3.0 or later * * Vmon: June 2013 Initial version */ #include <ts/ts.h> #include <string> #include <iostream> #include <sys/stat.h> #include <stdarg.h> /* va_list, va_start, va_arg, va_end */ #include "transaction_data.h" #include "white_lister.h" #include "bot_sniffer.h" #include "denialator.h" #include "banjax.h" #include "defer.h" using namespace std; #define TSError_does_not_work_in_TSPluginInit #ifdef TSError_does_not_work_in_TSPluginInit #define TSError TSErrorAlternative #endif const string CONFIG_FILENAME = "banjax.conf"; struct BanjaxPlugin { string config_dir; TSMutex reload_mutex; std::shared_ptr<Banjax> current_state; BanjaxPlugin(string config_dir) : config_dir(move(config_dir)) , reload_mutex(TSMutexCreate()) , current_state(make_shared<Banjax>(this->config_dir)) {} void reload_config() { TSMutexLock(reload_mutex); auto on_exit = defer([&] { TSMutexUnlock(reload_mutex); }); auto swab_s = current_state->release_swabber_socket(); auto snif_s = current_state->release_botsniffer_socket(); std::shared_ptr<Banjax> new_banjax(new Banjax(config_dir, move(swab_s), move(snif_s))); // This happens atomically, so (in theory) we don't need to wrap in in mutex // in the handle_transaction_start hook. current_state = std::move(new_banjax); } }; std::shared_ptr<BanjaxPlugin> g_banjax_plugin; void TSErrorAlternative(const char* fmt, ...) { va_list arglist; va_start(arglist, fmt); fprintf(stderr, "ERROR: "); vfprintf(stderr, fmt, arglist); fprintf(stderr, "\n"); va_end(arglist); } /** Read the config file and create filters whose name is mentioned in the config file. If you make a new filter you need to add it inside this function */ void Banjax::build_filters() { BanjaxFilter* cur_filter; for (const pair<int,string>& cur_filter_name : priority_map) { FilterConfig& cur_config = filter_config_map[cur_filter_name.second]; try { if (cur_filter_name.second == REGEX_BANNER_FILTER_NAME) { regex_manager.reset(new RegexManager(cur_config, &regex_manager_ip_db, &swabber_interface)); cur_filter = regex_manager.get(); } else if (cur_filter_name.second == CHALLENGER_FILTER_NAME){ challenge_manager.reset(new ChallengeManager(banjax_config_dir, cur_config, &challenger_ip_db, &swabber_interface, &global_ip_white_list)); cur_filter = challenge_manager.get(); } else if (cur_filter_name.second == WHITE_LISTER_FILTER_NAME){ white_lister.reset(new WhiteLister(cur_config, global_ip_white_list)); cur_filter = white_lister.get(); } else if (cur_filter_name.second == BOT_SNIFFER_FILTER_NAME){ bot_sniffer.reset(new BotSniffer(cur_config, move(botsniffer_socket_reuse))); cur_filter = bot_sniffer.get(); } else if (cur_filter_name.second == DENIALATOR_FILTER_NAME){ denialator.reset(new Denialator(cur_config, &swabber_ip_db, &swabber_interface, &global_ip_white_list)); cur_filter = denialator.get(); } else { TSError(("don't know how to construct requested filter " + cur_filter_name.second).c_str()); abort_traffic_server(); } } catch (YAML::Exception& e) { TSError(("error in intializing filter " + cur_filter_name.second).c_str()); abort_traffic_server(); } //at which que the filter need to be called for(unsigned int i = BanjaxFilter::HTTP_START; i < BanjaxFilter::TOTAL_NO_OF_QUEUES; i++) { if (cur_filter->queued_tasks[i]) { TSDebug(BANJAX_PLUGIN_NAME, "active task %s %u", cur_filter->BANJAX_FILTER_NAME.c_str(), i); task_queues[i].push_back(cur_filter->queued_tasks[i]); } } all_filters_requested_part |= cur_filter->requested_info(); all_filters_response_part |= cur_filter->response_info(); } } static int handle_transaction_start(TSCont contp, TSEvent event, void *edata) { if (event != TS_EVENT_HTTP_TXN_START) { TSDebug(BANJAX_PLUGIN_NAME, "txn unexpected event" ); return TS_EVENT_NONE; } TSHttpTxn txnp = (TSHttpTxn) edata; TSDebug(BANJAX_PLUGIN_NAME, "txn start"); TSCont txn_contp; TransactionData *cd; txn_contp = TSContCreate((TSEventFunc) TransactionData::handle_transaction_change, TSMutexCreate()); /* create the data that'll be associated with the continuation */ cd = (TransactionData *) TSmalloc(sizeof(TransactionData)); cd = new(cd) TransactionData(g_banjax_plugin->current_state, txnp); TSContDataSet(txn_contp, cd); TSHttpTxnHookAdd(txnp, TS_HTTP_READ_REQUEST_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_REQUEST_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, txn_contp); TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); return TS_EVENT_NONE; } static int handle_management(TSCont contp, TSEvent event, void *edata) { (void) contp; (void) edata; TSDebug(BANJAX_PLUGIN_NAME, "reload configuration signal received"); TSReleaseAssert(event == TS_EVENT_MGMT_UPDATE); g_banjax_plugin->reload_config(); return 0; } std::unique_ptr<Socket> Banjax::release_swabber_socket() { return swabber_interface.release_socket(); } std::unique_ptr<Socket> Banjax::release_botsniffer_socket() { if (!bot_sniffer) return nullptr; return bot_sniffer->release_socket(); } /** Constructor @param banjax_config_dir path to the folder containing banjax.conf */ Banjax::Banjax(const string& banjax_config_dir, std::unique_ptr<Socket> swabber_socket, std::unique_ptr<Socket> bot_sniffer_socket) : all_filters_requested_part(0), all_filters_response_part(0), banjax_config_dir(banjax_config_dir), swabber_interface(&swabber_ip_db, move(swabber_socket)), botsniffer_socket_reuse(move(bot_sniffer_socket)) { /* create an TSTextLogObject to log blacklisted requests to */ TSReturnCode error = TSTextLogObjectCreate(BANJAX_PLUGIN_NAME, TS_LOG_MODE_ADD_TIMESTAMP, &log); if (!log || error == TS_ERROR) { TSDebug(BANJAX_PLUGIN_NAME, "error while creating log"); } read_configuration(); } void Banjax::read_configuration() { // Read the file. If there is an error, report it and exit. static const string sep = "/"; string absolute_config_file = banjax_config_dir + sep + CONFIG_FILENAME; TSDebug(BANJAX_PLUGIN_NAME, "Reading configuration from [%s]", absolute_config_file.c_str()); try { cfg = YAML::LoadFile(absolute_config_file); process_config(cfg); } catch(YAML::BadFile& e) { TSError("I/O error while reading config file [%s]: [%s]. Make sure that file exists.", absolute_config_file.c_str(), e.what()); abort_traffic_server(); } catch(YAML::ParserException& e) { TSError("parsing error while reading config file [%s]: [%s].", absolute_config_file.c_str(), e.what()); abort_traffic_server(); } TSDebug(BANJAX_PLUGIN_NAME, "Finished loading main conf"); int min_priority = 0, max_priority = 0; //setting up priorities if (priorities.size()) { //first find the max priorities try { min_priority = priorities.begin()->second.as<int>(); max_priority = priorities.begin()->second.as<int>(); } catch( YAML::RepresentationException &e ) { TSError(("bad config format " + (string)e.what()).c_str()); abort_traffic_server(); } for (const auto& p : priorities) { if (p.second.as<int>() > max_priority) max_priority = p.second.as<int>(); if (p.second.as<int>() < min_priority) min_priority = p.second.as<int>(); } } //now either replace priorities or add them up for(pair<const std::string, FilterConfig>& p : filter_config_map) { if (priorities[p.first]) { p.second.priority = priorities[p.first].as<int>(); } else { p.second.priority += max_priority + 1; } if (priority_map.count(p.second.priority)) { TSError(("Priority " + to_string(p.second.priority) + " has been doubly assigned").c_str()); abort_traffic_server(); } priority_map[p.second.priority] = p.first; } //(re)set swabber configuration if there is no swabber node //in the configuration we reset the configuration swabber_interface.load_config(swabber_conf); //now we can make the filters build_filters(); } //Recursively read the entire config structure //including inside the included files void Banjax::process_config(const YAML::Node& cfg) { static const string sep = "/"; int current_sequential_priority = 0; auto is_filter = [](const std::string& s) { return std::find( all_filters_names.begin() , all_filters_names.end(), s) != all_filters_names.end(); }; for (YAML::const_iterator it = cfg.begin(); it != cfg.end(); ++it) { try { std::string node_name = it->first.as<std::string>(); if (is_filter(node_name)) { // If it's a filter see if it is already in the list if (filter_config_map.find(node_name) == filter_config_map.end()) { filter_config_map[node_name].priority = current_sequential_priority; current_sequential_priority++; } filter_config_map[node_name].config_node_list.push_back(it); } else if (node_name == "swabber") { //we simply send swabber configuration to swabber //if it doesn't exists it fails to default swabber_conf.config_node_list.push_back(it); } else if (node_name == "priority") { // Store it as priority config. for now we fire error if priority is // double defined if (priorities.size()) { TSError("double definition of priorities. only one priority list is allowed."); abort_traffic_server(); } priorities = Clone(it->second); } else if (node_name == "include") { for(const auto& sub : it->second) { string inc_loc = banjax_config_dir + sep + sub.as<std::string>(); TSDebug(BANJAX_PLUGIN_NAME, "Reading configuration from [%s]", inc_loc.c_str()); try { process_config(YAML::LoadFile(inc_loc)); } catch(YAML::BadFile& e) { TSError("I/O error while reading config file [%s]: [%s]. Make sure that file exists.", inc_loc.c_str(), e.what()); abort_traffic_server(); } catch(YAML::ParserException& e) { TSError("Parsing error while reading config file [%s]: [%s].", inc_loc.c_str(), e.what()); abort_traffic_server(); } } } else { //unknown node TSError(("unknown config node " + node_name).c_str()); abort_traffic_server(); } } catch( YAML::RepresentationException &e ) { TSError(("bad config format " + (string)e.what()).c_str()); abort_traffic_server(); } } } static void destroy_g_banjax_plugin() { g_banjax_plugin.reset(); } void TSPluginInit(int argc, const char *argv[]) { TSPluginRegistrationInfo info; info.plugin_name = (char*) BANJAX_PLUGIN_NAME; info.vendor_name = (char*) "eQualit.ie"; info.support_email = (char*) "info@deflect.ca"; if (!check_ts_version(TSTrafficServerVersionGet())) { TSError("Plugin requires Traffic Server 3.0 or later"); return abort_traffic_server(); } { std::stringstream ss; for (int i = 0; i < argc; i++) { ss << "\"" << argv[i] << "\""; if (i != argc + 1) ss << ", "; } TSDebug(BANJAX_PLUGIN_NAME, "TSPluginInit args: %s", ss.str().c_str()); } // Set the config folder to a default value (can be modified by argv[1]) std::string banjax_config_dir = TSPluginDirGet(); if (argc > 1) { banjax_config_dir = argv[1]; struct stat stat_buffer; if (stat(banjax_config_dir.c_str(), &stat_buffer) < 0) { std::string error_str = "given banjax config directory " + banjax_config_dir + " doen't exist or is unaccessible."; TSError(error_str.c_str()); return abort_traffic_server(); } if (!S_ISDIR(stat_buffer.st_mode)) { std::string error_str = "given banjax config directory " + banjax_config_dir + " doesn't seem to be an actual directory"; TSError(error_str.c_str()); return abort_traffic_server(); } } //if everything went smoothly then register banjax #if(TS_VERSION_NUMBER < 6000000) if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { #else if (TSPluginRegister(&info) != TS_SUCCESS) { #endif TSError("[version] Plugin registration failed. \n"); return abort_traffic_server(); } /* create the banjax object that control the whole procedure */ g_banjax_plugin.reset(new BanjaxPlugin{banjax_config_dir}); atexit(destroy_g_banjax_plugin); // Start handling transactions TSCont contp = TSContCreate(handle_transaction_start, nullptr); TSHttpHookAdd(TS_HTTP_TXN_START_HOOK, contp); // Handle reload by traffic_line -x TSCont management_contp = TSContCreate(handle_management, nullptr); TSMgmtUpdateRegister(management_contp, BANJAX_PLUGIN_NAME); } /** * stop ats due to banjax config problem */ void abort_traffic_server() { TSError("Banjax was unable to start properly"); TSError("preventing ATS to run cause quietly starting ats without banjax is worst possible combination"); TSReleaseAssert(false); } <commit_msg>Get rid of banjax.cpp/TSErrorAlternative<commit_after>/* * Banjax is an ATS plugin that: * enforce regex bans * store logs in a mysql db * run SVM on the log result * send a ban request to swabber in case of banning. * * Copyright (c) 2013 eQualit.ie under GNU AGPL v3.0 or later * * Vmon: June 2013 Initial version */ #include <ts/ts.h> #include <string> #include <iostream> #include <sys/stat.h> #include "transaction_data.h" #include "white_lister.h" #include "bot_sniffer.h" #include "denialator.h" #include "banjax.h" #include "defer.h" #include "print.h" using namespace std; const string CONFIG_FILENAME = "banjax.conf"; struct BanjaxPlugin { string config_dir; TSMutex reload_mutex; std::shared_ptr<Banjax> current_state; BanjaxPlugin(string config_dir) : config_dir(move(config_dir)) , reload_mutex(TSMutexCreate()) , current_state(make_shared<Banjax>(this->config_dir)) {} void reload_config() { TSMutexLock(reload_mutex); auto on_exit = defer([&] { TSMutexUnlock(reload_mutex); }); auto swab_s = current_state->release_swabber_socket(); auto snif_s = current_state->release_botsniffer_socket(); std::shared_ptr<Banjax> new_banjax(new Banjax(config_dir, move(swab_s), move(snif_s))); // This happens atomically, so (in theory) we don't need to wrap in in mutex // in the handle_transaction_start hook. current_state = std::move(new_banjax); } }; std::shared_ptr<BanjaxPlugin> g_banjax_plugin; /** Read the config file and create filters whose name is mentioned in the config file. If you make a new filter you need to add it inside this function */ void Banjax::build_filters() { BanjaxFilter* cur_filter; for (const pair<int,string>& cur_filter_name : priority_map) { FilterConfig& cur_config = filter_config_map[cur_filter_name.second]; try { if (cur_filter_name.second == REGEX_BANNER_FILTER_NAME) { regex_manager.reset(new RegexManager(cur_config, &regex_manager_ip_db, &swabber_interface)); cur_filter = regex_manager.get(); } else if (cur_filter_name.second == CHALLENGER_FILTER_NAME){ challenge_manager.reset(new ChallengeManager(banjax_config_dir, cur_config, &challenger_ip_db, &swabber_interface, &global_ip_white_list)); cur_filter = challenge_manager.get(); } else if (cur_filter_name.second == WHITE_LISTER_FILTER_NAME){ white_lister.reset(new WhiteLister(cur_config, global_ip_white_list)); cur_filter = white_lister.get(); } else if (cur_filter_name.second == BOT_SNIFFER_FILTER_NAME){ bot_sniffer.reset(new BotSniffer(cur_config, move(botsniffer_socket_reuse))); cur_filter = bot_sniffer.get(); } else if (cur_filter_name.second == DENIALATOR_FILTER_NAME){ denialator.reset(new Denialator(cur_config, &swabber_ip_db, &swabber_interface, &global_ip_white_list)); cur_filter = denialator.get(); } else { print::debug("Don't know how to construct filter: \"", cur_filter_name.second, "\""); abort_traffic_server(); } } catch (YAML::Exception& e) { print::debug("Error in intializing filter ", cur_filter_name.second); abort_traffic_server(); } //at which que the filter need to be called for(unsigned int i = BanjaxFilter::HTTP_START; i < BanjaxFilter::TOTAL_NO_OF_QUEUES; i++) { if (cur_filter->queued_tasks[i]) { print::debug("Active task ", cur_filter->BANJAX_FILTER_NAME, " on queue:", i); task_queues[i].push_back(cur_filter->queued_tasks[i]); } } all_filters_requested_part |= cur_filter->requested_info(); all_filters_response_part |= cur_filter->response_info(); } } static int handle_transaction_start(TSCont contp, TSEvent event, void *edata) { if (event != TS_EVENT_HTTP_TXN_START) { print::debug("Txn unexpected event"); return TS_EVENT_NONE; } TSHttpTxn txnp = (TSHttpTxn) edata; print::debug("Txn start"); TSCont txn_contp; TransactionData *cd; txn_contp = TSContCreate((TSEventFunc) TransactionData::handle_transaction_change, TSMutexCreate()); /* create the data that'll be associated with the continuation */ cd = (TransactionData *) TSmalloc(sizeof(TransactionData)); cd = new(cd) TransactionData(g_banjax_plugin->current_state, txnp); TSContDataSet(txn_contp, cd); TSHttpTxnHookAdd(txnp, TS_HTTP_READ_REQUEST_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_REQUEST_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, txn_contp); TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, txn_contp); TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); return TS_EVENT_NONE; } static int handle_management(TSCont contp, TSEvent event, void *edata) { (void) contp; (void) edata; print::debug("Reload configuration signal received"); TSReleaseAssert(event == TS_EVENT_MGMT_UPDATE); g_banjax_plugin->reload_config(); return 0; } std::unique_ptr<Socket> Banjax::release_swabber_socket() { return swabber_interface.release_socket(); } std::unique_ptr<Socket> Banjax::release_botsniffer_socket() { if (!bot_sniffer) return nullptr; return bot_sniffer->release_socket(); } /** Constructor @param banjax_config_dir path to the folder containing banjax.conf */ Banjax::Banjax(const string& banjax_config_dir, std::unique_ptr<Socket> swabber_socket, std::unique_ptr<Socket> bot_sniffer_socket) : all_filters_requested_part(0), all_filters_response_part(0), banjax_config_dir(banjax_config_dir), swabber_interface(&swabber_ip_db, move(swabber_socket)), botsniffer_socket_reuse(move(bot_sniffer_socket)) { /* create an TSTextLogObject to log blacklisted requests to */ TSReturnCode error = TSTextLogObjectCreate(BANJAX_PLUGIN_NAME, TS_LOG_MODE_ADD_TIMESTAMP, &log); if (!log || error == TS_ERROR) { print::debug("Error while creating log"); } read_configuration(); } void Banjax::read_configuration() { // Read the file. If there is an error, report it and exit. static const string sep = "/"; string absolute_config_file = banjax_config_dir + sep + CONFIG_FILENAME; print::debug("Reading configuration from [", absolute_config_file, "]"); try { cfg = YAML::LoadFile(absolute_config_file); process_config(cfg); } catch(YAML::BadFile& e) { print::debug("I/O error while reading config file [",absolute_config_file,"]: [",e.what(),"]. Make sure that file exists."); abort_traffic_server(); } catch(YAML::ParserException& e) { print::debug("parsing error while reading config file [",absolute_config_file,"]: [",e.what(),"]."); abort_traffic_server(); } print::debug("Finished loading main conf"); int min_priority = 0, max_priority = 0; //setting up priorities if (priorities.size()) { //first find the max priorities try { min_priority = priorities.begin()->second.as<int>(); max_priority = priorities.begin()->second.as<int>(); } catch( YAML::RepresentationException &e ) { print::debug("Bad config format ", e.what()); abort_traffic_server(); } for (const auto& p : priorities) { if (p.second.as<int>() > max_priority) max_priority = p.second.as<int>(); if (p.second.as<int>() < min_priority) min_priority = p.second.as<int>(); } } //now either replace priorities or add them up for(pair<const std::string, FilterConfig>& p : filter_config_map) { if (priorities[p.first]) { p.second.priority = priorities[p.first].as<int>(); } else { p.second.priority += max_priority + 1; } if (priority_map.count(p.second.priority)) { print::debug("Priority ", p.second.priority, " has been doubly assigned"); abort_traffic_server(); } priority_map[p.second.priority] = p.first; } //(re)set swabber configuration if there is no swabber node //in the configuration we reset the configuration swabber_interface.load_config(swabber_conf); //now we can make the filters build_filters(); } //Recursively read the entire config structure //including inside the included files void Banjax::process_config(const YAML::Node& cfg) { static const string sep = "/"; int current_sequential_priority = 0; auto is_filter = [](const std::string& s) { return std::find( all_filters_names.begin() , all_filters_names.end(), s) != all_filters_names.end(); }; for (YAML::const_iterator it = cfg.begin(); it != cfg.end(); ++it) { try { std::string node_name = it->first.as<std::string>(); if (is_filter(node_name)) { // If it's a filter see if it is already in the list if (filter_config_map.find(node_name) == filter_config_map.end()) { filter_config_map[node_name].priority = current_sequential_priority; current_sequential_priority++; } filter_config_map[node_name].config_node_list.push_back(it); } else if (node_name == "swabber") { //we simply send swabber configuration to swabber //if it doesn't exists it fails to default swabber_conf.config_node_list.push_back(it); } else if (node_name == "priority") { // Store it as priority config. for now we fire error if priority is // double defined if (priorities.size()) { print::debug("Double definition of priorities. only one priority list is allowed."); abort_traffic_server(); } priorities = Clone(it->second); } else if (node_name == "include") { for(const auto& sub : it->second) { string inc_loc = banjax_config_dir + sep + sub.as<std::string>(); print::debug("Reading configuration from [", inc_loc, "]"); try { process_config(YAML::LoadFile(inc_loc)); } catch(YAML::BadFile& e) { print::debug("I/O error while reading config file [",inc_loc,"]: [",e.what(),"]. Make sure that file exists."); abort_traffic_server(); } catch(YAML::ParserException& e) { print::debug("Parsing error while reading config file [",inc_loc,"]: [",e.what(),"]."); abort_traffic_server(); } } } else { //unknown node print::debug("Unknown config node ", node_name); abort_traffic_server(); } } catch( YAML::RepresentationException &e ) { print::debug("Bad config format ", e.what()); abort_traffic_server(); } } } static void destroy_g_banjax_plugin() { g_banjax_plugin.reset(); } void TSPluginInit(int argc, const char *argv[]) { TSPluginRegistrationInfo info; info.plugin_name = (char*) BANJAX_PLUGIN_NAME; info.vendor_name = (char*) "eQualit.ie"; info.support_email = (char*) "info@deflect.ca"; if (!check_ts_version(TSTrafficServerVersionGet())) { print::debug("Plugin requires Traffic Server 3.0 or later"); return abort_traffic_server(); } { std::stringstream ss; for (int i = 0; i < argc; i++) { ss << "\"" << argv[i] << "\""; if (i != argc + 1) ss << ", "; } print::debug("TSPluginInit args: ", ss.str()); } // Set the config folder to a default value (can be modified by argv[1]) std::string banjax_config_dir = TSPluginDirGet(); if (argc > 1) { banjax_config_dir = argv[1]; struct stat stat_buffer; if (stat(banjax_config_dir.c_str(), &stat_buffer) < 0) { std::string error_str = "given banjax config directory " + banjax_config_dir + " doen't exist or is unaccessible."; print::debug(error_str.c_str()); return abort_traffic_server(); } if (!S_ISDIR(stat_buffer.st_mode)) { std::string error_str = "given banjax config directory " + banjax_config_dir + " doesn't seem to be an actual directory"; print::debug(error_str.c_str()); return abort_traffic_server(); } } //if everything went smoothly then register banjax #if(TS_VERSION_NUMBER < 6000000) if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { #else if (TSPluginRegister(&info) != TS_SUCCESS) { #endif print::debug("[version] Plugin registration failed."); return abort_traffic_server(); } /* create the banjax object that control the whole procedure */ g_banjax_plugin.reset(new BanjaxPlugin{banjax_config_dir}); atexit(destroy_g_banjax_plugin); // Start handling transactions TSCont contp = TSContCreate(handle_transaction_start, nullptr); TSHttpHookAdd(TS_HTTP_TXN_START_HOOK, contp); // Handle reload by traffic_line -x TSCont management_contp = TSContCreate(handle_management, nullptr); TSMgmtUpdateRegister(management_contp, BANJAX_PLUGIN_NAME); } /** * stop ats due to banjax config problem */ void abort_traffic_server() { print::debug("Banjax was unable to start properly."); print::debug("preventing ATS to run cause quietly starting ATS without banjax is worst possible combination"); TSReleaseAssert(false); } <|endoftext|>
<commit_before>/********************************************************************* Author: Roberto Bruttomesso <roberto.bruttomesso@unisi.ch> OpenSMT -- Copyright (C) 2008, Roberto Bruttomesso OpenSMT 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. OpenSMT 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 OpenSMT. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #include "Egraph.h" #include "MinisatSMTSolver.h" #include "Tseitin.h" #include <cstdlib> #include <cstdio> #include <iostream> #include <csignal> #if defined(__linux__) #include <fpu_control.h> #endif void printResult( const lbool & ); void catcher( int ); extern int smtparse( ); extern int smtrestart( FILE * ); Egraph * parser_egraph; SMTConfig * parser_config; /*****************************************************************************\ * * * MAIN * * * \*****************************************************************************/ int main( int argc, char * argv[] ) { // Catch SigTerm, so that it answers even on ctrl-c signal( SIGTERM, catcher ); signal( SIGINT, catcher ); #ifndef SMTCOMP cerr << "#" << endl << "# -------------------------------------------------------------------------" << endl << "# " << endl << "# OpenSMT " << VERSION << "-- Copyright (C) 2008, Roberto Bruttomesso" << endl << "# " << endl << "# OpenSMT is free software: you can redistribute it and/or modify it under " << endl << "# the terms of the GNU General Public License as published by the Free " << endl << "# Software Foundation, either version 3 of the License, or (at your option)" << endl << "# any later version. " << endl << "# " << endl << "# OpenSMT is distributed in the hope that it will be useful, but WITHOUT " << endl << "# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or " << endl << "# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for " << endl << "# more details. " << endl << "# " << endl << "# You should have received a copy of the GNU General Public License along " << endl << "# with OpenSMT. If not, see <http://www.gnu.org/licenses/>. " << endl << "# " << endl << "# -------------------------------------------------------------------------" << endl << "# http://code.google.com/p/opensmt <roberto.bruttomesso@unisi.ch>" << endl << "# -------------------------------------------------------------------------" << endl << "#" << endl; #endif // Allocate configuration SMTConfig config( UNDEF, l_Undef ); // Allocates the egraph Egraph egraph( config ); // Parse the input formula parser_egraph = &egraph; parser_config = &config; // Accepts file from stdin if nothing specified FILE * fin = NULL; if ( argc == 1 ) fin = stdin; else if ( (fin = fopen( argv[ 1 ], "rt" )) == NULL ) { cerr << "Error: can't open file " << argv[ 1 ] << endl; exit( 1 ); } // Parse smtrestart( fin ); smtparse( ); fclose( fin ); // Initializes theory solvers egraph.initializeTheorySolvers( ); // // This trick (copied from Main.C of MiniSAT) is to allow // the repeatability of experiments that might be compromised // by the floating point unit approximations on doubles // #if defined(__linux__) && !defined( SMTCOMP ) fpu_control_t oldcw, newcw; _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw); reportf("# WARNING: for repeatability, setting FPU to use double precision\n"); #endif #ifdef PEDANTIC_DEBUG reportf("# WARNING: pedantic assertion checking enabled (very slow)\n"); #endif #ifdef EXTERNAL_TOOL reportf("# WARNING: external tool checking enabled (very slow)\n"); #endif #ifndef OPTIMIZE reportf( "# WARNING: this binary is compiled with optimizations disabled (slow)\n" ); #endif #ifndef SMTCOMP reportf( "#\n" ); #endif // Retrieve the formula Enode * formula = egraph.getFormula( ); if ( formula == NULL ) { cerr << "Error: formula undefined" << endl; exit( 1 ); } if ( config.logic == UNDEF ) { cerr << "Error: unable to determine logic" << endl; return 1; } // Allocates SMTSolver based on MiniSAT MinisatSMTSolver solver( egraph, config ); // Allocates Tseitin-like cnfizer Tseitin cnfizer( egraph, solver, config ); // CNFize the input formula and fed clauses to the solver lbool result = cnfizer.cnfizeAndGiveToSolver( formula ); // Solve result = solver.smtSolve( ); printResult( result ); // Prints the model (currently disabled) // if ( result == l_True ) S.printModel( ); #ifndef SMTCOMP if ( config.status != l_Undef && result != l_Undef && result != config.status ) { cerr << "# Error: result does not match with status" << endl; return 1; } #endif return 0; } void catcher(int sig) { switch (sig) { case SIGINT: case SIGTERM: printResult( l_Undef ); exit( 1 ); break; } } void printResult( const lbool & result ) { #ifndef SMTCOMP fflush( stderr ); #endif if ( result == l_True ) cout << "sat" << endl; else if ( result == l_False ) cout << "unsat" << endl; else if ( result == l_Undef ) cout << "unknown" << endl; else { cerr << "Error: wrong result" << endl; exit( 1 ); } fflush( stdout ); #ifndef SMTCOMP // // Statistics // double cpu_time = cpuTime(); reportf( "#\n" ); reportf( "# CPU Time used: %g s\n", cpu_time == 0 ? 0 : cpu_time ); #if defined(__linux__) uint64_t mem_used = memUsed(); reportf( "# Memory used: %.3f MB\n", mem_used == 0 ? 0 : mem_used / 1048576.0 ); #endif reportf( "#\n" ); #endif } <commit_msg>Added a space in the header [RB]<commit_after>/********************************************************************* Author: Roberto Bruttomesso <roberto.bruttomesso@unisi.ch> OpenSMT -- Copyright (C) 2008, Roberto Bruttomesso OpenSMT 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. OpenSMT 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 OpenSMT. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #include "Egraph.h" #include "MinisatSMTSolver.h" #include "Tseitin.h" #include <cstdlib> #include <cstdio> #include <iostream> #include <csignal> #if defined(__linux__) #include <fpu_control.h> #endif void printResult( const lbool & ); void catcher( int ); extern int smtparse( ); extern int smtrestart( FILE * ); Egraph * parser_egraph; SMTConfig * parser_config; /*****************************************************************************\ * * * MAIN * * * \*****************************************************************************/ int main( int argc, char * argv[] ) { // Catch SigTerm, so that it answers even on ctrl-c signal( SIGTERM, catcher ); signal( SIGINT, catcher ); #ifndef SMTCOMP cerr << "#" << endl << "# -------------------------------------------------------------------------" << endl << "# " << endl << "# OpenSMT " << VERSION << " -- Copyright (C) 2008, Roberto Bruttomesso" << endl << "# " << endl << "# OpenSMT is free software: you can redistribute it and/or modify it under " << endl << "# the terms of the GNU General Public License as published by the Free " << endl << "# Software Foundation, either version 3 of the License, or (at your option)" << endl << "# any later version. " << endl << "# " << endl << "# OpenSMT is distributed in the hope that it will be useful, but WITHOUT " << endl << "# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or " << endl << "# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for " << endl << "# more details. " << endl << "# " << endl << "# You should have received a copy of the GNU General Public License along " << endl << "# with OpenSMT. If not, see <http://www.gnu.org/licenses/>. " << endl << "# " << endl << "# -------------------------------------------------------------------------" << endl << "# http://code.google.com/p/opensmt <roberto.bruttomesso@unisi.ch>" << endl << "# -------------------------------------------------------------------------" << endl << "#" << endl; #endif // Allocate configuration SMTConfig config( UNDEF, l_Undef ); // Allocates the egraph Egraph egraph( config ); // Parse the input formula parser_egraph = &egraph; parser_config = &config; // Accepts file from stdin if nothing specified FILE * fin = NULL; if ( argc == 1 ) fin = stdin; else if ( (fin = fopen( argv[ 1 ], "rt" )) == NULL ) { cerr << "Error: can't open file " << argv[ 1 ] << endl; exit( 1 ); } // Parse smtrestart( fin ); smtparse( ); fclose( fin ); // Initializes theory solvers egraph.initializeTheorySolvers( ); // // This trick (copied from Main.C of MiniSAT) is to allow // the repeatability of experiments that might be compromised // by the floating point unit approximations on doubles // #if defined(__linux__) && !defined( SMTCOMP ) fpu_control_t oldcw, newcw; _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw); reportf("# WARNING: for repeatability, setting FPU to use double precision\n"); #endif #ifdef PEDANTIC_DEBUG reportf("# WARNING: pedantic assertion checking enabled (very slow)\n"); #endif #ifdef EXTERNAL_TOOL reportf("# WARNING: external tool checking enabled (very slow)\n"); #endif #ifndef OPTIMIZE reportf( "# WARNING: this binary is compiled with optimizations disabled (slow)\n" ); #endif #ifndef SMTCOMP reportf( "#\n" ); #endif // Retrieve the formula Enode * formula = egraph.getFormula( ); if ( formula == NULL ) { cerr << "Error: formula undefined" << endl; exit( 1 ); } if ( config.logic == UNDEF ) { cerr << "Error: unable to determine logic" << endl; return 1; } // Allocates SMTSolver based on MiniSAT MinisatSMTSolver solver( egraph, config ); // Allocates Tseitin-like cnfizer Tseitin cnfizer( egraph, solver, config ); // CNFize the input formula and fed clauses to the solver lbool result = cnfizer.cnfizeAndGiveToSolver( formula ); // Solve result = solver.smtSolve( ); printResult( result ); // Prints the model (currently disabled) // if ( result == l_True ) S.printModel( ); #ifndef SMTCOMP if ( config.status != l_Undef && result != l_Undef && result != config.status ) { cerr << "# Error: result does not match with status" << endl; return 1; } #endif return 0; } void catcher(int sig) { switch (sig) { case SIGINT: case SIGTERM: printResult( l_Undef ); exit( 1 ); break; } } void printResult( const lbool & result ) { #ifndef SMTCOMP fflush( stderr ); #endif if ( result == l_True ) cout << "sat" << endl; else if ( result == l_False ) cout << "unsat" << endl; else if ( result == l_Undef ) cout << "unknown" << endl; else { cerr << "Error: wrong result" << endl; exit( 1 ); } fflush( stdout ); #ifndef SMTCOMP // // Statistics // double cpu_time = cpuTime(); reportf( "#\n" ); reportf( "# CPU Time used: %g s\n", cpu_time == 0 ? 0 : cpu_time ); #if defined(__linux__) uint64_t mem_used = memUsed(); reportf( "# Memory used: %.3f MB\n", mem_used == 0 ? 0 : mem_used / 1048576.0 ); #endif reportf( "#\n" ); #endif } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : B2.cpp * Author : Kazune Takahashi * Created : 7/22/2019, 3:04:34 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } ll N, K; ll C; int A[200010]; ll a[60][200010]; int main() { cin >> N >> K; C = N * K; for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { a[i][0] = -1; } vector<int> used(200010, -1); for (auto k = 0; k < 2; k++) { for (auto i = 0; i < N; i++) { if (used[A[i]] != -1) { a[0][used[A[i]]] = k * N + i - used[A[i]] + 1; } used[A[i]] = k * N + i; } } #if DEBUG == 1 for (auto i = 0; i < N; i++) { cerr << "a[0][" << i << "] = " << a[0][i] << endl; } #endif for (auto k = 1; k < 60; k++) { for (auto i = 0; i < N; i++) { a[k][i] = a[k - 1][i] + a[k - 1][a[k - 1][i] % N]; #if DEBUG == 1 if (k < 3) { cerr << "a[" << k << "][" << i << "] = " << a[k][i] << endl; } #endif } } ll sum = 0; int now = 0; while (true) { int ind = 0; for (auto k = 0; k < 60; k++) { if (a[k][now] + sum >= C) { ind = k - 1; break; } } if (ind == -1) { break; } sum += a[ind][now]; now = sum % N; } #if DEBUG == 1 cerr << "sum = " << sum << endl; cerr << "now = " << now << endl; #endif deque<int> D; vector<bool> stacked(200010, false); for (auto i = now; i < N; i++) { if (!stacked[A[i]]) { D.push_back(A[i]); stacked[A[i]] = true; } else { while (true) { int x = *D.rbegin(); D.pop_back(); stacked[x] = false; if (x == A[i]) { break; } } } } for (auto i = 0u; i < D.size(); i++) { cout << D[i]; if (i < D.size() - 1) { cout << " "; } } cout << endl; }<commit_msg>tried B2.cpp to 'B'<commit_after>#define DEBUG 1 /** * File : B2.cpp * Author : Kazune Takahashi * Created : 7/22/2019, 3:04:34 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } ll N, K; ll C; int A[200010]; ll a[60][200010]; int main() { cin >> N >> K; C = N * K; for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { a[i][0] = -1; } vector<int> used(200010, -1); for (auto k = 0; k < 2; k++) { for (auto i = 0; i < N; i++) { if (used[A[i]] != -1) { a[0][used[A[i]]] = k * N + i - used[A[i]] + 1; } used[A[i]] = k * N + i; } } #if DEBUG == 1 for (auto i = 0; i < N; i++) { cerr << "a[0][" << i << "] = " << a[0][i] << endl; } #endif for (auto k = 1; k < 60; k++) { for (auto i = 0; i < N; i++) { a[k][i] = a[k - 1][i] + a[k - 1][a[k - 1][i] % N]; #if DEBUG == 1 if (k < 5) { cerr << "a[" << k << "][" << i << "] = " << a[k][i] << endl; } #endif } } ll sum = 0; int now = 0; while (true) { int ind = 0; for (auto k = 0; k < 60; k++) { if (a[k][now] + sum >= C) { ind = k - 1; break; } } if (ind == -1) { break; } sum += a[ind][now]; now = sum % N; } #if DEBUG == 1 cerr << "sum = " << sum << endl; cerr << "now = " << now << endl; #endif deque<int> D; vector<bool> stacked(200010, false); for (auto i = now; i < N; i++) { if (!stacked[A[i]]) { D.push_back(A[i]); stacked[A[i]] = true; } else { while (true) { int x = *D.rbegin(); D.pop_back(); stacked[x] = false; if (x == A[i]) { break; } } } } for (auto i = 0u; i < D.size(); i++) { cout << D[i]; if (i < D.size() - 1) { cout << " "; } } cout << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E3.cpp * Author : Kazune Takahashi * Created : 2019/9/2 0:33:07 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } using point = tuple<int, int>; ostream &operator<<(ostream &os, point p) { return os << "{" << get<0>(p) << ", " << get<1>(p) << "}"; } point make_point(int i, int j) { if (i > j) { swap(i, j); } return point{i, j}; } map<point, int> DP; map<point, vector<point>> V; set<point> Y; int dfs(point p) { if (DP.find(p) != DP.end()) { return DP[p]; } #if DEBUG == 1 cerr << "p = " << p << endl; #endif if (Y.find(p) != Y.end()) { No(); } DP[p] = 0; Y.insert(p); for (auto e : V[p]) { maxs(DP[p], dfs(e) + 1); } Y.erase(p); return DP[p]; } int main() { int N; cin >> N; vector<vector<int>> A(N, vector<int>(N - 1)); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N - 1; j++) { cin >> A[i][j]; A[i][j]--; } } for (auto i = 0; i < N; i++) { for (auto j = 1; j < N - 1; j++) { point from{make_point(i, A[i][j - 1])}; point to{make_point(i, A[i][j])}; V[to].push_back(from); #if DEBUG == 1 cerr << "to: " << to << ", from: " << from << endl; #endif } } for (auto i = 0; i < N; i++) { for (auto j = i + 1; j < N; j++) { dfs(point{i, j}); } } int ans{0}; for (auto e : DP) { maxs(ans, e.second); } cout << ans << endl; }<commit_msg>tried E3.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E3.cpp * Author : Kazune Takahashi * Created : 2019/9/2 0:33:07 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define maxs(x, y) (x = max(x, y)) #define mins(x, y) (x = min(x, y)) using ll = long long; class mint { public: static ll MOD; ll x; mint() : x(0) {} mint(ll x) : x(x % MOD) {} mint operator-() const { return x ? MOD - x : 0; } mint &operator+=(const mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } mint &operator-=(const mint &a) { return *this += -a; } mint &operator*=(const mint &a) { (x *= a.x) %= MOD; return *this; } mint &operator/=(const mint &a) { mint b{a}; return *this *= b.power(MOD - 2); } mint operator+(const mint &a) const { return mint(*this) += a; } mint operator-(const mint &a) const { return mint(*this) -= a; } mint operator*(const mint &a) const { return mint(*this) *= a; } mint operator/(const mint &a) const { return mint(*this) /= a; } bool operator<(const mint &a) const { return x < a.x; } bool operator==(const mint &a) const { return x == a.x; } const mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { mint half = power(N / 2); return half * half; } } }; ll mint::MOD = 1e9 + 7; istream &operator>>(istream &stream, mint &a) { return stream >> a.x; } ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; } class combination { public: vector<mint> inv, fact, factinv; static int MAX_SIZE; combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2; i < MAX_SIZE; i++) { inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1; i < MAX_SIZE; i++) { fact[i] = mint(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } mint operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } }; int combination::MAX_SIZE = 3000010; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } using point = tuple<int, int>; ostream &operator<<(ostream &os, point p) { return os << "{" << get<0>(p) << ", " << get<1>(p) << "}"; } point make_point(int i, int j) { if (i > j) { swap(i, j); } return point{i, j}; } map<point, int> DP; map<point, vector<point>> V; set<point> Y; int dfs(point p) { if (DP.find(p) != DP.end()) { return DP[p]; } #if DEBUG == 1 cerr << "p = " << p << endl; #endif if (Y.find(p) != Y.end()) { No(); } Y.insert(p); int tmp{0}; for (auto e : V[p]) { maxs(tmp, dfs(e) + 1); } Y.erase(p); return DP[p] = tmp; } int main() { int N; cin >> N; vector<vector<int>> A(N, vector<int>(N - 1)); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N - 1; j++) { cin >> A[i][j]; A[i][j]--; } } for (auto i = 0; i < N; i++) { for (auto j = 1; j < N - 1; j++) { point from{make_point(i, A[i][j - 1])}; point to{make_point(i, A[i][j])}; V[to].push_back(from); #if DEBUG == 1 cerr << "to: " << to << ", from: " << from << endl; #endif } } for (auto i = 0; i < N; i++) { for (auto j = i + 1; j < N; j++) { dfs(point{i, j}); } } int ans{0}; for (auto e : DP) { maxs(ans, e.second); } cout << ans << endl; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mybasic.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:12:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SBXCLASS_HXX //autogen #include <svtools/sbx.hxx> #endif // AB-Uno-Test //#define unotest #ifdef unotest #ifndef _USR_UNO_HXX #include <usr/uno.hxx> #endif #include <sbuno.hxx> #include <sbunoobj.hxx> #endif #include "sbintern.hxx" #ifndef _BASIC_TTRESHLP_HXX #include "ttstrhlp.hxx" #endif #include "mybasic.hxx" #include "basic.hrc" #include "appbased.hxx" #include "status.hxx" #include "basic.hrc" #include "object.hxx" #include "comm_bas.hxx" #include "processw.hxx" TYPEINIT1(MyBasic,StarBASIC) class MyFactory : public SbxFactory { public: virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX ); }; static SampleObjectFac aFac1; static MyFactory aFac2; static CommunicationFactory aComManFac; static ProcessFactory aProcessFac; static short nInst = 0; SbxBase* MyFactory::Create( UINT16 nSbxId, UINT32 nCr ) { if( nCr == SBXCR_TEST && nSbxId == SBXID_MYBASIC ) return new MyBasic; else return NULL; } MyBasic::MyBasic() : StarBASIC() { nError = 0; if( !nInst++ ) { AddFactory( &aFac1 ); AddFactory( &aFac2 ); AddFactory( &aComManFac ); AddFactory( &aProcessFac ); } SbxVariable* p = new SbxCollection( CUniString("MyColl") ); p->SetName( CUniString("Objects") ); Insert( p ); // AB-Uno-Test #ifdef unotest // Uno-Service-Manager holenReflection Service bolen createAndSetDefaultServiceManager(); // spaeter schon erledigt // Uno-Test-Objekt holen UsrAny aObjAny = getIntrospectionTestObject(); // Objekt verpacken in ein SbUnoObject packen String aName( "UnoObject" ); SbxObjectRef xSbUnoObj = GetSbUnoObject( aName, aObjAny ); //SbxObjectRef xSbUnoObj = new SbUnoObject( aName, aObjAny ); Insert( (SbxObject*)xSbUnoObj ); #endif pTestObject = NULL; } Link MyBasic::GenLogHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, Log ); } Link MyBasic::GenWinInfoHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, WinInfo ); } Link MyBasic::GenModuleWinExistsHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, ModuleWinExists ); } void MyBasic::StartListening( SfxBroadcaster &rBroadcaster ) { ((BasicFrame*)GetpApp()->GetAppWindow())->StartListening( rBroadcaster ); } void MyBasic::SetCompileModule( SbModule *pMod ) { GetSbData()->pCompMod = pMod; } SbModule *MyBasic::GetCompileModule() { return GetSbData()->pCompMod; } String MyBasic::GenRealString( const String &aResString ) { return ((BasicFrame*)GetpApp()->GetAppWindow())->GenRealString( aResString ); } void MyBasic::LoadIniFile() { } SbTextType MyBasic::GetSymbolType( const String &rSymbol, BOOL bWasTTControl ) { return SB_SYMBOL; // Alles was hier landet ist vom Typ SB_SYMBOL und bleibt es auch } MyBasic::~MyBasic() { aErrors.Clear(); if( !--nInst ) { RemoveFactory( &aFac1 ); RemoveFactory( &aFac2 ); RemoveFactory( &aComManFac ); RemoveFactory( &aProcessFac ); } } BOOL MyBasic::Compile( SbModule* p ) { aErrors.Clear(); nError = 0; return StarBASIC::Compile( p ); } BOOL MyBasic::ErrorHdl() { AppEdit *CurrWin = aBasicApp.pFrame->FindModuleWin( GetActiveModule()->GetName() ); if(CurrWin) CurrWin->ToTop(); else { // erstmal Fenster aufmachen String aModName = GetActiveModule()->GetName(); if ( aModName.Copy(0,2).CompareToAscii("--") == COMPARE_EQUAL ) aModName.Erase(0,2); GetActiveModule()->SetName(aModName); AppWin* p = new AppBasEd( aBasicApp.pFrame, GetActiveModule() ); p->Show(); p->GrabFocus(); } if( IsCompilerError() ) { aErrors.Insert( new BasicError ( aBasicApp.pFrame->pWork, 0, StarBASIC::GetErrorText(), GetLine(), GetCol1(), GetCol2() ), LIST_APPEND ); nError++; return BOOL( nError < 20 ); // Abbruch nach 20 Fehlern } else { ReportRuntimeError(); return FALSE; } } void MyBasic::ReportRuntimeError() { String nErrorText; nErrorText = GetSpechialErrorText(); BasicError( aBasicApp.pFrame->pWork, GetVBErrorCode( GetErrorCode() ), nErrorText, GetLine(), GetCol1(), GetCol2() ).Show(); } const String MyBasic::GetSpechialErrorText() { return GetErrorText(); } USHORT MyBasic::BreakHdl() { SbModule* pMod = GetActiveModule(); if( pMod ) { AppEdit* pWin = aBasicApp.pFrame->FindModuleWin( pMod->GetName() ); if( !pWin ) { // erstmal Fenster aufmachen String aModName = GetActiveModule()->GetName(); if ( aModName.Copy(0,2).CompareToAscii("--") == COMPARE_EQUAL ) aModName.Erase(0,2); GetActiveModule()->SetName(aModName); AppWin* p = new AppBasEd( aBasicApp.pFrame, GetActiveModule() ); p->Show(); p->GrabFocus(); p->ToTop(); pWin = aBasicApp.pFrame->FindModuleWin( aModName ); } pWin->Highlight( GetLine(), GetCol1(), GetCol2() ); } if( IsBreak() ) // Wenn Breakpoint (oder "Run to Cursor") { // if ( GetActiveModule()->IsBP(GetLine()) ) // GetActiveModule()->ClearBP(GetLine()); return aBasicApp.pFrame->BreakHandler(); } else { return aBasicApp.pFrame->BreakHandler(); } } /*************************************************************************** |* |* class BasicError |* ***************************************************************************/ BasicError::BasicError ( AppWin* w, USHORT nE, const String& r, USHORT nL, USHORT nC1, USHORT nC2 ) : aText( ResId( IDS_ERROR1 ) ) { pWin = w; nLine = nL; nCol1 = nC1; nCol2 = nC2; if( nE ) { aText += String::CreateFromInt32( nE ); aText.AppendAscii(": "); aText += r; } else aText = r; } // Dies ist ein Beispiel, wie die Fehler-Information geschickt // aufgebaut werden kann, um ein Statement zu highlighten. void BasicError::Show() { if( pWin && pWin->ISA(AppEdit) ) { ((AppEdit*)pWin)->Highlight( nLine, nCol1, nCol2 ); aBasicApp.pFrame->pStatus->Message( aText ); } else MessBox( aBasicApp.pFrame, WB_OK, aBasicApp.pFrame->GetText(), aText ).Execute(); } <commit_msg>better handling of runtime error<commit_after>/************************************************************************* * * $RCSfile: mybasic.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: gh $ $Date: 2000-11-07 14:03:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SBXCLASS_HXX //autogen #include <svtools/sbx.hxx> #endif // AB-Uno-Test //#define unotest #ifdef unotest #ifndef _USR_UNO_HXX #include <usr/uno.hxx> #endif #include <sbuno.hxx> #include <sbunoobj.hxx> #endif #include "sbintern.hxx" #ifndef _BASIC_TTRESHLP_HXX #include "ttstrhlp.hxx" #endif #include "mybasic.hxx" #include "basic.hrc" #include "appbased.hxx" #include "status.hxx" #include "basic.hrc" #include "object.hxx" #include "comm_bas.hxx" #include "processw.hxx" TYPEINIT1(MyBasic,StarBASIC) class MyFactory : public SbxFactory { public: virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX ); }; static SampleObjectFac aFac1; static MyFactory aFac2; static CommunicationFactory aComManFac; static ProcessFactory aProcessFac; static short nInst = 0; SbxBase* MyFactory::Create( UINT16 nSbxId, UINT32 nCr ) { if( nCr == SBXCR_TEST && nSbxId == SBXID_MYBASIC ) return new MyBasic; else return NULL; } MyBasic::MyBasic() : StarBASIC() { nError = 0; if( !nInst++ ) { AddFactory( &aFac1 ); AddFactory( &aFac2 ); AddFactory( &aComManFac ); AddFactory( &aProcessFac ); } SbxVariable* p = new SbxCollection( CUniString("MyColl") ); p->SetName( CUniString("Objects") ); Insert( p ); // AB-Uno-Test #ifdef unotest // Uno-Service-Manager holenReflection Service bolen createAndSetDefaultServiceManager(); // spaeter schon erledigt // Uno-Test-Objekt holen UsrAny aObjAny = getIntrospectionTestObject(); // Objekt verpacken in ein SbUnoObject packen String aName( "UnoObject" ); SbxObjectRef xSbUnoObj = GetSbUnoObject( aName, aObjAny ); //SbxObjectRef xSbUnoObj = new SbUnoObject( aName, aObjAny ); Insert( (SbxObject*)xSbUnoObj ); #endif pTestObject = NULL; } Link MyBasic::GenLogHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, Log ); } Link MyBasic::GenWinInfoHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, WinInfo ); } Link MyBasic::GenModuleWinExistsHdl() { return LINK( GetpApp()->GetAppWindow(), BasicFrame, ModuleWinExists ); } void MyBasic::StartListening( SfxBroadcaster &rBroadcaster ) { ((BasicFrame*)GetpApp()->GetAppWindow())->StartListening( rBroadcaster ); } void MyBasic::SetCompileModule( SbModule *pMod ) { GetSbData()->pCompMod = pMod; } SbModule *MyBasic::GetCompileModule() { return GetSbData()->pCompMod; } String MyBasic::GenRealString( const String &aResString ) { return ((BasicFrame*)GetpApp()->GetAppWindow())->GenRealString( aResString ); } void MyBasic::LoadIniFile() { } SbTextType MyBasic::GetSymbolType( const String &rSymbol, BOOL bWasTTControl ) { return SB_SYMBOL; // Alles was hier landet ist vom Typ SB_SYMBOL und bleibt es auch } MyBasic::~MyBasic() { aErrors.Clear(); if( !--nInst ) { RemoveFactory( &aFac1 ); RemoveFactory( &aFac2 ); RemoveFactory( &aComManFac ); RemoveFactory( &aProcessFac ); } } BOOL MyBasic::Compile( SbModule* p ) { aErrors.Clear(); nError = 0; return StarBASIC::Compile( p ); } BOOL MyBasic::ErrorHdl() { AppBasEd *pCurrWin = aBasicApp.pFrame->FindModuleWin( GetActiveModule()->GetName() ); if(pCurrWin) pCurrWin->ToTop(); else { // erstmal Fenster aufmachen String aModName = GetActiveModule()->GetName(); if ( aModName.Copy(0,2).CompareToAscii("--") == COMPARE_EQUAL ) aModName.Erase(0,2); GetActiveModule()->SetName(aModName); AppWin* p = new AppBasEd( aBasicApp.pFrame, GetActiveModule() ); p->Show(); p->GrabFocus(); } if( IsCompilerError() ) { aErrors.Insert( new BasicError ( pCurrWin, 0, StarBASIC::GetErrorText(), GetLine(), GetCol1(), GetCol2() ), LIST_APPEND ); nError++; return BOOL( nError < 20 ); // Abbruch nach 20 Fehlern } else { ReportRuntimeError( pCurrWin ); return FALSE; } } void MyBasic::ReportRuntimeError( AppBasEd *pEditWin ) { String nErrorText; nErrorText = GetSpechialErrorText(); if ( pEditWin ) // just in case the focus is not right pEditWin->ToTop(); BasicError( pEditWin, GetVBErrorCode( GetErrorCode() ), nErrorText, GetLine(), GetCol1(), GetCol2() ).Show(); } const String MyBasic::GetSpechialErrorText() { return GetErrorText(); } USHORT MyBasic::BreakHdl() { SbModule* pMod = GetActiveModule(); if( pMod ) { AppEdit* pWin = aBasicApp.pFrame->FindModuleWin( pMod->GetName() ); if( !pWin ) { // erstmal Fenster aufmachen String aModName = GetActiveModule()->GetName(); if ( aModName.Copy(0,2).CompareToAscii("--") == COMPARE_EQUAL ) aModName.Erase(0,2); GetActiveModule()->SetName(aModName); AppWin* p = new AppBasEd( aBasicApp.pFrame, GetActiveModule() ); p->Show(); p->GrabFocus(); p->ToTop(); pWin = aBasicApp.pFrame->FindModuleWin( aModName ); } pWin->Highlight( GetLine(), GetCol1(), GetCol2() ); } if( IsBreak() ) // Wenn Breakpoint (oder "Run to Cursor") { // if ( GetActiveModule()->IsBP(GetLine()) ) // GetActiveModule()->ClearBP(GetLine()); return aBasicApp.pFrame->BreakHandler(); } else { return aBasicApp.pFrame->BreakHandler(); } } /*************************************************************************** |* |* class BasicError |* ***************************************************************************/ BasicError::BasicError ( AppBasEd* w, USHORT nE, const String& r, USHORT nL, USHORT nC1, USHORT nC2 ) : aText( ResId( IDS_ERROR1 ) ) { pWin = w; nLine = nL; nCol1 = nC1; nCol2 = nC2; if( nE ) { aText += String::CreateFromInt32( nE ); aText.AppendAscii(": "); aText += r; } else aText = r; } // Dies ist ein Beispiel, wie die Fehler-Information geschickt // aufgebaut werden kann, um ein Statement zu highlighten. void BasicError::Show() { if( pWin ) { pWin->Highlight( nLine, nCol1, nCol2 ); aBasicApp.pFrame->pStatus->Message( aText ); } else MessBox( aBasicApp.pFrame, WB_OK, aBasicApp.pFrame->GetText(), aText ).Execute(); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cmath> #include <ctime> #include <regex> #include "lib/font.h" #include "lib/body.h" #include "lib/image.h" #include "lib/video.h" #include "lib/output.h" #include "lib/misc.h" #include "lib/matrix.h" #include "lib/linkedlist.h" #include "lib/units.h" #include <pngwriter.h> using namespace std; // Function to return the index of an argument in argv int FindFlag(char * argv[], int argc, string argumentShort, string argumentLong = "") { int shortIndex = -1; int longIndex = -1; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], argumentShort.c_str()) == 0 and shortIndex == -1) { shortIndex = i; } if (argumentLong != "") { if (strcmp(argv[i], argumentLong.c_str()) == 0 and longIndex == -1) { longIndex = i; } } } if (shortIndex != -1 and longIndex == -1) { return shortIndex; } else if (shortIndex == -1 and longIndex != -1) { return longIndex; } else { return -1; } } int main(int argc, char * argv[]) { string usageStatement = "Usage: ./sombrero [-g --generate] [-r --run] [-s --settings]"; // Need to make these "settable" by the user // Defaults int bodyCount = 200; int width = 640; int height = 480; // "run" settings double dt = DAY; int frames = 200; int framerate = 45; List bodyList = List(); Body * body; Body * bodyA; Body * bodyB; // No arguments supplied if (argc == 1) { cout << "No arguments supplied." << endl; cout << usageStatement << endl; return 1; } else { // Get indexes of main flags // May be more efficient to generate a dictionary of all of the flags and their indexes... int generateFlag = FindFlag(argv, argc, "-g", "--generate"); int runFlag = FindFlag(argv, argc, "-r", "--run"); int settingsFlag = FindFlag(argv, argc, "-s", "--settings"); string flagString = ""; bool generate = generateFlag != -1; bool run = runFlag != -1; bool settings = settingsFlag != -1; flagString = to_string(generate) + to_string(run) + to_string(settings); // Valid if flag string matches one of the following patterns: // 10* // 01* // REGUlAR EXPRESSIONS! regex validFlags("(01|10)(0|1)"); if (regex_match(flagString, validFlags)) { cout << "Valid!" << endl; } else { cout << "Not Valid!" << endl; } return 0; } /////////////////////// // Generate Body arrangement if (strcmp(argv[1], "-g") == 0 or strcmp(argv[1], "--generate") == 0) { if (argc >= 3) { // Generate random arrangement of bodies (+ rotation video) // i.e. create new bodyList if (strcmp(argv[2], "random") == 0) { for (int i = 0; i < bodyCount - 1; i++) { double r = Random(1e11, 1e11); double theta = Random(0, 2 * PI); double phi = Random(0, 2 * PI); double x = r * cos(theta) * cos(phi); double y = r * sin(theta); double z = r * cos(theta) * sin(phi); double mass = Random(1e23, 1e24); bodyList.Append(new Body(x, y, z, mass, Random(1e6, 9e6), 0, 0, 0)); } bodyList.Append(new Body(0.0, 0.0, 0.0, 2e30, 1e8, 0.0, 0.0, 0.0)); // Save bodies to output.txt Output output("init/output.txt", width, height, 100); output.AddAllBodies(bodyList); output.Save(); } // Generate rotate video around bodies // i.e. Load bodies from file else if (strcmp(argv[2], "rotate") == 0) { string filename = "init/output.txt"; if (argc == 4) { // Assume that the final argument is the filename filename = argv[3]; } if (FileExists(filename)) { LoadBodiesFromFile(filename.c_str(), bodyList); } else { cout << "./sombrero --generate rotate [filename]" << endl; cout << "When using rotate, must include valid filename: e.g. init/output.txt" << endl; return 1; } } // No *valid* options supplied else { cout << usageStatement << endl; cout << "Must supply generate argument: [random, rotate]" << endl; return 1; } } // No options supplied else { cout << usageStatement << endl; cout << "Must supply generate argument: [random, rotate]" << endl; return 1; } // Generate rotate video around bodies Video video = Video("images/", "image_", width, height, framerate); video.ClearImageFolder(); // Rotate bodies about the y-axis for (double angle = 0.0; angle < 360.0; angle ++) { string imageFileName = "images/image_" + PadWithZeroes(angle, 360) + ".png"; Image image = Image(imageFileName, width, height, 100); body = bodyList.GetHead(); while (body != NULL) { // Rotate body Vector p; p.Set(body->GetX(), body->GetY(), body->GetZ()); Vector t; t = p.RotateY(angle); t = t.RoundValues(); image.DrawBody(t.GetX(), t.GetY(), 255, 255, 255); body = body->next; } // Add details to image image.DrawText("ROTATION", 10, 10, 255, 255, 255); image.DrawText("A: " + to_string((int)angle), 10, 20, 255, 255, 255); image.DrawText("N: " + to_string(bodyList.GetLength()), 10, 30, 255, 255, 255); image.Save(); } // Build video from images video.Build("result.mp4", 360); return 0; } // Run simulation if (strcmp(argv[1], "-r") == 0 or strcmp(argv[1], "--run") == 0) { LoadBodiesFromFile("init/output.txt", bodyList); Video video = Video("images/", "image_", width, height, framerate); video.ClearImageFolder(); for (int f = 0; f < frames; f++) { // Reset force counter on each body body = bodyList.GetHead(); while (body != NULL) { body->ResetForce(); body = body->next; } // n-body Algorithm (optimised) bodyA = bodyList.GetHead(); bodyB = NULL; while (bodyA != NULL) { bodyB = bodyA->next; while (bodyB != NULL) { // Calculate distance double xDistance = bodyA->GetX() - bodyB->GetX(); double yDistance = bodyA->GetY() - bodyB->GetY(); double zDistance = bodyA->GetZ() - bodyB->GetZ(); double totalDistance = sqrt(pow(xDistance, 2) + pow(yDistance, 2) + pow(zDistance, 2)); // Calculate angles double phiAngle = atan2(zDistance, sqrt(pow(xDistance, 2) + pow(yDistance, 2))); double thetaAngle = atan2(yDistance, xDistance); // Calculate force double force = GR * ((bodyA->GetMass() * bodyB->GetMass()) / (pow(totalDistance, 2))); // Add forces to totals bodyA->AddForce(force, phiAngle, thetaAngle); bodyB->AddForce(-force, phiAngle, thetaAngle); // Advance pointer bodyB = bodyB->next; } bodyA = bodyA->next; } string imageFileName = "images/image_" + PadWithZeroes(f, frames) + ".png"; Image image = Image(imageFileName, width, height, 100); // Calculate next position for each body body = bodyList.GetHead(); while (body != NULL) { body->Update(dt); body = body->next; } // Collision Physics bodyA = bodyList.GetHead(); bodyB = NULL; while (bodyA != NULL) { bodyB = bodyA->next; while (bodyB != NULL) { double collisionTime = -1; // Set up position vectors Vector initialA; initialA.Set(bodyA->GetX(), bodyA->GetY(), bodyA->GetZ()); Vector finalA; finalA.Set(bodyA->GetNextX(), bodyA->GetNextY(), bodyA->GetNextZ()); Vector initialB; initialB.Set(bodyB->GetX(), bodyB->GetY(), bodyB->GetZ()); Vector finalB; finalB.Set(bodyB->GetNextX(), bodyB->GetNextY(), bodyB->GetNextZ()); // Check the two lines are not parallel Vector lineA = finalA.Subtract(initialA); Vector lineB = finalB.Subtract(initialB); if (lineA.DotProduct(lineB) != 0) { // Calculate collision times Vector vectorA = initialB.Subtract(initialA); Vector vectorB = (finalB.Subtract(finalA)).Add(initialA.Subtract(initialB)); double dotProduct = vectorA.DotProduct(vectorB); double radiiSum = bodyA->GetRadius() + bodyB->GetRadius(); double determinant = (4 * pow(dotProduct, 2)) - (4 * pow(vectorB.Magnitude(), 2) * (pow(vectorA.Magnitude(), 2) - pow(radiiSum, 2))); double time1 = (-2 * dotProduct + sqrt(determinant)) / (2 * pow(vectorB.Magnitude(), 2)); double time2 = (-2 * dotProduct - sqrt(determinant)) / (2 * pow(vectorB.Magnitude(), 2)); bool timeValid1 = time1 >= 0 && time1 <= 1; bool timeValid2 = time2 >= 0 && time2 <= 1; // Check validity if (timeValid1 && timeValid2) { if (time1 <= time2) { collisionTime = time1 * dt; } else { collisionTime = time2 * dt; } } } // Collide particles if collision has occured if (collisionTime != -1) { double newMass = bodyA->GetMass() + bodyB->GetMass(); // Conservation of linear momentum // X double aXVelocity = bodyA->GetXVelocity(); double bXVelocity = bodyB->GetXVelocity(); double newXVelocity = ((bodyA->GetMass() * aXVelocity) + (bodyB->GetMass() * bXVelocity)) / (newMass); // Y double aYVelocity = bodyA->GetYVelocity(); double bYVelocity = bodyB->GetYVelocity(); double newYVelocity = ((bodyA->GetMass() * aYVelocity) + (bodyB->GetMass() * bYVelocity)) / (newMass); // Z double aZVelocity = bodyA->GetZVelocity(); double bZVelocity = bodyB->GetZVelocity(); double newZVelocity = ((bodyA->GetMass() * aZVelocity) + (bodyB->GetMass() * bZVelocity)) / (newMass); // Calculate new position // Use midpoint of the two "new positions" bodyA->Update(collisionTime); bodyB->Update(collisionTime); double newX = (bodyA->GetNextX() + bodyB->GetNextX()) / 2; double newY = (bodyA->GetNextY() + bodyB->GetNextY()) / 2; double newZ = (bodyA->GetNextZ() + bodyB->GetNextZ()) / 2; // Calculate new radius // TODO: Figure out way of calculating a new radius given constant density? // At the moment, use larger radius of the two bodies double newRadius; if (bodyA->GetRadius() >= bodyB->GetRadius()) { newRadius = bodyA->GetRadius(); } else { newRadius = bodyB->GetRadius(); } // Create a new (combined) body, and remove A and B; bodyList.Remove(bodyA->id); bodyList.Remove(bodyB->id); Body * newBody = new Body(newX, newY, newZ, newMass, newRadius, newXVelocity, newYVelocity, newZVelocity); newBody->Update(dt - collisionTime); bodyList.Append(newBody); } bodyB = bodyB->next; } bodyA = bodyA->next; } // Move each body to their new positions body = bodyList.GetHead(); while (body != NULL) { body->Step(); image.DrawBody(body->GetX(), body->GetY(), 255, 255, 255); body = body->next; } // Draw information on frame image.DrawText("SIMULATION", 10, 10, 255, 255, 255); image.DrawText("F: " + to_string(f), 10, 20, 255, 255, 255); image.DrawText("N: " + to_string(bodyList.GetLength()), 10, 30, 255, 255, 255); image.Save(); } video.Build("result_run.mp4", frames); // Create output.txt Output output("init/output.txt", width, height, 100); output.AddAllBodies(bodyList); output.Save(); return 0; } // No *valid* arguments supplied else { cout << "No valid arguments provided." << endl; cout << usageStatement << endl; return 1; } return 0; } <commit_msg>Removed FindFlag, replaced with regex validity check<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cmath> #include <ctime> #include <regex> #include "lib/font.h" #include "lib/body.h" #include "lib/image.h" #include "lib/video.h" #include "lib/output.h" #include "lib/misc.h" #include "lib/matrix.h" #include "lib/linkedlist.h" #include "lib/units.h" #include <pngwriter.h> using namespace std; int main(int argc, char * argv[]) { string usageStatement = "Usage: " + (string)argv[0] + " -c configfile.scfg (-g --generate (random|rotate) )|(-r --run framecount)"; // Need to make these "settable" by the user // Defaults int bodyCount = 200; int width = 640; int height = 480; // "run" settings double dt = DAY; int frames = 200; int framerate = 45; List bodyList = List(); Body * body; Body * bodyA; Body * bodyB; // Check command is valid using regex // ./sombrero -c filename.scfg -g random -r frames // -c (character).scfg (-g *characters*) | (-r *integer > 0*) regex validCommand("-c [\\w]+.scfg (((\\-g|\\-\\-generate) (random|rotate))|((\\-r|\\-\\-run) [1-9][0-9]*))"); string command = ""; for (int i = 1; i < argc; i++) { command += (string)argv[i]; if (i != argc - 1) { command += " "; } } cout << "command: (" << command << ")" << endl; if (!regex_match(command, validCommand)) { cout << "Not a valid command. See usage statement." << endl; cout << usageStatement << endl; return 1; } cout << "Valid." << endl; return 0; // No arguments supplied if (argc == 1) { cout << "No arguments supplied." << endl; cout << usageStatement << endl; return 1; } // Generate Body arrangement if (strcmp(argv[1], "-g") == 0 or strcmp(argv[1], "--generate") == 0) { if (argc >= 3) { // Generate random arrangement of bodies (+ rotation video) // i.e. create new bodyList if (strcmp(argv[2], "random") == 0) { for (int i = 0; i < bodyCount - 1; i++) { double r = Random(1e11, 1e11); double theta = Random(0, 2 * PI); double phi = Random(0, 2 * PI); double x = r * cos(theta) * cos(phi); double y = r * sin(theta); double z = r * cos(theta) * sin(phi); double mass = Random(1e23, 1e24); bodyList.Append(new Body(x, y, z, mass, Random(1e6, 9e6), 0, 0, 0)); } bodyList.Append(new Body(0.0, 0.0, 0.0, 2e30, 1e8, 0.0, 0.0, 0.0)); // Save bodies to output.txt Output output("init/output.txt", width, height, 100); output.AddAllBodies(bodyList); output.Save(); } // Generate rotate video around bodies // i.e. Load bodies from file else if (strcmp(argv[2], "rotate") == 0) { string filename = "init/output.txt"; if (argc == 4) { // Assume that the final argument is the filename filename = argv[3]; } if (FileExists(filename)) { LoadBodiesFromFile(filename.c_str(), bodyList); } else { cout << "./sombrero --generate rotate [filename]" << endl; cout << "When using rotate, must include valid filename: e.g. init/output.txt" << endl; return 1; } } // No *valid* options supplied else { cout << "Must supply valid generate argument: [random, rotate]" << endl; cout << usageStatement << endl; return 1; } } // No options supplied else { cout << "Must supply generate argument: [random, rotate]" << endl; cout << usageStatement << endl; return 1; } // Generate rotate video around bodies Video video = Video("images/", "image_", width, height, framerate); video.ClearImageFolder(); // Rotate bodies about the y-axis for (double angle = 0.0; angle < 360.0; angle ++) { string imageFileName = "images/image_" + PadWithZeroes(angle, 360) + ".png"; Image image = Image(imageFileName, width, height, 100); body = bodyList.GetHead(); while (body != NULL) { // Rotate body Vector p; p.Set(body->GetX(), body->GetY(), body->GetZ()); Vector t; t = p.RotateY(angle); t = t.RoundValues(); image.DrawBody(t.GetX(), t.GetY(), 255, 255, 255); body = body->next; } // Add details to image image.DrawText("ROTATION", 10, 10, 255, 255, 255); image.DrawText("A: " + to_string((int)angle), 10, 20, 255, 255, 255); image.DrawText("N: " + to_string(bodyList.GetLength()), 10, 30, 255, 255, 255); image.Save(); } // Build video from images video.Build("result.mp4", 360); return 0; } // Run simulation if (strcmp(argv[1], "-r") == 0 or strcmp(argv[1], "--run") == 0) { LoadBodiesFromFile("init/output.txt", bodyList); Video video = Video("images/", "image_", width, height, framerate); video.ClearImageFolder(); for (int f = 0; f < frames; f++) { // Reset force counter on each body body = bodyList.GetHead(); while (body != NULL) { body->ResetForce(); body = body->next; } // n-body Algorithm (optimised) bodyA = bodyList.GetHead(); bodyB = NULL; while (bodyA != NULL) { bodyB = bodyA->next; while (bodyB != NULL) { // Calculate distance double xDistance = bodyA->GetX() - bodyB->GetX(); double yDistance = bodyA->GetY() - bodyB->GetY(); double zDistance = bodyA->GetZ() - bodyB->GetZ(); double totalDistance = sqrt(pow(xDistance, 2) + pow(yDistance, 2) + pow(zDistance, 2)); // Calculate angles double phiAngle = atan2(zDistance, sqrt(pow(xDistance, 2) + pow(yDistance, 2))); double thetaAngle = atan2(yDistance, xDistance); // Calculate force double force = GR * ((bodyA->GetMass() * bodyB->GetMass()) / (pow(totalDistance, 2))); // Add forces to totals bodyA->AddForce(force, phiAngle, thetaAngle); bodyB->AddForce(-force, phiAngle, thetaAngle); // Advance pointer bodyB = bodyB->next; } bodyA = bodyA->next; } string imageFileName = "images/image_" + PadWithZeroes(f, frames) + ".png"; Image image = Image(imageFileName, width, height, 100); // Calculate next position for each body body = bodyList.GetHead(); while (body != NULL) { body->Update(dt); body = body->next; } // Collision Physics bodyA = bodyList.GetHead(); bodyB = NULL; while (bodyA != NULL) { bodyB = bodyA->next; while (bodyB != NULL) { double collisionTime = -1; // Set up position vectors Vector initialA; initialA.Set(bodyA->GetX(), bodyA->GetY(), bodyA->GetZ()); Vector finalA; finalA.Set(bodyA->GetNextX(), bodyA->GetNextY(), bodyA->GetNextZ()); Vector initialB; initialB.Set(bodyB->GetX(), bodyB->GetY(), bodyB->GetZ()); Vector finalB; finalB.Set(bodyB->GetNextX(), bodyB->GetNextY(), bodyB->GetNextZ()); // Check the two lines are not parallel Vector lineA = finalA.Subtract(initialA); Vector lineB = finalB.Subtract(initialB); if (lineA.DotProduct(lineB) != 0) { // Calculate collision times Vector vectorA = initialB.Subtract(initialA); Vector vectorB = (finalB.Subtract(finalA)).Add(initialA.Subtract(initialB)); double dotProduct = vectorA.DotProduct(vectorB); double radiiSum = bodyA->GetRadius() + bodyB->GetRadius(); double determinant = (4 * pow(dotProduct, 2)) - (4 * pow(vectorB.Magnitude(), 2) * (pow(vectorA.Magnitude(), 2) - pow(radiiSum, 2))); double time1 = (-2 * dotProduct + sqrt(determinant)) / (2 * pow(vectorB.Magnitude(), 2)); double time2 = (-2 * dotProduct - sqrt(determinant)) / (2 * pow(vectorB.Magnitude(), 2)); bool timeValid1 = time1 >= 0 && time1 <= 1; bool timeValid2 = time2 >= 0 && time2 <= 1; // Check validity if (timeValid1 && timeValid2) { if (time1 <= time2) { collisionTime = time1 * dt; } else { collisionTime = time2 * dt; } } } // Collide particles if collision has occured if (collisionTime != -1) { double newMass = bodyA->GetMass() + bodyB->GetMass(); // Conservation of linear momentum // X double aXVelocity = bodyA->GetXVelocity(); double bXVelocity = bodyB->GetXVelocity(); double newXVelocity = ((bodyA->GetMass() * aXVelocity) + (bodyB->GetMass() * bXVelocity)) / (newMass); // Y double aYVelocity = bodyA->GetYVelocity(); double bYVelocity = bodyB->GetYVelocity(); double newYVelocity = ((bodyA->GetMass() * aYVelocity) + (bodyB->GetMass() * bYVelocity)) / (newMass); // Z double aZVelocity = bodyA->GetZVelocity(); double bZVelocity = bodyB->GetZVelocity(); double newZVelocity = ((bodyA->GetMass() * aZVelocity) + (bodyB->GetMass() * bZVelocity)) / (newMass); // Calculate new position // Use midpoint of the two "new positions" bodyA->Update(collisionTime); bodyB->Update(collisionTime); double newX = (bodyA->GetNextX() + bodyB->GetNextX()) / 2; double newY = (bodyA->GetNextY() + bodyB->GetNextY()) / 2; double newZ = (bodyA->GetNextZ() + bodyB->GetNextZ()) / 2; // Calculate new radius // TODO: Figure out way of calculating a new radius given constant density? // At the moment, use larger radius of the two bodies double newRadius; if (bodyA->GetRadius() >= bodyB->GetRadius()) { newRadius = bodyA->GetRadius(); } else { newRadius = bodyB->GetRadius(); } // Create a new (combined) body, and remove A and B; bodyList.Remove(bodyA->id); bodyList.Remove(bodyB->id); Body * newBody = new Body(newX, newY, newZ, newMass, newRadius, newXVelocity, newYVelocity, newZVelocity); newBody->Update(dt - collisionTime); bodyList.Append(newBody); } bodyB = bodyB->next; } bodyA = bodyA->next; } // Move each body to their new positions body = bodyList.GetHead(); while (body != NULL) { body->Step(); image.DrawBody(body->GetX(), body->GetY(), 255, 255, 255); body = body->next; } // Draw information on frame image.DrawText("SIMULATION", 10, 10, 255, 255, 255); image.DrawText("F: " + to_string(f), 10, 20, 255, 255, 255); image.DrawText("N: " + to_string(bodyList.GetLength()), 10, 30, 255, 255, 255); image.Save(); } video.Build("result_run.mp4", frames); // Create output.txt Output output("init/output.txt", width, height, 100); output.AddAllBodies(bodyList); output.Save(); return 0; } // No *valid* arguments supplied else { cout << "No valid arguments provided." << endl; cout << usageStatement << endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "Simulation.h" #include "GridHelper.h" #include "Parameters.h" #include "PerformanceTracker.h" #include "pica/fieldSolver/YeeSolver.h" #include "pica/grid/Grid.h" #include "pica/grid/YeeGrid.h" #include "pica/math/Constants.h" #include "pica/math/Vectors.h" #include "pica/particles/Particle.h" #include "pica/threading/OpenMPHelper.h" #include "pica/utility/Utility.h" #include <memory> #include <stdexcept> using namespace pica; template<class Grid, class FieldSolver> void updateField(Grid& grid, FieldSolver& fieldSolver, double dt, PerformanceTracker& tracker) { tracker.start(PerformanceTracker::Stage_FieldSolver); fieldSolver.updateB(grid, dt / 2.0); fieldSolver.updateE(grid, dt); FieldBoundaryConditions<Grid>().apply(grid); fieldSolver.updateB(grid, dt / 2.0); tracker.finish(PerformanceTracker::Stage_FieldSolver); } template<class Grid, class FieldSolver> void runIteration(Grid& grid, FieldSolver& fieldSolver, double dt, PerformanceTracker& tracker) { updateField(grid, fieldSolver, dt, tracker); } template<class Position, class Real> Real getTimeStep(Position step) { Real sumInvSquares = 0; for (int d = 0; d < VectorDimensionHelper<Position>::dimension; d++) sumInvSquares += static_cast<Real>(1.0) / (step[d] * step[d]); return 0.5 / (Constants<Real>::c() * sqrt(sumInvSquares)); } template<Dimension dimension, class Particle, class ParticleArray> void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { typedef YeeGrid<dimension> Grid; typedef typename Grid::PositionType PositionType; typedef typename Grid::IndexType IndexType; typedef typename Grid::ValueType Real; PositionType minPosition; PositionType maxPosition = OnesHelper<dimension, Real>::get(); IndexType numCells; for (int d = 0; d < parameters.dimension; d++) numCells[d] = parameters.numCells[d]; PositionType step = (maxPosition - minPosition) / PositionType(numCells); std::auto_ptr<Grid> grid = createGrid<Grid>(minPosition, maxPosition, numCells); YeeSolver fieldSolver; Real timeStep = getTimeStep<PositionType, Real>(step); omp_set_num_threads(parameters.numThreads); for (int i = 0; i < parameters.numIterations; i++) runIteration(*grid, fieldSolver, timeStep, tracker); } template<Dimension dimension, class Particle> void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { switch (parameters.particleRepresentation) { case ParticleRepresentation_AoS: runSimulation<dimension, Particle, ParticleArray<Particle, ParticleRepresentation_AoS>::Type>(parameters, tracker); break; case ParticleRepresentation_SoA: runSimulation<dimension, Particle, ParticleArray<Particle, ParticleRepresentation_SoA>::Type>(parameters, tracker); break; default: throw std::invalid_argument("wrong value of particle representation"); } } void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { switch (parameters.dimension) { case 1: runSimulation<One, Particle1d>(parameters, tracker); break; case 2: runSimulation<Two, Particle2d>(parameters, tracker); break; case 3: runSimulation<Three, Particle3d>(parameters, tracker); break; default: throw std::invalid_argument("wrong value of dimension: " + toString(parameters.dimension)); } } <commit_msg>Add generation of particles to benchmark.<commit_after>#include "Simulation.h" #include "GridHelper.h" #include "Parameters.h" #include "PerformanceTracker.h" #include "pica/fieldSolver/YeeSolver.h" #include "pica/grid/Grid.h" #include "pica/grid/YeeGrid.h" #include "pica/math/Constants.h" #include "pica/math/Vectors.h" #include "pica/particles/Particle.h" #include "pica/particles/ParticleTraits.h" #include "pica/threading/OpenMPHelper.h" #include "pica/utility/Utility.h" #include <cstdlib> #include <limits> #include <memory> #include <stdexcept> using namespace pica; template<class Grid, class FieldSolver> void updateField(Grid& grid, FieldSolver& fieldSolver, double dt, PerformanceTracker& tracker) { tracker.start(PerformanceTracker::Stage_FieldSolver); fieldSolver.updateB(grid, dt / 2.0); fieldSolver.updateE(grid, dt); FieldBoundaryConditions<Grid>().apply(grid); fieldSolver.updateB(grid, dt / 2.0); tracker.finish(PerformanceTracker::Stage_FieldSolver); } template<class Grid, class FieldSolver> void runIteration(Grid& grid, FieldSolver& fieldSolver, double dt, PerformanceTracker& tracker) { updateField(grid, fieldSolver, dt, tracker); } template<class Position, class Real> Real getTimeStep(Position step) { Real sumInvSquares = 0; for (int d = 0; d < VectorDimensionHelper<Position>::dimension; d++) sumInvSquares += static_cast<Real>(1.0) / (step[d] * step[d]); return 0.5 / (Constants<Real>::c() * sqrt(sumInvSquares)); } double getNormal() { double result; do { double u1 = (double)rand() / (double)RAND_MAX; double u2 = (double)rand() / (double)RAND_MAX; result = std::sqrt(-2 * std::log(u1)) * std::cos(2 * constants::pi * u2); } while (!(result <= std::numeric_limits<double>::max() && result >= -std::numeric_limits<double>::max())); return result; } template<class Ensemble> void createParticles(const Parameters& parameters, typename Ensemble::PositionType minPosition, typename Ensemble::PositionType maxPosition, Ensemble& ensemble) { srand(0); typedef typename Ensemble::PositionType PositionType; typedef typename ParticleTraits<typename Ensemble::Particle>::MomentumType MomentumType; int numParticles = parameters.numCells.volume() * parameters.particlesPerCell; for (int i = 0; i < numParticles; i++) { typename Ensemble::Particle particle; particle.setMass(constants::electronMass); particle.setCharge(constants::electronCharge); particle.setFactor(1.0); PositionType position; for (int d = 0; d < VectorDimensionHelper<PositionType>::dimension; d++) position[d] = minPosition[d] + (maxPosition[d] - minPosition[d]) * (double)rand() / (double)RAND_MAX; particle.setPosition(position); // The standard deviation is sqrt(1/(2*alpha)), where alpha is // 3/2 * ((T/mc^2 + 1)^2 - 1)^(-1) double alpha = parameters.temperature / particle.getMass() / constants::c / constants::c + 1; alpha = 1.5 / (alpha * alpha - 1); double sigma = sqrt(0.5 / alpha) * particle.getMass() * constants::c; // Initial particle momentum is combination of given initial // momentum based on coords and random term in N(0, sigma) MomentumType momentum; for (int d = 0; d < VectorDimensionHelper<MomentumType>::dimension; d++) momentum[d] = getNormal() * sigma; particle.setMomentum(momentum); ensemble.add(particle); } } template<Dimension dimension, class Particle, class ParticleArray, class Ensemble> void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { typedef YeeGrid<dimension> Grid; typedef typename Grid::PositionType PositionType; typedef typename Grid::IndexType IndexType; typedef typename Grid::ValueType Real; PositionType minPosition; PositionType maxPosition = OnesHelper<dimension, Real>::get(); IndexType numCells; for (int d = 0; d < parameters.dimension; d++) numCells[d] = parameters.numCells[d]; PositionType step = (maxPosition - minPosition) / PositionType(numCells); std::auto_ptr<Grid> grid = createGrid<Grid>(minPosition, maxPosition, numCells); Ensemble ensemble(minPosition, maxPosition); createParticles(parameters, minPosition, maxPosition, ensemble); YeeSolver fieldSolver; Real timeStep = getTimeStep<PositionType, Real>(step); omp_set_num_threads(parameters.numThreads); for (int i = 0; i < parameters.numIterations; i++) runIteration(*grid, fieldSolver, timeStep, tracker); } template<Dimension dimension, class Particle, class ParticleArray> void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { switch (parameters.ensembleRepresentation) { case EnsembleRepresentation_Unordered: runSimulation<dimension, Particle, ParticleArray, Ensemble_<ParticleArray, EnsembleRepresentation_Unordered>::Type>(parameters, tracker); break; case EnsembleRepresentation_Ordered: runSimulation<dimension, Particle, ParticleArray, Ensemble_<ParticleArray, EnsembleRepresentation_Ordered>::Type>(parameters, tracker); break; default: throw std::invalid_argument("wrong value of ensemble representation"); } } template<Dimension dimension, class Particle> void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { switch (parameters.particleRepresentation) { case ParticleRepresentation_AoS: runSimulation<dimension, Particle, ParticleArray<Particle, ParticleRepresentation_AoS>::Type>(parameters, tracker); break; case ParticleRepresentation_SoA: runSimulation<dimension, Particle, ParticleArray<Particle, ParticleRepresentation_SoA>::Type>(parameters, tracker); break; default: throw std::invalid_argument("wrong value of particle representation"); } } void runSimulation(const Parameters& parameters, PerformanceTracker& tracker) { switch (parameters.dimension) { case 1: runSimulation<One, Particle1d>(parameters, tracker); break; case 2: runSimulation<Two, Particle2d>(parameters, tracker); break; case 3: runSimulation<Three, Particle3d>(parameters, tracker); break; default: throw std::invalid_argument("wrong value of dimension: " + toString(parameters.dimension)); } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/mainline_ue_trap.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mainline_ue_trap.H /// @brief Subroutines for the MC mainline ue address trap registers (MBUER*Q) /// // *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com> // *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_MAINLINE_UE_TRAP_H_ #define _MSS_MAINLINE_UE_TRAP_H_ #include <fapi2.H> #include <lib/mcbist/address.H> #include <generic/memory/lib/utils/scom.H> #include <lib/utils/find.H> #include <lib/ecc/ecc_traits.H> namespace mss { namespace ecc { namespace mainline_ue_trap { /// /// @brief Read MBS Mainline UE Address Trap (MBUER*Q) register /// @tparam T fapi2 Target Type - derived from i_target's type /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_target the fapi2 target of the mc /// @param[out] o_data the value of the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< fapi2::TargetType T, typename TT = eccTraits<T> > inline fapi2::ReturnCode read( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data ) { const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target); const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target); FAPI_TRY( mss::getScom(l_mcbist_target, (TT::MAINLINE_UE_REGS[l_port]), o_data) ); FAPI_INF("read: 0x%016lx", o_data); fapi_try_exit: return fapi2::current_err; } /// /// @brief Write MBS Mainline UE Address Trap (MBUER*Q) register /// @tparam T fapi2 Target Type - derived from i_target's type /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_target the fapi2 target of the mc /// @param[in] i_data the value to write to the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< fapi2::TargetType T, typename TT = eccTraits<T> > inline fapi2::ReturnCode write( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data ) { const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target); const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target); FAPI_TRY( mss::putScom(l_mcbist_target, (TT::MAINLINE_UE_REGS[l_port]), i_data) ); FAPI_INF("write: 0x%016lx", i_data); fapi_try_exit: return fapi2::current_err; } /// /// @brief set_address /// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA /// @tparam TT traits type defaults to eccTraits<T> /// @param[in, out] io_data the register value /// @param[in] i_address mcbist::address form of address field /// template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> > inline void set_address( fapi2::buffer<uint64_t>& io_data, const mcbist::address& i_address) { io_data.insertFromRight<TT::UE_ADDR_TRAP, TT::UE_ADDR_TRAP_LEN>(uint64_t(i_address)); FAPI_INF("set_address: 0x%016lx", uint64_t(i_address)); } /// /// @brief get_address /// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_data the register value /// @param[out] o_address mcbist::address form of address field /// template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> > inline void get_address( const fapi2::buffer<uint64_t>& i_data, mcbist::address& o_address ) { uint64_t l_addr = 0; i_data.extractToRight<TT::UE_ADDR_TRAP, TT::UE_ADDR_TRAP_LEN>(l_addr); o_address = mcbist::address(l_addr); FAPI_INF("get_address: 0x%016lx", uint64_t(l_addr)); } } // close namespace mainline_ue_trap } // close namespace ecc } // close namespace mss #endif <commit_msg>Move find API to share among memory controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/mainline_ue_trap.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mainline_ue_trap.H /// @brief Subroutines for the MC mainline ue address trap registers (MBUER*Q) /// // *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com> // *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_MAINLINE_UE_TRAP_H_ #define _MSS_MAINLINE_UE_TRAP_H_ #include <fapi2.H> #include <lib/mcbist/address.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/find.H> #include <lib/ecc/ecc_traits.H> namespace mss { namespace ecc { namespace mainline_ue_trap { /// /// @brief Read MBS Mainline UE Address Trap (MBUER*Q) register /// @tparam T fapi2 Target Type - derived from i_target's type /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_target the fapi2 target of the mc /// @param[out] o_data the value of the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< fapi2::TargetType T, typename TT = eccTraits<T> > inline fapi2::ReturnCode read( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data ) { const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target); const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target); FAPI_TRY( mss::getScom(l_mcbist_target, (TT::MAINLINE_UE_REGS[l_port]), o_data) ); FAPI_INF("read: 0x%016lx", o_data); fapi_try_exit: return fapi2::current_err; } /// /// @brief Write MBS Mainline UE Address Trap (MBUER*Q) register /// @tparam T fapi2 Target Type - derived from i_target's type /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_target the fapi2 target of the mc /// @param[in] i_data the value to write to the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< fapi2::TargetType T, typename TT = eccTraits<T> > inline fapi2::ReturnCode write( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data ) { const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target); const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target); FAPI_TRY( mss::putScom(l_mcbist_target, (TT::MAINLINE_UE_REGS[l_port]), i_data) ); FAPI_INF("write: 0x%016lx", i_data); fapi_try_exit: return fapi2::current_err; } /// /// @brief set_address /// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA /// @tparam TT traits type defaults to eccTraits<T> /// @param[in, out] io_data the register value /// @param[in] i_address mcbist::address form of address field /// template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> > inline void set_address( fapi2::buffer<uint64_t>& io_data, const mcbist::address& i_address) { io_data.insertFromRight<TT::UE_ADDR_TRAP, TT::UE_ADDR_TRAP_LEN>(uint64_t(i_address)); FAPI_INF("set_address: 0x%016lx", uint64_t(i_address)); } /// /// @brief get_address /// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA /// @tparam TT traits type defaults to eccTraits<T> /// @param[in] i_data the register value /// @param[out] o_address mcbist::address form of address field /// template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> > inline void get_address( const fapi2::buffer<uint64_t>& i_data, mcbist::address& o_address ) { uint64_t l_addr = 0; i_data.extractToRight<TT::UE_ADDR_TRAP, TT::UE_ADDR_TRAP_LEN>(l_addr); o_address = mcbist::address(l_addr); FAPI_INF("get_address: 0x%016lx", uint64_t(l_addr)); } } // close namespace mainline_ue_trap } // close namespace ecc } // close namespace mss #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_training.C /// @brief Train dram /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include "p9_mss_draminit_training.H" using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Train dram /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, const uint16_t i_special_training ) { fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training; FAPI_INF("Start draminit training"); uint8_t l_reset_disable = 0; FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) ); // Configure the CCS engine. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, false); mss::ccs::ue_disable(i_target, l_ccs_config, false); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true); // Hm. Centaur sets this up for the longest duration possible. Can we do better? mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0); #ifndef JIM_SAYS_TURN_OFF_ECC mss::ccs::disable_ecc(i_target, l_ccs_config); #endif FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // Clean out any previous calibration results, set bad-bits and configure the ranks. FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size()); for( auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program; // Setup a series of register probes which we'll see during the polling loop l_program.iv_probes = { // One block for each DP16 {p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0}, {p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0}, {p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0}, {p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0}, {p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1}, {p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1}, {p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1}, {p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1}, {p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2}, {p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2}, {p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2}, {p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2}, {p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3}, {p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3}, {p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3}, {p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3}, {p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4}, {p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4}, {p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4}, {p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4}, }; // Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF, // and we're supposed to poll for the done or timeout bit. But we don't want // to wait 0xFFFF cycles before we start polling - that's too long. So we put // in a best-guess of how long to wait. This, in a perfect world, would be the // time it takes one rank to train one training algorithm times the number of // ranks we're going to train. We fail-safe as worst-case we simply poll the // register too much - so we can tune this as we learn more. l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US; l_program.iv_poll.iv_initial_sim_delay = 200; l_program.iv_poll.iv_poll_count = 0xFFFF; // Returned from set_rank_pairs, it tells us how many rank pairs // we configured on this port. std::vector<uint64_t> l_pairs; #ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE // This isn't correct - shouldn't be setting static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000; FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) ); #endif FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) ); FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) ); // Disable port fails as it doesn't appear the MC handles initial cal timeouts // correctly (cal_length.) BRS, see conversation with Brad Michael FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) ); // The following registers must be configured to the correct operating environment: // Unclear, can probably be 0's for sim BRS // • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422 FAPI_TRY( mss::reset_seq_config0(p) ); FAPI_TRY( mss::reset_seq_rd_wr_data(p) ); FAPI_TRY( mss::reset_odt_config(p) ); // These are reset in phy_scominit // • Section 5.2.6.1 WC Configuration 0 Register on page 434 // • Section 5.2.6.2 WC Configuration 1 Register on page 436 // • Section 5.2.6.3 WC Configuration 2 Register on page 438 // Get our rank pairs. FAPI_TRY( mss::get_rank_pairs(p, l_pairs) ); // Setup the config register // // Grab the attribute which contains the information on what cal steps we should run // if the i_specal_training bits have not been specified. if (i_special_training == 0) { FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) ); } FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training); // Check to see if we're supposed to reset the delay values before starting training // don't reset if we're running special training - assumes there's a checkpoint which has valid state. if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0)) { FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) ); } FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size()); // For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it. // NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE // THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS. for (auto rp : l_pairs) { auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp); FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1); l_program.iv_instructions.push_back(l_inst); // We need to figure out how long to wait before we start polling. Each cal step has an expected // duration, so for each cal step which was enabled, we update the CCS program. FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) ); FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) ); // In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a // timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58) // for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register // should be polled to determine which calibration step failed. // If we got a cal timeout, or another CCS error just leave now. If we got success, check the error // bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY. FAPI_TRY( mss::ccs::execute(i_target, l_program, p) ); FAPI_TRY( mss::process_initial_cal_errors(p) ); } } fapi_try_exit: FAPI_INF("End draminit training"); return fapi2::current_err; } } <commit_msg>Change procedure include paths<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_training.C /// @brief Train dram /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <p9_mss_draminit_training.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Train dram /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, const uint16_t i_special_training ) { fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training; FAPI_INF("Start draminit training"); uint8_t l_reset_disable = 0; FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) ); // Configure the CCS engine. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, false); mss::ccs::ue_disable(i_target, l_ccs_config, false); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true); // Hm. Centaur sets this up for the longest duration possible. Can we do better? mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0); #ifndef JIM_SAYS_TURN_OFF_ECC mss::ccs::disable_ecc(i_target, l_ccs_config); #endif FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // Clean out any previous calibration results, set bad-bits and configure the ranks. FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size()); for( auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program; // Setup a series of register probes which we'll see during the polling loop l_program.iv_probes = { // One block for each DP16 {p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0}, {p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0}, {p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0}, {p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0}, {p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1}, {p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1}, {p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1}, {p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1}, {p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2}, {p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2}, {p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2}, {p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2}, {p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3}, {p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3}, {p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3}, {p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3}, {p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4}, {p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4}, {p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4}, {p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4}, }; // Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF, // and we're supposed to poll for the done or timeout bit. But we don't want // to wait 0xFFFF cycles before we start polling - that's too long. So we put // in a best-guess of how long to wait. This, in a perfect world, would be the // time it takes one rank to train one training algorithm times the number of // ranks we're going to train. We fail-safe as worst-case we simply poll the // register too much - so we can tune this as we learn more. l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US; l_program.iv_poll.iv_initial_sim_delay = 200; l_program.iv_poll.iv_poll_count = 0xFFFF; // Returned from set_rank_pairs, it tells us how many rank pairs // we configured on this port. std::vector<uint64_t> l_pairs; #ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE // This isn't correct - shouldn't be setting static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000; FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) ); #endif FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) ); FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) ); // Disable port fails as it doesn't appear the MC handles initial cal timeouts // correctly (cal_length.) BRS, see conversation with Brad Michael FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) ); // The following registers must be configured to the correct operating environment: // Unclear, can probably be 0's for sim BRS // • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422 FAPI_TRY( mss::reset_seq_config0(p) ); FAPI_TRY( mss::reset_seq_rd_wr_data(p) ); FAPI_TRY( mss::reset_odt_config(p) ); // These are reset in phy_scominit // • Section 5.2.6.1 WC Configuration 0 Register on page 434 // • Section 5.2.6.2 WC Configuration 1 Register on page 436 // • Section 5.2.6.3 WC Configuration 2 Register on page 438 // Get our rank pairs. FAPI_TRY( mss::get_rank_pairs(p, l_pairs) ); // Setup the config register // // Grab the attribute which contains the information on what cal steps we should run // if the i_specal_training bits have not been specified. if (i_special_training == 0) { FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) ); } FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training); // Check to see if we're supposed to reset the delay values before starting training // don't reset if we're running special training - assumes there's a checkpoint which has valid state. if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0)) { FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) ); } FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size()); // For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it. // NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE // THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS. for (auto rp : l_pairs) { auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp); FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1); l_program.iv_instructions.push_back(l_inst); // We need to figure out how long to wait before we start polling. Each cal step has an expected // duration, so for each cal step which was enabled, we update the CCS program. FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) ); FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) ); // In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a // timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58) // for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register // should be polled to determine which calibration step failed. // If we got a cal timeout, or another CCS error just leave now. If we got success, check the error // bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY. FAPI_TRY( mss::ccs::execute(i_target, l_program, p) ); FAPI_TRY( mss::process_initial_cal_errors(p) ); } } fapi_try_exit: FAPI_INF("End draminit training"); return fapi2::current_err; } } <|endoftext|>
<commit_before>#include "elm/encoding/encoding.h" #include "gtest/gtest.h" <commit_msg>remove unused test file<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_training.C /// @brief Train dram /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include "p9_mss_draminit_training.H" using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Train dram /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { fapi2::buffer<uint16_t> l_cal_steps_enabled; FAPI_INF("Start draminit training"); uint8_t l_reset_disable = 0; FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) ); // Configure the CCS engine. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, false); mss::ccs::ue_disable(i_target, l_ccs_config, false); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true); // Hm. Centaur sets this up for the longest duration possible. Can we do better? mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0); #ifndef JIM_SAYS_TURN_OFF_ECC mss::ccs::disable_ecc(i_target, l_ccs_config); #endif FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // Clean out any previous calibration results, set bad-bits and configure the ranks. FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size()); for( auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::ccs::program<TARGET_TYPE_MCBIST> l_program; // Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF, // and we're supposed to poll for the done or timeout bit. But we don't want // to wait 0xFFFF cycles before we start polling - that's too long. So we put // in a best-guess of how long to wait. This, in a perfect world, would be the // time it takes one rank to train one training algorithm times the number of // ranks we're going to train. We fail-safe as worst-case we simply poll the // register too much - so we can tune this as we learn more. l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US; l_program.iv_poll.iv_initial_sim_delay = 200; l_program.iv_poll.iv_poll_count = 0xFFFF; // Returned from set_rank_pairs, it tells us how many rank pairs // we configured on this port. std::vector<uint64_t> l_pairs; #ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE // This isn't correct - shouldn't be setting static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000; FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) ); #endif FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) ); FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) ); // Hit the reset button for wr_lvl values. These won't reset until the next run of wr_lvl FAPI_TRY( mss::reset_wc_config0(p) ); FAPI_TRY( mss::reset_wc_config1(p) ); FAPI_TRY( mss::reset_wc_config2(p) ); FAPI_TRY( mss::reset_wc_rtt_wr_swap_enable(p) ); // The following registers must be configured to the correct operating environment: // Unclear, can probably be 0's for sim BRS // • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422 FAPI_TRY( mss::reset_seq_config0(p) ); FAPI_TRY( mss::reset_seq_rd_wr_data(p) ); FAPI_TRY( mss::reset_odt_config(p) ); // These are reset in phy_scominit // • Section 5.2.6.1 WC Configuration 0 Register on page 434 // • Section 5.2.6.2 WC Configuration 1 Register on page 436 // • Section 5.2.6.3 WC Configuration 2 Register on page 438 // Get our rank pairs. FAPI_TRY( mss::get_rank_pairs(p, l_pairs) ); // Setup the config register // // Grab the attribute which contains the information on what cal steps we should run FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) ); // Check to see if we're supposed to reset the delay values before starting training if (l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) { FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) ); } FAPI_TRY( mss::dump_cal_registers(p) ); FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size()); // For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it. // NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE // THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS. for (auto rp : l_pairs) { auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp); FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1); l_program.iv_instructions.push_back(l_inst); // We need to figure out how long to wait before we start polling. Each cal step has an expected // duration, so for each cal step which was enabled, we update the CCS program. FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) ); FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) ); // In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a // timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58) // for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register // should be polled to determine which calibration step failed. // If we got a cal timeout, or another CCS error just leave now. If we got success, check the error // bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY. FAPI_TRY( mss::ccs::execute(i_target, l_program, p) ); FAPI_TRY( mss::process_initial_cal_errors(p) ); } } fapi_try_exit: FAPI_INF("End draminit training"); return fapi2::current_err; } } <commit_msg>Change polling to include probes, add granular training controls<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_training.C /// @brief Train dram /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include "p9_mss_draminit_training.H" using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; extern "C" { /// /// @brief Train dram /// @param[in] i_target, the McBIST of the ports of the dram you're training /// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, const uint16_t i_special_training ) { fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training; FAPI_INF("Start draminit training"); uint8_t l_reset_disable = 0; FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) ); // Configure the CCS engine. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, false); mss::ccs::ue_disable(i_target, l_ccs_config, false); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true); // Hm. Centaur sets this up for the longest duration possible. Can we do better? mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0); #ifndef JIM_SAYS_TURN_OFF_ECC mss::ccs::disable_ecc(i_target, l_ccs_config); #endif FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // Clean out any previous calibration results, set bad-bits and configure the ranks. FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size()); for( auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program; // Setup a series of register probes which we'll see during the polling loop l_program.iv_probes = { // One block for each DP16 {p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0}, {p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0}, {p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0}, {p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0}, {p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1}, {p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1}, {p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1}, {p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1}, {p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2}, {p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2}, {p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2}, {p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2}, {p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3}, {p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3}, {p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3}, {p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3}, {p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4}, {p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4}, {p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4}, {p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4}, }; // Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF, // and we're supposed to poll for the done or timeout bit. But we don't want // to wait 0xFFFF cycles before we start polling - that's too long. So we put // in a best-guess of how long to wait. This, in a perfect world, would be the // time it takes one rank to train one training algorithm times the number of // ranks we're going to train. We fail-safe as worst-case we simply poll the // register too much - so we can tune this as we learn more. l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US; l_program.iv_poll.iv_initial_sim_delay = 200; l_program.iv_poll.iv_poll_count = 0xFFFF; // Returned from set_rank_pairs, it tells us how many rank pairs // we configured on this port. std::vector<uint64_t> l_pairs; #ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE // This isn't correct - shouldn't be setting static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000; FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) ); #endif FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) ); FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) ); // Hit the reset button for wr_lvl values. These won't reset until the next run of wr_lvl FAPI_TRY( mss::reset_wc_config0(p) ); FAPI_TRY( mss::reset_wc_config1(p) ); FAPI_TRY( mss::reset_wc_config2(p) ); FAPI_TRY( mss::reset_wc_rtt_wr_swap_enable(p) ); // The following registers must be configured to the correct operating environment: // Unclear, can probably be 0's for sim BRS // • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422 FAPI_TRY( mss::reset_seq_config0(p) ); FAPI_TRY( mss::reset_seq_rd_wr_data(p) ); FAPI_TRY( mss::reset_odt_config(p) ); // These are reset in phy_scominit // • Section 5.2.6.1 WC Configuration 0 Register on page 434 // • Section 5.2.6.2 WC Configuration 1 Register on page 436 // • Section 5.2.6.3 WC Configuration 2 Register on page 438 // Get our rank pairs. FAPI_TRY( mss::get_rank_pairs(p, l_pairs) ); // Setup the config register // // Grab the attribute which contains the information on what cal steps we should run // if the i_specal_training bits have not been specified. if (i_special_training == 0) { FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) ); } FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training); // Check to see if we're supposed to reset the delay values before starting training // don't reset if we're running special training - assumes there's a checkpoint which has valid state. if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0)) { FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) ); } FAPI_TRY( mss::dump_cal_registers(p) ); FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size()); // For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it. // NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE // THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS. for (auto rp : l_pairs) { auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp); FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1); l_program.iv_instructions.push_back(l_inst); // We need to figure out how long to wait before we start polling. Each cal step has an expected // duration, so for each cal step which was enabled, we update the CCS program. FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) ); FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) ); // In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a // timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58) // for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register // should be polled to determine which calibration step failed. // If we got a cal timeout, or another CCS error just leave now. If we got success, check the error // bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY. FAPI_TRY( mss::ccs::execute(i_target, l_program, p) ); FAPI_TRY( mss::process_initial_cal_errors(p) ); } } fapi_try_exit: FAPI_INF("End draminit training"); return fapi2::current_err; } } <|endoftext|>
<commit_before>#include <vector> #include <queue> #include <climits> #include <iostream> #include <tuple> using namespace std; typedef pair<int, int> edge; auto prim(vector<vector<edge>> &g) { size_t n = g.size(); vector<bool> used(n); vector<int> pred(n, -1); vector<int> prio(n, INT_MAX); prio[0] = 0; priority_queue<edge, vector<edge>, greater<edge>> q; q.push({prio[0], 0}); long long tree_weight = 0; while (!q.empty()) { auto[w, u] = q.top(); q.pop(); if (used[u]) continue; used[u] = true; tree_weight += w; for (auto[v, weight] : g[u]) { if (!used[v] && prio[v] > weight) { prio[v] = weight; pred[v] = u; q.push({weight, v}); } } } return make_tuple(tree_weight, pred); } int main() { vector<vector<edge>> g(3); g[0].push_back({1, 10}); g[1].push_back({0, 10}); g[1].push_back({2, 10}); g[2].push_back({1, 10}); g[2].push_back({0, 5}); g[0].push_back({2, 5}); auto[len, pred] = prim(g); cout << len << endl; } <commit_msg>update<commit_after>#include <vector> #include <queue> #include <climits> #include <iostream> #include <tuple> using namespace std; typedef pair<int, int> edge; auto prim(vector<vector<edge>> &g) { size_t n = g.size(); vector<bool> used(n); vector<int> pred(n, -1); vector<int> prio(n, INT_MAX); prio[0] = 0; priority_queue<edge, vector<edge>, greater<edge>> q; q.push({prio[0], 0}); long long tree_weight = 0; while (!q.empty()) { auto[w, u] = q.top(); q.pop(); if (used[u]) continue; used[u] = true; tree_weight += w; for (auto[v, weight] : g[u]) { if (!used[v] && prio[v] > weight) { prio[v] = weight; pred[v] = u; q.push({weight, v}); } } } return make_tuple(tree_weight, pred); } int main() { vector<vector<edge>> g(3); g[0].push_back({1, 10}); g[1].push_back({0, 10}); g[1].push_back({2, 10}); g[2].push_back({1, 10}); g[2].push_back({0, 5}); g[0].push_back({2, 5}); auto[tree_weight, pred] = prim(g); cout << tree_weight << endl; } <|endoftext|>
<commit_before>// tImageTIFF.cpp // // This knows how to load TIFFs. It knows the details of the tiff file format and loads the data into multiple tPixel // arrays, one for each frame (in a TIFF thay are called pages). These arrays may be 'stolen' by tPictures. // // Copyright (c) 2020 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <Foundation/tStandard.h> #include <Foundation/tString.h> #include <System/tFile.h> #include "Image/tImageTIFF.h" #include "LibTIFF/include/tiff.h" #include "LibTIFF/include/tiffio.h" #include "LibTIFF/include/tiffvers.h" using namespace tSystem; namespace tImage { bool tImageTIFF::Load(const tString& tiffFile) { Clear(); if (tSystem::tGetFileType(tiffFile) != tSystem::tFileType::TIFF) return false; if (!tFileExists(tiffFile)) return false; TIFF* tiff = TIFFOpen(tiffFile.Chars(), "r"); if (!tiff) return false; // Create all frames. do { int width = 0; int height = 0; TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height); if ((width <= 0) || (height <= 0)) break; int numPixels = width*height; uint32* pixels = (uint32*)_TIFFmalloc(numPixels * sizeof(uint32)); int successCode = TIFFReadRGBAImage(tiff, width, height, pixels, 0); if (!successCode) { _TIFFfree(pixels); break; } Frame* frame = new Frame; frame->Width = width; frame->Height = height; frame->Pixels = new tPixel[width*height]; frame->SrcPixelFormat = tPixelFormat::B8G8R8A8; for (int p = 0; p < width*height; p++) frame->Pixels[p] = pixels[p]; /* uint32& TiffPixel = raster[y*width+x]; // read the current pixel of the TIF Vec4b& pixel = image.at<Vec4b>(Point(y, x)); // read the current pixel of the matrix pixel[0] = TIFFGetB(TiffPixel); // Set the pixel values as BGRA pixel[1] = TIFFGetG(TiffPixel); pixel[2] = TIFFGetR(TiffPixel); pixel[3] = TIFFGetA(TiffPixel); */ _TIFFfree(pixels); Frames.Append(frame); } while (TIFFReadDirectory(tiff)); TIFFClose(tiff); // close the tif file return true; } } <commit_msg>Fixed issue with tiff loading not setting pixel format.<commit_after>// tImageTIFF.cpp // // This knows how to load TIFFs. It knows the details of the tiff file format and loads the data into multiple tPixel // arrays, one for each frame (in a TIFF thay are called pages). These arrays may be 'stolen' by tPictures. // // Copyright (c) 2020 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <Foundation/tStandard.h> #include <Foundation/tString.h> #include <System/tFile.h> #include "Image/tImageTIFF.h" #include "LibTIFF/include/tiff.h" #include "LibTIFF/include/tiffio.h" #include "LibTIFF/include/tiffvers.h" using namespace tSystem; namespace tImage { bool tImageTIFF::Load(const tString& tiffFile) { Clear(); if (tSystem::tGetFileType(tiffFile) != tSystem::tFileType::TIFF) return false; if (!tFileExists(tiffFile)) return false; TIFF* tiff = TIFFOpen(tiffFile.Chars(), "r"); if (!tiff) return false; // Create all frames. do { int width = 0; int height = 0; TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height); if ((width <= 0) || (height <= 0)) break; int numPixels = width*height; uint32* pixels = (uint32*)_TIFFmalloc(numPixels * sizeof(uint32)); int successCode = TIFFReadRGBAImage(tiff, width, height, pixels, 0); if (!successCode) { _TIFFfree(pixels); break; } Frame* frame = new Frame; frame->Width = width; frame->Height = height; frame->Pixels = new tPixel[width*height]; frame->SrcPixelFormat = tPixelFormat::R8G8B8A8; for (int p = 0; p < width*height; p++) frame->Pixels[p] = pixels[p]; _TIFFfree(pixels); Frames.Append(frame); } while (TIFFReadDirectory(tiff)); TIFFClose(tiff); if (Frames.GetNumItems() == 0) return false; SrcPixelFormat = tPixelFormat::R8G8B8A8; return true; } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //Ocl #include "mitkOclFilter.h" #include "mitkOclUtils.h" #include "mitkOpenCLActivator.h" //Mitk #include <mitkLogMacros.h> #include <mitkConfig.h> //usService #include "usServiceReference.h" #include <usServiceRegistration.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usModule.h> #include <usModuleResource.h> #include <usModuleResourceStream.h> mitk::OclFilter::OclFilter() : m_ClCompilerFlags(""), m_ClProgram(nullptr), m_CommandQue(nullptr), m_FilterID("mitkOclFilter"), m_Preambel(" "), m_Initialized(false) { } mitk::OclFilter::OclFilter(const char* filename) : m_ClCompilerFlags(""), m_ClProgram(nullptr), m_CommandQue(nullptr), m_FilterID(filename), m_Preambel(" "), m_Initialized(false) { m_ClFiles.push_back(filename); } mitk::OclFilter::~OclFilter() { MITK_DEBUG << "OclFilter Destructor"; // release program if (m_ClProgram) { us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); // remove program from storage resources->RemoveProgram(m_FilterID); } } bool mitk::OclFilter::ExecuteKernel( cl_kernel kernel, unsigned int workSizeDim ) { cl_int clErr = 0; clErr = clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim, nullptr, this->m_GlobalWorkSize, m_LocalWorkSize, 0, nullptr, nullptr); CHECK_OCL_ERR( clErr ); return ( clErr == CL_SUCCESS ); } bool mitk::OclFilter::ExecuteKernelChunks( cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim ) { size_t offset[3] ={0, 0, 0}; cl_int clErr = 0; if(workSizeDim == 2) { for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0]) { for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1]) { clErr |= clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim, offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr); } } } else if(workSizeDim == 3) { for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0]) { for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1]) { for(offset[2] = 0; offset[2] < m_GlobalWorkSize[2]; offset[2] += chunksDim[2]) { clErr |= clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim, offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr); } } } } CHECK_OCL_ERR(clErr); return ( clErr == CL_SUCCESS ); } bool mitk::OclFilter::Initialize() { us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); m_CommandQue = resources->GetCommandQueue(); cl_int clErr = 0; m_Initialized = CHECK_OCL_ERR(clErr); if ( m_ClFiles.empty()) { MITK_ERROR<<"No OpenCL Source FILE specified"; return false; } if (m_ClProgram == nullptr) { try { this->m_ClProgram = resources->GetProgram( this->m_FilterID ); } catch(const mitk::Exception& e) { MITK_INFO << "Program not stored in resource manager, compiling. " << e; this->CompileSource(); } } return m_Initialized; } void mitk::OclFilter::LoadSourceFiles(CStringList &sourceCode, ClSizeList &sourceCodeSize) { for( CStringList::iterator it = m_ClFiles.begin(); it != m_ClFiles.end(); ++it ) { MITK_DEBUG << "Load file :" << *it; us::ModuleResource mdr = GetModule()->GetResource(*it); if( !mdr.IsValid() ) MITK_WARN << "Could not load resource: " << mdr.GetName() << " is invalid!"; us::ModuleResourceStream rss(mdr); // read resource file to a string std::istreambuf_iterator<char> eos; std::string source(std::istreambuf_iterator<char>(rss), eos); // add preambel and build up string to compile std::string src(m_Preambel); src.append("\n"); src.append(source); // allocate new char buffer char* tmp = new char[src.size() + 1]; strcpy(tmp,src.c_str()); // add source to list sourceCode.push_back((const char*)tmp); sourceCodeSize.push_back(src.size()); } } void mitk::OclFilter::CompileSource() { // helper variable int clErr = 0; CStringList sourceCode; ClSizeList sourceCodeSize; if (m_ClFiles.empty()) { MITK_ERROR("ocl.filter") << "No shader source file was set"; return; } //get a valid opencl context us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); cl_context gpuContext = resources->GetContext(); // load the program source from file LoadSourceFiles(sourceCode, sourceCodeSize); if ( !sourceCode.empty() ) { // create program from all files in the file list m_ClProgram = clCreateProgramWithSource(gpuContext, sourceCode.size(), &sourceCode[0], &sourceCodeSize[0], &clErr); CHECK_OCL_ERR(clErr); // build the source code MITK_DEBUG << "Building Program Source"; std::string compilerOptions = ""; compilerOptions.append(m_ClCompilerFlags); MITK_DEBUG("ocl.filter") << "cl compiler flags: " << compilerOptions.c_str(); clErr = clBuildProgram(m_ClProgram, 0, nullptr, compilerOptions.c_str(), nullptr, nullptr); CHECK_OCL_ERR(clErr); // if OpenCL Source build failed if (clErr != CL_SUCCESS) { MITK_ERROR("ocl.filter") << "Failed to build source"; oclLogBuildInfo(m_ClProgram, resources->GetCurrentDevice() ); oclLogBinary(m_ClProgram, resources->GetCurrentDevice() ); m_Initialized = false; } // store the succesfully build program into the program storage provided by the resource service resources->InsertProgram(m_ClProgram, m_FilterID, true); // free the char buffers with the source code for( CStringList::iterator it = sourceCode.begin(); it != sourceCode.end(); ++it ) { delete[] *it; } } else { MITK_ERROR("ocl.filter") << "Could not load from source"; m_Initialized = false; } } void mitk::OclFilter::SetWorkingSize(unsigned int locx, unsigned int dimx, unsigned int locy, unsigned int dimy, unsigned int locz, unsigned int dimz) { // set the local work size this->m_LocalWorkSize[0] = locx; this->m_LocalWorkSize[1] = locy; this->m_LocalWorkSize[2] = locz; this->m_GlobalWorkSize[0] = dimx; this->m_GlobalWorkSize[1] = dimy; this->m_GlobalWorkSize[2] = dimz; // estimate the global work size this->m_GlobalWorkSize[0] = iDivUp( dimx, this->m_LocalWorkSize[0]) * this->m_LocalWorkSize[0]; if ( dimy > 1) this->m_GlobalWorkSize[1] = iDivUp( dimy, this->m_LocalWorkSize[1]) * this->m_LocalWorkSize[1]; if( dimz > 1 ) this->m_GlobalWorkSize[2] = iDivUp( dimz, this->m_LocalWorkSize[2]) * this->m_LocalWorkSize[2]; } void mitk::OclFilter::SetSourcePreambel(const char* preambel) { this->m_Preambel = preambel; } void mitk::OclFilter::AddSourceFile(const char* filename) { m_ClFiles.push_back(filename); } void mitk::OclFilter::SetCompilerFlags(const char* flags) { m_ClCompilerFlags = flags; } bool mitk::OclFilter::IsInitialized() { return m_Initialized; } <commit_msg>the chunked openCL execution waits for 16 chunks to finish until it queues the next ones, so that the system gets some time to check whether the GPU still responds<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //Ocl #include "mitkOclFilter.h" #include "mitkOclUtils.h" #include "mitkOpenCLActivator.h" //Mitk #include <mitkLogMacros.h> #include <mitkConfig.h> //usService #include "usServiceReference.h" #include <usServiceRegistration.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usModule.h> #include <usModuleResource.h> #include <usModuleResourceStream.h> mitk::OclFilter::OclFilter() : m_ClCompilerFlags(""), m_ClProgram(nullptr), m_CommandQue(nullptr), m_FilterID("mitkOclFilter"), m_Preambel(" "), m_Initialized(false) { } mitk::OclFilter::OclFilter(const char* filename) : m_ClCompilerFlags(""), m_ClProgram(nullptr), m_CommandQue(nullptr), m_FilterID(filename), m_Preambel(" "), m_Initialized(false) { m_ClFiles.push_back(filename); } mitk::OclFilter::~OclFilter() { MITK_DEBUG << "OclFilter Destructor"; // release program if (m_ClProgram) { us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); // remove program from storage resources->RemoveProgram(m_FilterID); } } bool mitk::OclFilter::ExecuteKernel( cl_kernel kernel, unsigned int workSizeDim ) { cl_int clErr = 0; clErr = clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim, nullptr, this->m_GlobalWorkSize, m_LocalWorkSize, 0, nullptr, nullptr); CHECK_OCL_ERR( clErr ); return ( clErr == CL_SUCCESS ); } bool mitk::OclFilter::ExecuteKernelChunks( cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim ) { size_t offset[3] ={0, 0, 0}; cl_int clErr = 0; unsigned int currentChunk = 0; cl_event* waitFor = new cl_event[16]; if(workSizeDim == 2) { for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0]) { for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1]) { if (currentChunk % 16 == 0 && currentChunk != 0) { clWaitForEvents(16, &waitFor[0]); clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim, offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[0]); } else { clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim, offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[currentChunk%16]); } currentChunk++; //clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim, // offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr); } } } else if(workSizeDim == 3) { for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0]) { for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1]) { for(offset[2] = 0; offset[2] < m_GlobalWorkSize[2]; offset[2] += chunksDim[2]) { clErr |= clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim, offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr); } } } } CHECK_OCL_ERR(clErr); return ( clErr == CL_SUCCESS ); } bool mitk::OclFilter::Initialize() { us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); m_CommandQue = resources->GetCommandQueue(); cl_int clErr = 0; m_Initialized = CHECK_OCL_ERR(clErr); if ( m_ClFiles.empty()) { MITK_ERROR<<"No OpenCL Source FILE specified"; return false; } if (m_ClProgram == nullptr) { try { this->m_ClProgram = resources->GetProgram( this->m_FilterID ); } catch(const mitk::Exception& e) { MITK_INFO << "Program not stored in resource manager, compiling. " << e; this->CompileSource(); } } return m_Initialized; } void mitk::OclFilter::LoadSourceFiles(CStringList &sourceCode, ClSizeList &sourceCodeSize) { for( CStringList::iterator it = m_ClFiles.begin(); it != m_ClFiles.end(); ++it ) { MITK_DEBUG << "Load file :" << *it; us::ModuleResource mdr = GetModule()->GetResource(*it); if( !mdr.IsValid() ) MITK_WARN << "Could not load resource: " << mdr.GetName() << " is invalid!"; us::ModuleResourceStream rss(mdr); // read resource file to a string std::istreambuf_iterator<char> eos; std::string source(std::istreambuf_iterator<char>(rss), eos); // add preambel and build up string to compile std::string src(m_Preambel); src.append("\n"); src.append(source); // allocate new char buffer char* tmp = new char[src.size() + 1]; strcpy(tmp,src.c_str()); // add source to list sourceCode.push_back((const char*)tmp); sourceCodeSize.push_back(src.size()); } } void mitk::OclFilter::CompileSource() { // helper variable int clErr = 0; CStringList sourceCode; ClSizeList sourceCodeSize; if (m_ClFiles.empty()) { MITK_ERROR("ocl.filter") << "No shader source file was set"; return; } //get a valid opencl context us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); cl_context gpuContext = resources->GetContext(); // load the program source from file LoadSourceFiles(sourceCode, sourceCodeSize); if ( !sourceCode.empty() ) { // create program from all files in the file list m_ClProgram = clCreateProgramWithSource(gpuContext, sourceCode.size(), &sourceCode[0], &sourceCodeSize[0], &clErr); CHECK_OCL_ERR(clErr); // build the source code MITK_DEBUG << "Building Program Source"; std::string compilerOptions = ""; compilerOptions.append(m_ClCompilerFlags); MITK_DEBUG("ocl.filter") << "cl compiler flags: " << compilerOptions.c_str(); clErr = clBuildProgram(m_ClProgram, 0, nullptr, compilerOptions.c_str(), nullptr, nullptr); CHECK_OCL_ERR(clErr); // if OpenCL Source build failed if (clErr != CL_SUCCESS) { MITK_ERROR("ocl.filter") << "Failed to build source"; oclLogBuildInfo(m_ClProgram, resources->GetCurrentDevice() ); oclLogBinary(m_ClProgram, resources->GetCurrentDevice() ); m_Initialized = false; } // store the succesfully build program into the program storage provided by the resource service resources->InsertProgram(m_ClProgram, m_FilterID, true); // free the char buffers with the source code for( CStringList::iterator it = sourceCode.begin(); it != sourceCode.end(); ++it ) { delete[] *it; } } else { MITK_ERROR("ocl.filter") << "Could not load from source"; m_Initialized = false; } } void mitk::OclFilter::SetWorkingSize(unsigned int locx, unsigned int dimx, unsigned int locy, unsigned int dimy, unsigned int locz, unsigned int dimz) { // set the local work size this->m_LocalWorkSize[0] = locx; this->m_LocalWorkSize[1] = locy; this->m_LocalWorkSize[2] = locz; this->m_GlobalWorkSize[0] = dimx; this->m_GlobalWorkSize[1] = dimy; this->m_GlobalWorkSize[2] = dimz; // estimate the global work size this->m_GlobalWorkSize[0] = iDivUp( dimx, this->m_LocalWorkSize[0]) * this->m_LocalWorkSize[0]; if ( dimy > 1) this->m_GlobalWorkSize[1] = iDivUp( dimy, this->m_LocalWorkSize[1]) * this->m_LocalWorkSize[1]; if( dimz > 1 ) this->m_GlobalWorkSize[2] = iDivUp( dimz, this->m_LocalWorkSize[2]) * this->m_LocalWorkSize[2]; } void mitk::OclFilter::SetSourcePreambel(const char* preambel) { this->m_Preambel = preambel; } void mitk::OclFilter::AddSourceFile(const char* filename) { m_ClFiles.push_back(filename); } void mitk::OclFilter::SetCompilerFlags(const char* flags) { m_ClCompilerFlags = flags; } bool mitk::OclFilter::IsInitialized() { return m_Initialized; } <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <algorithm> #include <cstdint> #include <codecvt> #include <locale> #include <cstring> // Types using RC_Pointer = void*; using RC_Size = size_t; using RC_UnicodeChar = char16_t; // Constants const int PATH_MAXIMUM_LENGTH = 260; // Enumerations enum class ProcessAccess { Read, Write, Full }; enum class SectionProtection { NoAccess = 0, Read = 1, Write = 2, Execute = 4, Guard = 8 }; inline SectionProtection operator|(SectionProtection lhs, SectionProtection rhs) { using T = std::underlying_type_t<SectionProtection>; return static_cast<SectionProtection>(static_cast<T>(lhs) | static_cast<T>(rhs)); } inline SectionProtection& operator|=(SectionProtection& lhs, SectionProtection rhs) { using T = std::underlying_type_t<SectionProtection>; lhs = static_cast<SectionProtection>(static_cast<T>(lhs) | static_cast<T>(rhs)); return lhs; } enum class SectionType { Unknown, Private, Mapped, Image }; enum class SectionCategory { Unknown, CODE, DATA, HEAP }; enum class ControlRemoteProcessAction { Suspend, Resume, Terminate }; enum class DebugContinueStatus { Handled, NotHandled }; enum class HardwareBreakpointRegister { InvalidRegister, Dr0, Dr1, Dr2, Dr3 }; enum class HardwareBreakpointTrigger { Execute, Access, Write, }; enum class HardwareBreakpointSize { Size1 = 1, Size2 = 2, Size4 = 4, Size8 = 8 }; // Structures #pragma pack(push, 1) struct EnumerateProcessData { RC_Size Id; RC_UnicodeChar ModulePath[PATH_MAXIMUM_LENGTH]; }; struct InstructionData { int Length; uint8_t Data[15]; RC_UnicodeChar Instruction[64]; }; struct EnumerateRemoteSectionData { RC_Pointer BaseAddress; RC_Size Size; SectionType Type; SectionCategory Category; SectionProtection Protection; RC_UnicodeChar Name[16]; RC_UnicodeChar ModulePath[PATH_MAXIMUM_LENGTH]; }; struct EnumerateRemoteModuleData { RC_Pointer BaseAddress; RC_Size Size; RC_UnicodeChar Path[PATH_MAXIMUM_LENGTH]; }; struct ExceptionDebugInfo { RC_Size ExceptionCode; RC_Size ExceptionFlags; RC_Pointer ExceptionAddress; HardwareBreakpointRegister CausedBy; struct RegisterInfo { #ifdef RECLASSNET64 RC_Pointer Rax; RC_Pointer Rbx; RC_Pointer Rcx; RC_Pointer Rdx; RC_Pointer Rdi; RC_Pointer Rsi; RC_Pointer Rsp; RC_Pointer Rbp; RC_Pointer Rip; RC_Pointer R8; RC_Pointer R9; RC_Pointer R10; RC_Pointer R11; RC_Pointer R12; RC_Pointer R13; RC_Pointer R14; RC_Pointer R15; #else RC_Pointer Eax; RC_Pointer Ebx; RC_Pointer Ecx; RC_Pointer Edx; RC_Pointer Edi; RC_Pointer Esi; RC_Pointer Esp; RC_Pointer Ebp; RC_Pointer Eip; #endif }; RegisterInfo Registers; }; struct DebugEvent { DebugContinueStatus ContinueStatus; RC_Pointer ProcessId; RC_Pointer ThreadId; ExceptionDebugInfo ExceptionInfo; }; struct DebugRegister6 { union { uintptr_t Value; struct { unsigned DR0 : 1; unsigned DR1 : 1; unsigned DR2 : 1; unsigned DR3 : 1; unsigned Reserved : 9; unsigned BD : 1; unsigned BS : 1; unsigned BT : 1; }; }; }; struct DebugRegister7 { union { uintptr_t Value; struct { unsigned G0 : 1; unsigned L0 : 1; unsigned G1 : 1; unsigned L1 : 1; unsigned G2 : 1; unsigned L2 : 1; unsigned G3 : 1; unsigned L3 : 1; unsigned GE : 1; unsigned LE : 1; unsigned Reserved : 6; unsigned RW0 : 2; unsigned Len0 : 2; unsigned RW1 : 2; unsigned Len1 : 2; unsigned RW2 : 2; unsigned Len2 : 2; unsigned RW3 : 2; unsigned Len3 : 2; }; }; }; #pragma pack(pop) // Helpers inline void MultiByteToUnicode(const char* src, RC_UnicodeChar* dst, int size) { #if _MSC_VER == 1900 // VS Bug: https://connect.microsoft.com/VisualStudio/feedback/details/1348277/link-error-when-using-std-codecvt-utf8-utf16-char16-t auto temp = std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t>{}.from_bytes(src); #else auto temp = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(src); #endif std::memcpy(dst, temp.c_str(), std::min<int>(static_cast<int>(temp.length()), size) * sizeof(char16_t)); } <commit_msg>VS2017 update.<commit_after>#pragma once #include <type_traits> #include <algorithm> #include <cstdint> #include <codecvt> #include <locale> #include <cstring> // Types using RC_Pointer = void*; using RC_Size = size_t; using RC_UnicodeChar = char16_t; // Constants const int PATH_MAXIMUM_LENGTH = 260; // Enumerations enum class ProcessAccess { Read, Write, Full }; enum class SectionProtection { NoAccess = 0, Read = 1, Write = 2, Execute = 4, Guard = 8 }; inline SectionProtection operator|(SectionProtection lhs, SectionProtection rhs) { using T = std::underlying_type_t<SectionProtection>; return static_cast<SectionProtection>(static_cast<T>(lhs) | static_cast<T>(rhs)); } inline SectionProtection& operator|=(SectionProtection& lhs, SectionProtection rhs) { using T = std::underlying_type_t<SectionProtection>; lhs = static_cast<SectionProtection>(static_cast<T>(lhs) | static_cast<T>(rhs)); return lhs; } enum class SectionType { Unknown, Private, Mapped, Image }; enum class SectionCategory { Unknown, CODE, DATA, HEAP }; enum class ControlRemoteProcessAction { Suspend, Resume, Terminate }; enum class DebugContinueStatus { Handled, NotHandled }; enum class HardwareBreakpointRegister { InvalidRegister, Dr0, Dr1, Dr2, Dr3 }; enum class HardwareBreakpointTrigger { Execute, Access, Write, }; enum class HardwareBreakpointSize { Size1 = 1, Size2 = 2, Size4 = 4, Size8 = 8 }; // Structures #pragma pack(push, 1) struct EnumerateProcessData { RC_Size Id; RC_UnicodeChar ModulePath[PATH_MAXIMUM_LENGTH]; }; struct InstructionData { int Length; uint8_t Data[15]; RC_UnicodeChar Instruction[64]; }; struct EnumerateRemoteSectionData { RC_Pointer BaseAddress; RC_Size Size; SectionType Type; SectionCategory Category; SectionProtection Protection; RC_UnicodeChar Name[16]; RC_UnicodeChar ModulePath[PATH_MAXIMUM_LENGTH]; }; struct EnumerateRemoteModuleData { RC_Pointer BaseAddress; RC_Size Size; RC_UnicodeChar Path[PATH_MAXIMUM_LENGTH]; }; struct ExceptionDebugInfo { RC_Size ExceptionCode; RC_Size ExceptionFlags; RC_Pointer ExceptionAddress; HardwareBreakpointRegister CausedBy; struct RegisterInfo { #ifdef RECLASSNET64 RC_Pointer Rax; RC_Pointer Rbx; RC_Pointer Rcx; RC_Pointer Rdx; RC_Pointer Rdi; RC_Pointer Rsi; RC_Pointer Rsp; RC_Pointer Rbp; RC_Pointer Rip; RC_Pointer R8; RC_Pointer R9; RC_Pointer R10; RC_Pointer R11; RC_Pointer R12; RC_Pointer R13; RC_Pointer R14; RC_Pointer R15; #else RC_Pointer Eax; RC_Pointer Ebx; RC_Pointer Ecx; RC_Pointer Edx; RC_Pointer Edi; RC_Pointer Esi; RC_Pointer Esp; RC_Pointer Ebp; RC_Pointer Eip; #endif }; RegisterInfo Registers; }; struct DebugEvent { DebugContinueStatus ContinueStatus; RC_Pointer ProcessId; RC_Pointer ThreadId; ExceptionDebugInfo ExceptionInfo; }; struct DebugRegister6 { union { uintptr_t Value; struct { unsigned DR0 : 1; unsigned DR1 : 1; unsigned DR2 : 1; unsigned DR3 : 1; unsigned Reserved : 9; unsigned BD : 1; unsigned BS : 1; unsigned BT : 1; }; }; }; struct DebugRegister7 { union { uintptr_t Value; struct { unsigned G0 : 1; unsigned L0 : 1; unsigned G1 : 1; unsigned L1 : 1; unsigned G2 : 1; unsigned L2 : 1; unsigned G3 : 1; unsigned L3 : 1; unsigned GE : 1; unsigned LE : 1; unsigned Reserved : 6; unsigned RW0 : 2; unsigned Len0 : 2; unsigned RW1 : 2; unsigned Len1 : 2; unsigned RW2 : 2; unsigned Len2 : 2; unsigned RW3 : 2; unsigned Len3 : 2; }; }; }; #pragma pack(pop) // Helpers inline void MultiByteToUnicode(const char* src, RC_UnicodeChar* dst, int size) { #if _MSC_VER >= 1900 // VS Bug: https://connect.microsoft.com/VisualStudio/feedback/details/1348277/link-error-when-using-std-codecvt-utf8-utf16-char16-t auto temp = std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t>{}.from_bytes(src); #else auto temp = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(src); #endif std::memcpy(dst, temp.c_str(), std::min<int>(static_cast<int>(temp.length()), size) * sizeof(char16_t)); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief Write-ahead log slot /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Wal/Slot.h" using namespace triagens::wal; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief create a slot //////////////////////////////////////////////////////////////////////////////// Slot::Slot () : _tick(0), _logfileId(0), _mem(nullptr), _size(0), _status(StatusType::UNUSED) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy a slot //////////////////////////////////////////////////////////////////////////////// Slot::~Slot () { } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief return the slot status as a string //////////////////////////////////////////////////////////////////////////////// std::string Slot::statusText () const { switch (_status) { case StatusType::UNUSED: return "unused"; case StatusType::USED: return "used"; case StatusType::RETURNED: return "returned"; } } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as used //////////////////////////////////////////////////////////////////////////////// void Slot::setUnused () { assert(isReturned()); _tick = 0; _logfileId = 0; _mem = nullptr; _size = 0; _status = StatusType::UNUSED; } //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as used //////////////////////////////////////////////////////////////////////////////// void Slot::setUsed (void* mem, uint32_t size, Logfile::IdType logfileId, Slot::TickType tick) { assert(isUnused()); _tick = tick; _logfileId = logfileId; _mem = mem; _size = size; _status = StatusType::USED; } //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as returned //////////////////////////////////////////////////////////////////////////////// void Slot::setReturned () { assert(isUsed()); _status = StatusType::RETURNED; } // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>compiler rant<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief Write-ahead log slot /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Wal/Slot.h" using namespace triagens::wal; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief create a slot //////////////////////////////////////////////////////////////////////////////// Slot::Slot () : _tick(0), _logfileId(0), _mem(nullptr), _size(0), _status(StatusType::UNUSED) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy a slot //////////////////////////////////////////////////////////////////////////////// Slot::~Slot () { } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief return the slot status as a string //////////////////////////////////////////////////////////////////////////////// std::string Slot::statusText () const { switch (_status) { case StatusType::UNUSED: return "unused"; case StatusType::USED: return "used"; case StatusType::RETURNED: return "returned"; } // listen, damn compilers!! // _status is an enum class so it has a fixed amount of possible values, // which are all covered in the above switch statement // stop stelling me that the control flow will reach the end of a non-void // function. this cannot happen!!!!! assert(false); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as used //////////////////////////////////////////////////////////////////////////////// void Slot::setUnused () { assert(isReturned()); _tick = 0; _logfileId = 0; _mem = nullptr; _size = 0; _status = StatusType::UNUSED; } //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as used //////////////////////////////////////////////////////////////////////////////// void Slot::setUsed (void* mem, uint32_t size, Logfile::IdType logfileId, Slot::TickType tick) { assert(isUnused()); _tick = tick; _logfileId = logfileId; _mem = mem; _size = size; _status = StatusType::USED; } //////////////////////////////////////////////////////////////////////////////// /// @brief mark as slot as returned //////////////////////////////////////////////////////////////////////////////// void Slot::setReturned () { assert(isUsed()); _status = StatusType::RETURNED; } // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>/*********************************************************************************** ** ** FileManager.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "FileManager.h" #include "../Wisp/WispApplication.h" CFileManager g_FileManager; //---------------------------------------------------------------------------------- CFileManager::CFileManager() : m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0) { } //---------------------------------------------------------------------------------- CFileManager::~CFileManager() { } //---------------------------------------------------------------------------------- bool CFileManager::Load() { //Try to use map uop files first, if we can, we will use them. if (UseUOP) { if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop"))) { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; } if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop"))) { if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; } if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop"))) { if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } } else { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } /* Эти файлы не используются самой последней версией клиента 7.0.52.2 if (!m_tileart.Load(g_App.FilePath("tileart.uop"))) return false; if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop"))) return false; if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop"))) return false; IFOR(i, 1, 5) { if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i))) return false; }*/ if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx"))) return false; if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul"))) return false; else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx"))) return false; else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx"))) return false; else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle"))) return false; else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul"))) return false; else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul"))) return false; else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul"))) return false; else if (!m_HuesMul.Load(g_App.FilePath("hues.mul"))) return false; else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul"))) return false; else if (!m_LightMul.Load(g_App.FilePath("light.mul"))) return false; else if (!m_MultiMul.Load(g_App.FilePath("multi.mul"))) return false; else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul"))) return false; else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul"))) return false; else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul"))) return false; else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul"))) return false; else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul"))) return false; m_SpeechMul.Load(g_App.FilePath("speech.mul")); //m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { if (i > 0) { m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i)); m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i)); } if (UseUOP && !m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i))) { m_MapMul[i].Load(g_App.FilePath("map%i.mul", i)); } /*else { /if (i == 0 || i == 1 || i == 2 || i == 5) { if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i))) return false; } }*/ m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i)); m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i)); m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i)); m_MapDifl[i].Load(g_App.FilePath("mapdifl%i.mul", i)); m_MapDif[i].Load(g_App.FilePath("mapdif%i.mul", i)); m_StaDifl[i].Load(g_App.FilePath("stadifl%i.mul", i)); m_StaDifi[i].Load(g_App.FilePath("stadifi%i.mul", i)); m_StaDif[i].Load(g_App.FilePath("stadif%i.mul", i)); } IFOR(i, 0, 20) { string s; if (i) s = g_App.FilePath("unifont%i.mul", i); else s = g_App.FilePath("unifont.mul"); if (!m_UnifontMul[i].Load(s) && i > 1) break; m_UnicodeFontsCount++; } if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul"))) m_UseVerdata = false; return true; } //---------------------------------------------------------------------------------- void CFileManager::Unload() { m_ArtIdx.Unload(); m_GumpIdx.Unload(); m_SoundIdx.Unload(); m_ArtMul.Unload(); m_GumpMul.Unload(); m_SoundMul.Unload(); m_artLegacyMUL.Unload(); m_gumpartLegacyMUL.Unload(); m_soundLegacyMUL.Unload(); m_tileart.Unload(); m_string_dictionary.Unload(); m_MultiCollection.Unload(); m_AnimationSequence.Unload(); m_MainMisc.Unload(); IFOR(i, 1, 5) { m_AnimationFrame[i].Unload(); } m_LightIdx.Unload(); m_MultiIdx.Unload(); m_SkillsIdx.Unload(); m_MultiMap.Unload(); m_TextureIdx.Unload(); m_SpeechMul.Unload(); m_AnimdataMul.Unload(); m_HuesMul.Unload(); m_FontsMul.Unload(); m_LightMul.Unload(); m_MultiMul.Unload(); m_PaletteMul.Unload(); m_RadarcolMul.Unload(); m_SkillsMul.Unload(); m_TextureMul.Unload(); m_TiledataMul.Unload(); m_LangcodeIff.Unload(); IFOR(i, 0, 6) { m_AnimIdx[i].Unload(); m_AnimMul[i].Unload(); m_MapUOP[i].Unload(); m_MapXUOP[i].Unload(); m_MapMul[i].Unload(); m_StaticIdx[i].Unload(); m_StaticMul[i].Unload(); m_FacetMul[i].Unload(); m_MapDifl[i].Unload(); m_MapDif[i].Unload(); m_StaDifl[i].Unload(); m_StaDifi[i].Unload(); m_StaDif[i].Unload(); } IFOR(i, 0, 20) m_UnifontMul[i].Unload(); m_VerdataMul.Unload(); } //----------------------------------------------------------------------------------<commit_msg>map mul loading without uop attempt if version is lower than 7x<commit_after>/*********************************************************************************** ** ** FileManager.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "FileManager.h" #include "../Wisp/WispApplication.h" CFileManager g_FileManager; //---------------------------------------------------------------------------------- CFileManager::CFileManager() : m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0) { } //---------------------------------------------------------------------------------- CFileManager::~CFileManager() { } //---------------------------------------------------------------------------------- bool CFileManager::Load() { //Try to use map uop files first, if we can, we will use them. if (UseUOP) { if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop"))) { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; } if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop"))) { if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; } if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop"))) { if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } } else { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } /* Эти файлы не используются самой последней версией клиента 7.0.52.2 if (!m_tileart.Load(g_App.FilePath("tileart.uop"))) return false; if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop"))) return false; if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop"))) return false; IFOR(i, 1, 5) { if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i))) return false; }*/ if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx"))) return false; if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul"))) return false; else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx"))) return false; else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx"))) return false; else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle"))) return false; else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul"))) return false; else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul"))) return false; else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul"))) return false; else if (!m_HuesMul.Load(g_App.FilePath("hues.mul"))) return false; else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul"))) return false; else if (!m_LightMul.Load(g_App.FilePath("light.mul"))) return false; else if (!m_MultiMul.Load(g_App.FilePath("multi.mul"))) return false; else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul"))) return false; else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul"))) return false; else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul"))) return false; else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul"))) return false; else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul"))) return false; m_SpeechMul.Load(g_App.FilePath("speech.mul")); //m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { if (i > 0) { m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i)); m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i)); } if (UseUOP) m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i)); else m_MapMul[i].Load(g_App.FilePath("map%i.mul", i)); /*else { /if (i == 0 || i == 1 || i == 2 || i == 5) { if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i))) return false; } }*/ m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i)); m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i)); m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i)); m_MapDifl[i].Load(g_App.FilePath("mapdifl%i.mul", i)); m_MapDif[i].Load(g_App.FilePath("mapdif%i.mul", i)); m_StaDifl[i].Load(g_App.FilePath("stadifl%i.mul", i)); m_StaDifi[i].Load(g_App.FilePath("stadifi%i.mul", i)); m_StaDif[i].Load(g_App.FilePath("stadif%i.mul", i)); } IFOR(i, 0, 20) { string s; if (i) s = g_App.FilePath("unifont%i.mul", i); else s = g_App.FilePath("unifont.mul"); if (!m_UnifontMul[i].Load(s) && i > 1) break; m_UnicodeFontsCount++; } if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul"))) m_UseVerdata = false; return true; } //---------------------------------------------------------------------------------- void CFileManager::Unload() { m_ArtIdx.Unload(); m_GumpIdx.Unload(); m_SoundIdx.Unload(); m_ArtMul.Unload(); m_GumpMul.Unload(); m_SoundMul.Unload(); m_artLegacyMUL.Unload(); m_gumpartLegacyMUL.Unload(); m_soundLegacyMUL.Unload(); m_tileart.Unload(); m_string_dictionary.Unload(); m_MultiCollection.Unload(); m_AnimationSequence.Unload(); m_MainMisc.Unload(); IFOR(i, 1, 5) { m_AnimationFrame[i].Unload(); } m_LightIdx.Unload(); m_MultiIdx.Unload(); m_SkillsIdx.Unload(); m_MultiMap.Unload(); m_TextureIdx.Unload(); m_SpeechMul.Unload(); m_AnimdataMul.Unload(); m_HuesMul.Unload(); m_FontsMul.Unload(); m_LightMul.Unload(); m_MultiMul.Unload(); m_PaletteMul.Unload(); m_RadarcolMul.Unload(); m_SkillsMul.Unload(); m_TextureMul.Unload(); m_TiledataMul.Unload(); m_LangcodeIff.Unload(); IFOR(i, 0, 6) { m_AnimIdx[i].Unload(); m_AnimMul[i].Unload(); m_MapUOP[i].Unload(); m_MapXUOP[i].Unload(); m_MapMul[i].Unload(); m_StaticIdx[i].Unload(); m_StaticMul[i].Unload(); m_FacetMul[i].Unload(); m_MapDifl[i].Unload(); m_MapDif[i].Unload(); m_StaDifl[i].Unload(); m_StaDifi[i].Unload(); m_StaDif[i].Unload(); } IFOR(i, 0, 20) m_UnifontMul[i].Unload(); m_VerdataMul.Unload(); } //----------------------------------------------------------------------------------<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageActor.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkImageActor.h" #include "vtkObjectFactory.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkRenderer.h" #include "vtkImageProperty.h" #include "vtkImageSliceMapper.h" #include "vtkInformation.h" #include "vtkStreamingDemandDrivenPipeline.h" vtkStandardNewMacro(vtkImageActor); //---------------------------------------------------------------------------- vtkImageActor::vtkImageActor() { this->DisplayExtent[0] = -1; this->DisplayExtent[1] = 0; this->DisplayExtent[2] = 0; this->DisplayExtent[3] = 0; this->DisplayExtent[4] = 0; this->DisplayExtent[5] = 0; vtkMath::UninitializeBounds(this->DisplayBounds); this->Property = vtkImageProperty::New(); this->Property->SetInterpolationTypeToLinear(); this->Property->SetAmbient(1.0); this->Property->SetDiffuse(0.0); vtkImageSliceMapper *mapper = vtkImageSliceMapper::New(); this->Mapper = mapper; mapper->BorderOff(); mapper->SliceAtFocalPointOff(); mapper->SliceFacesCameraOff(); mapper->SetOrientationToZ(); } //---------------------------------------------------------------------------- vtkImageActor::~vtkImageActor() { if (this->Property) { this->Property->Delete(); this->Property = NULL; } if (this->Mapper) { this->Mapper->Delete(); this->Mapper = NULL; } } //---------------------------------------------------------------------------- void vtkImageActor::SetInputData(vtkImageData *input) { if (this->Mapper && input != this->Mapper->GetInput()) { this->Mapper->SetInputData(input); this->Modified(); } } //---------------------------------------------------------------------------- vtkAlgorithm *vtkImageActor::GetInputAlgorithm() { if (!this->Mapper) { return 0; } return this->Mapper->GetInputAlgorithm(); } //---------------------------------------------------------------------------- vtkImageData *vtkImageActor::GetInput() { if (!this->Mapper) { return 0; } return this->Mapper->GetInput(); } //---------------------------------------------------------------------------- void vtkImageActor::SetInterpolate(int i) { if (this->Property) { if (i) { if (this->Property->GetInterpolationType() != VTK_LINEAR_INTERPOLATION) { this->Property->SetInterpolationTypeToLinear(); this->Modified(); } } else { if (this->Property->GetInterpolationType() != VTK_NEAREST_INTERPOLATION) { this->Property->SetInterpolationTypeToNearest(); this->Modified(); } } } } //---------------------------------------------------------------------------- int vtkImageActor::GetInterpolate() { if (this->Property && this->Property->GetInterpolationType() != VTK_NEAREST_INTERPOLATION) { return 1; } return 0; } //---------------------------------------------------------------------------- void vtkImageActor::SetOpacity(double o) { if (this->Property && this->Property->GetOpacity() != o) { this->Property->SetOpacity(o); this->Modified(); } } //---------------------------------------------------------------------------- double vtkImageActor::GetOpacity() { if (this->Property) { return this->Property->GetOpacity(); } return 1.0; } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumber() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper)->GetSliceNumber(); } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumberMax() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper) ->GetSliceNumberMaxValue(); } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumberMin() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper) ->GetSliceNumberMinValue(); } //---------------------------------------------------------------------------- void vtkImageActor::SetDisplayExtent(int extent[6]) { int idx, modified = 0; for (idx = 0; idx < 6; ++idx) { if (this->DisplayExtent[idx] != extent[idx]) { this->DisplayExtent[idx] = extent[idx]; modified = 1; } } if (modified) { if (this->Mapper && this->Mapper->IsA("vtkImageSliceMapper")) { if (this->DisplayExtent[0] != -1) { static_cast<vtkImageSliceMapper *>(this->Mapper)->CroppingOn(); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetCroppingRegion(this->DisplayExtent); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetOrientation(this->GetOrientationFromExtent(this->DisplayExtent)); } else { static_cast<vtkImageSliceMapper *>(this->Mapper)->CroppingOff(); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetOrientationToZ(); } } this->Modified(); } } //---------------------------------------------------------------------------- void vtkImageActor::SetDisplayExtent(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { int extent[6]; extent[0] = minX; extent[1] = maxX; extent[2] = minY; extent[3] = maxY; extent[4] = minZ; extent[5] = maxZ; this->SetDisplayExtent(extent); } //---------------------------------------------------------------------------- void vtkImageActor::GetDisplayExtent(int extent[6]) { for (int idx = 0; idx < 6; ++idx) { extent[idx] = this->DisplayExtent[idx]; } } //---------------------------------------------------------------------------- // Get the bounds for this Volume as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkImageActor::GetDisplayBounds() { vtkAlgorithm* inputAlg = this->Mapper->GetInputAlgorithm(); if (this->Mapper) { inputAlg = this->Mapper->GetInputAlgorithm(); } if (!this->Mapper || !inputAlg) { return this->DisplayBounds; } inputAlg->UpdateInformation(); int extent[6]; vtkInformation* inputInfo = this->Mapper->GetInputInformation(); inputInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); double spacing[3] = {1, 1, 1}; if (inputInfo->Has(vtkDataObject::SPACING())) { inputInfo->Get(vtkDataObject::SPACING(), spacing); } double origin[3] = {0, 0, 0}; if (inputInfo->Has(vtkDataObject::ORIGIN())) { inputInfo->Get(vtkDataObject::ORIGIN(), origin); } // if the display extent has not been set, use first slice extent[5] = extent[4]; if (this->DisplayExtent[0] != -1) { extent[0] = this->DisplayExtent[0]; extent[1] = this->DisplayExtent[1]; extent[2] = this->DisplayExtent[2]; extent[3] = this->DisplayExtent[3]; extent[4] = this->DisplayExtent[4]; extent[5] = this->DisplayExtent[5]; } if (spacing[0] >= 0) { this->DisplayBounds[0] = extent[0]*spacing[0] + origin[0]; this->DisplayBounds[1] = extent[1]*spacing[0] + origin[0]; } else { this->DisplayBounds[0] = extent[1]*spacing[0] + origin[0]; this->DisplayBounds[1] = extent[0]*spacing[0] + origin[0]; } if (spacing[1] >= 0) { this->DisplayBounds[2] = extent[2]*spacing[1] + origin[1]; this->DisplayBounds[3] = extent[3]*spacing[1] + origin[1]; } else { this->DisplayBounds[2] = extent[3]*spacing[1] + origin[1]; this->DisplayBounds[3] = extent[2]*spacing[1] + origin[1]; } if (spacing[2] >= 0) { this->DisplayBounds[4] = extent[4]*spacing[2] + origin[2]; this->DisplayBounds[5] = extent[5]*spacing[2] + origin[2]; } else { this->DisplayBounds[4] = extent[5]*spacing[2] + origin[2]; this->DisplayBounds[5] = extent[4]*spacing[2] + origin[2]; } return this->DisplayBounds; } //---------------------------------------------------------------------------- // Get the bounds for the displayed data as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). void vtkImageActor::GetDisplayBounds(double bounds[6]) { this->GetDisplayBounds(); for (int i = 0; i < 6; i++) { bounds[i] = this->DisplayBounds[i]; } } //---------------------------------------------------------------------------- // Get the bounds for this Prop3D as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkImageActor::GetBounds() { int i,n; double *bounds, bbox[24], *fptr; bounds = this->GetDisplayBounds(); // Check for the special case when the data bounds are unknown if (!bounds) { return bounds; } // fill out vertices of a bounding box bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5]; bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5]; bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5]; bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5]; bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4]; bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4]; bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4]; bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4]; // make sure matrix (transform) is up-to-date this->ComputeMatrix(); // and transform into actors coordinates fptr = bbox; for (n = 0; n < 8; n++) { double homogeneousPt[4] = {fptr[0], fptr[1], fptr[2], 1.0}; this->Matrix->MultiplyPoint(homogeneousPt, homogeneousPt); fptr[0] = homogeneousPt[0] / homogeneousPt[3]; fptr[1] = homogeneousPt[1] / homogeneousPt[3]; fptr[2] = homogeneousPt[2] / homogeneousPt[3]; fptr += 3; } // now calc the new bounds this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_DOUBLE_MAX; for (i = 0; i < 8; i++) { for (n = 0; n < 3; n++) { if (bbox[i*3+n] < this->Bounds[n*2]) { this->Bounds[n*2] = bbox[i*3+n]; } if (bbox[i*3+n] > this->Bounds[n*2+1]) { this->Bounds[n*2+1] = bbox[i*3+n]; } } } return this->Bounds; } //---------------------------------------------------------------------------- int vtkImageActor::GetOrientationFromExtent(const int extent[6]) { int orientation = 2; if (extent[4] == extent[5]) { orientation = 2; } else if (extent[2] == extent[3]) { orientation = 1; } else if (extent[0] == extent[1]) { orientation = 0; } return orientation; } //---------------------------------------------------------------------------- void vtkImageActor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Input: " << this->GetInput() << "\n"; os << indent << "Interpolate: " << (this->GetInterpolate() ? "On\n" : "Off\n"); os << indent << "Opacity: " << this->GetOpacity() << "\n"; os << indent << "DisplayExtent: (" << this->DisplayExtent[0]; for (int idx = 1; idx < 6; ++idx) { os << ", " << this->DisplayExtent[idx]; } os << ")\n"; } //---------------------------------------------------------------------------- int vtkImageActor::GetWholeZMin() { int *extent; if ( ! this->GetInputAlgorithm()) { return 0; } this->GetInputAlgorithm()->UpdateInformation(); extent = this->Mapper->GetInputInformation()->Get( vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); return extent[4]; } //---------------------------------------------------------------------------- int vtkImageActor::GetWholeZMax() { int *extent; if ( ! this->GetInputAlgorithm()) { return 0; } this->GetInputAlgorithm()->UpdateInformation(); extent = this->Mapper->GetInputInformation()->Get( vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); return extent[5]; } //----------------------------------------------------------------------------- // Description: // Does this prop have some translucent polygonal geometry? int vtkImageActor::HasTranslucentPolygonalGeometry() { vtkImageData *input = this->GetInput(); if (!input) { return 0; } // This requires that Update has been called on the mapper, // which the Renderer does immediately before it renders. if ( input->GetScalarType() == VTK_UNSIGNED_CHAR ) { if (!(this->GetOpacity() >= 1.0 && input->GetNumberOfScalarComponents() % 2)) { return 1; } } return 0; } <commit_msg>vtkImageActor now supports DisplayExtent starting at -1<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageActor.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkImageActor.h" #include "vtkObjectFactory.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkRenderer.h" #include "vtkImageProperty.h" #include "vtkImageSliceMapper.h" #include "vtkInformation.h" #include "vtkStreamingDemandDrivenPipeline.h" vtkStandardNewMacro(vtkImageActor); //---------------------------------------------------------------------------- vtkImageActor::vtkImageActor() { this->DisplayExtent[0] = 0; this->DisplayExtent[1] = -1; this->DisplayExtent[2] = 0; this->DisplayExtent[3] = -1; this->DisplayExtent[4] = 0; this->DisplayExtent[5] = -1; vtkMath::UninitializeBounds(this->DisplayBounds); this->Property = vtkImageProperty::New(); this->Property->SetInterpolationTypeToLinear(); this->Property->SetAmbient(1.0); this->Property->SetDiffuse(0.0); vtkImageSliceMapper *mapper = vtkImageSliceMapper::New(); this->Mapper = mapper; mapper->BorderOff(); mapper->SliceAtFocalPointOff(); mapper->SliceFacesCameraOff(); mapper->SetOrientationToZ(); } //---------------------------------------------------------------------------- vtkImageActor::~vtkImageActor() { if (this->Property) { this->Property->Delete(); this->Property = NULL; } if (this->Mapper) { this->Mapper->Delete(); this->Mapper = NULL; } } //---------------------------------------------------------------------------- void vtkImageActor::SetInputData(vtkImageData *input) { if (this->Mapper && input != this->Mapper->GetInput()) { this->Mapper->SetInputData(input); this->Modified(); } } //---------------------------------------------------------------------------- vtkAlgorithm *vtkImageActor::GetInputAlgorithm() { if (!this->Mapper) { return 0; } return this->Mapper->GetInputAlgorithm(); } //---------------------------------------------------------------------------- vtkImageData *vtkImageActor::GetInput() { if (!this->Mapper) { return 0; } return this->Mapper->GetInput(); } //---------------------------------------------------------------------------- void vtkImageActor::SetInterpolate(int i) { if (this->Property) { if (i) { if (this->Property->GetInterpolationType() != VTK_LINEAR_INTERPOLATION) { this->Property->SetInterpolationTypeToLinear(); this->Modified(); } } else { if (this->Property->GetInterpolationType() != VTK_NEAREST_INTERPOLATION) { this->Property->SetInterpolationTypeToNearest(); this->Modified(); } } } } //---------------------------------------------------------------------------- int vtkImageActor::GetInterpolate() { if (this->Property && this->Property->GetInterpolationType() != VTK_NEAREST_INTERPOLATION) { return 1; } return 0; } //---------------------------------------------------------------------------- void vtkImageActor::SetOpacity(double o) { if (this->Property && this->Property->GetOpacity() != o) { this->Property->SetOpacity(o); this->Modified(); } } //---------------------------------------------------------------------------- double vtkImageActor::GetOpacity() { if (this->Property) { return this->Property->GetOpacity(); } return 1.0; } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumber() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper)->GetSliceNumber(); } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumberMax() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper) ->GetSliceNumberMaxValue(); } //---------------------------------------------------------------------------- int vtkImageActor::GetSliceNumberMin() { if (!this->Mapper || !this->Mapper->IsA("vtkImageSliceMapper")) { return 0; } return static_cast<vtkImageSliceMapper *>(this->Mapper) ->GetSliceNumberMinValue(); } //---------------------------------------------------------------------------- void vtkImageActor::SetDisplayExtent(int extent[6]) { int idx, modified = 0; for (idx = 0; idx < 6; ++idx) { if (this->DisplayExtent[idx] != extent[idx]) { this->DisplayExtent[idx] = extent[idx]; modified = 1; } } if (modified) { if (this->Mapper && this->Mapper->IsA("vtkImageSliceMapper")) { if (this->DisplayExtent[0] <= this->DisplayExtent[1]) { static_cast<vtkImageSliceMapper *>(this->Mapper)->CroppingOn(); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetCroppingRegion(this->DisplayExtent); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetOrientation(this->GetOrientationFromExtent(this->DisplayExtent)); } else { static_cast<vtkImageSliceMapper *>(this->Mapper)->CroppingOff(); static_cast<vtkImageSliceMapper *>(this->Mapper)-> SetOrientationToZ(); } } this->Modified(); } } //---------------------------------------------------------------------------- void vtkImageActor::SetDisplayExtent(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { int extent[6]; extent[0] = minX; extent[1] = maxX; extent[2] = minY; extent[3] = maxY; extent[4] = minZ; extent[5] = maxZ; this->SetDisplayExtent(extent); } //---------------------------------------------------------------------------- void vtkImageActor::GetDisplayExtent(int extent[6]) { for (int idx = 0; idx < 6; ++idx) { extent[idx] = this->DisplayExtent[idx]; } } //---------------------------------------------------------------------------- // Get the bounds for this Volume as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkImageActor::GetDisplayBounds() { vtkAlgorithm* inputAlg = this->Mapper->GetInputAlgorithm(); if (this->Mapper) { inputAlg = this->Mapper->GetInputAlgorithm(); } if (!this->Mapper || !inputAlg) { return this->DisplayBounds; } inputAlg->UpdateInformation(); int extent[6]; vtkInformation* inputInfo = this->Mapper->GetInputInformation(); inputInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); double spacing[3] = {1, 1, 1}; if (inputInfo->Has(vtkDataObject::SPACING())) { inputInfo->Get(vtkDataObject::SPACING(), spacing); } double origin[3] = {0, 0, 0}; if (inputInfo->Has(vtkDataObject::ORIGIN())) { inputInfo->Get(vtkDataObject::ORIGIN(), origin); } // if the display extent has not been set, use first slice extent[5] = extent[4]; if (this->DisplayExtent[0] <= this->DisplayExtent[1]) { extent[0] = this->DisplayExtent[0]; extent[1] = this->DisplayExtent[1]; extent[2] = this->DisplayExtent[2]; extent[3] = this->DisplayExtent[3]; extent[4] = this->DisplayExtent[4]; extent[5] = this->DisplayExtent[5]; } if (spacing[0] >= 0) { this->DisplayBounds[0] = extent[0]*spacing[0] + origin[0]; this->DisplayBounds[1] = extent[1]*spacing[0] + origin[0]; } else { this->DisplayBounds[0] = extent[1]*spacing[0] + origin[0]; this->DisplayBounds[1] = extent[0]*spacing[0] + origin[0]; } if (spacing[1] >= 0) { this->DisplayBounds[2] = extent[2]*spacing[1] + origin[1]; this->DisplayBounds[3] = extent[3]*spacing[1] + origin[1]; } else { this->DisplayBounds[2] = extent[3]*spacing[1] + origin[1]; this->DisplayBounds[3] = extent[2]*spacing[1] + origin[1]; } if (spacing[2] >= 0) { this->DisplayBounds[4] = extent[4]*spacing[2] + origin[2]; this->DisplayBounds[5] = extent[5]*spacing[2] + origin[2]; } else { this->DisplayBounds[4] = extent[5]*spacing[2] + origin[2]; this->DisplayBounds[5] = extent[4]*spacing[2] + origin[2]; } return this->DisplayBounds; } //---------------------------------------------------------------------------- // Get the bounds for the displayed data as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). void vtkImageActor::GetDisplayBounds(double bounds[6]) { this->GetDisplayBounds(); for (int i = 0; i < 6; i++) { bounds[i] = this->DisplayBounds[i]; } } //---------------------------------------------------------------------------- // Get the bounds for this Prop3D as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkImageActor::GetBounds() { int i,n; double *bounds, bbox[24], *fptr; bounds = this->GetDisplayBounds(); // Check for the special case when the data bounds are unknown if (!bounds) { return bounds; } // fill out vertices of a bounding box bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5]; bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5]; bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5]; bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5]; bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4]; bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4]; bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4]; bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4]; // make sure matrix (transform) is up-to-date this->ComputeMatrix(); // and transform into actors coordinates fptr = bbox; for (n = 0; n < 8; n++) { double homogeneousPt[4] = {fptr[0], fptr[1], fptr[2], 1.0}; this->Matrix->MultiplyPoint(homogeneousPt, homogeneousPt); fptr[0] = homogeneousPt[0] / homogeneousPt[3]; fptr[1] = homogeneousPt[1] / homogeneousPt[3]; fptr[2] = homogeneousPt[2] / homogeneousPt[3]; fptr += 3; } // now calc the new bounds this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_DOUBLE_MAX; for (i = 0; i < 8; i++) { for (n = 0; n < 3; n++) { if (bbox[i*3+n] < this->Bounds[n*2]) { this->Bounds[n*2] = bbox[i*3+n]; } if (bbox[i*3+n] > this->Bounds[n*2+1]) { this->Bounds[n*2+1] = bbox[i*3+n]; } } } return this->Bounds; } //---------------------------------------------------------------------------- int vtkImageActor::GetOrientationFromExtent(const int extent[6]) { int orientation = 2; if (extent[4] == extent[5]) { orientation = 2; } else if (extent[2] == extent[3]) { orientation = 1; } else if (extent[0] == extent[1]) { orientation = 0; } return orientation; } //---------------------------------------------------------------------------- void vtkImageActor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Input: " << this->GetInput() << "\n"; os << indent << "Interpolate: " << (this->GetInterpolate() ? "On\n" : "Off\n"); os << indent << "Opacity: " << this->GetOpacity() << "\n"; os << indent << "DisplayExtent: (" << this->DisplayExtent[0]; for (int idx = 1; idx < 6; ++idx) { os << ", " << this->DisplayExtent[idx]; } os << ")\n"; } //---------------------------------------------------------------------------- int vtkImageActor::GetWholeZMin() { int *extent; if ( ! this->GetInputAlgorithm()) { return 0; } this->GetInputAlgorithm()->UpdateInformation(); extent = this->Mapper->GetInputInformation()->Get( vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); return extent[4]; } //---------------------------------------------------------------------------- int vtkImageActor::GetWholeZMax() { int *extent; if ( ! this->GetInputAlgorithm()) { return 0; } this->GetInputAlgorithm()->UpdateInformation(); extent = this->Mapper->GetInputInformation()->Get( vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); return extent[5]; } //----------------------------------------------------------------------------- // Description: // Does this prop have some translucent polygonal geometry? int vtkImageActor::HasTranslucentPolygonalGeometry() { vtkImageData *input = this->GetInput(); if (!input) { return 0; } // This requires that Update has been called on the mapper, // which the Renderer does immediately before it renders. if ( input->GetScalarType() == VTK_UNSIGNED_CHAR ) { if (!(this->GetOpacity() >= 1.0 && input->GetNumberOfScalarComponents() % 2)) { return 1; } } return 0; } <|endoftext|>
<commit_before> #include "common.h" // Didn't find sleep in QCore #ifdef Q_OS_WIN #include <winsock2.h> // for windows.h #include <windows.h> // for Sleep #endif #include <QDebug> // TODO move this to a different file from common.h void qSleep(int ms) { #ifdef Q_OS_WIN Sleep(uint(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, nullptr); #endif } //TODO use cryptographically secure callID generation to avoid collisions. const QString alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789"; QString generateRandomString(uint32_t length) { // TODO make this cryptographically secure to avoid collisions QString string; for( unsigned int i = 0; i < length; ++i ) { string.append(alphabet.at(qrand()%alphabet.size())); } return string; } const std::map<DebugContext, QString> contextToString = {{DC_NO_CONTEXT, ""}, {DC_STARTUP, "Startup"}, {DC_SHUTDOWN, "Shutdown"}, {DC_SETTINGS, "Settings"}, {DC_START_CALL, "Starting call"}, {DC_END_CALL, "Ending a call"}, {DC_RINGING, "Ringing"}, {DC_ACCEPT, "Accepting"}, {DC_NEGOTIATING, "Negotiating the call"}, {DC_SIP_CONTENT, "SIP Content"}, {DC_ADD_MEDIA, "Creating Media"}, {DC_REMOVE_MEDIA, "Removing Media"}, {DC_PROCESS_MEDIA, "Processing Media"}, {DC_AUDIO, "Audio"}, {DC_FULLSCREEN, "Fullscreen"}, {DC_DRAWING, "Drawing"}, {DC_TCP, "TCP connection"}, {DC_SEND_SIP, "Sending SIP"}, {DC_SEND_SIP_REQUEST, "Sending SIP Request"}, {DC_SEND_SIP_RESPONSE, "Sending SIP Response"}, {DC_RECEIVE_SIP, "Receiving SIP"}, {DC_RECEIVE_SIP_REQUEST, "Receiving SIP Request"}, {DC_RECEIVE_SIP_RESPONSE, "Receiving SIP Response"}}; void printDebug(DebugType type, QObject* object, DebugContext context, QString description, QStringList valueNames, QStringList values) { printDebug(type, object->metaObject()->className(), context, description, valueNames, values); } void printDebug(DebugType type, QString className, DebugContext context, QString description, QStringList valueNames, QStringList values) { QString valueString = ""; if (valueNames.size() == values.size()) // equal number of names and values { for (int i = 0; i < valueNames.size(); ++i) { valueString.append(valueNames.at(i)); valueString.append(": "); valueString.append(values.at(i)); if (i != valueNames.size() - 1) { valueString.append("\r\n"); } } } else if (valueNames.size() == 1) // if we have one name, add it { valueString.append(valueNames.at(0)); valueString.append(": "); } if (valueNames.empty() || valueNames.size() == 1) // print values { for (int i = 0; i < values.size(); ++i) { valueString.append(values.at(i)); if (i != values.size() - 1) { valueString.append(", "); } } valueString.append("\r\n"); } else { qDebug() << "Debug printing could not figure how to print error values." << "Names:" << valueNames.size() << "values: " << values.size(); } QString contextString = "No context"; if (contextToString.find(context) != contextToString.end()) { contextString = contextToString.at(context); } // This could be reduced, but it might change so not worth probably at the moment. // Choose which text to print based on type. switch (type) { case DEBUG_NORMAL: { qDebug().nospace().noquote() << contextString << ", " << className << ": " << description << " " << valueString; break; } case DEBUG_ERROR: { qCritical() << "ERROR: " << description << " " << valueString; break; } case DEBUG_WARNING: { qCritical() << "Warning: " << description << " " << valueString; break; } case DEBUG_PEER_ERROR: { qWarning().nospace().noquote() << "PEER ERROR: --------------------------------------------"; qWarning().nospace().noquote() << contextString << ", " << className << ": " << description << " " << valueString; qWarning().nospace().noquote() << "-------------------------------------------- PEER ERROR"; break; } case DEBUG_PROGRAM_ERROR: { qCritical().nospace().noquote() << "BUG DETECTED: --------------------------------------------"; qCritical().nospace().noquote() << contextString << ", " << className << ": " << description << " " << valueString; qCritical().nospace().noquote() << "-------------------------------------------- BUG"; break; } case DEBUG_PROGRAM_WARNING: { qWarning().nospace().noquote() << "MINOR BUG DETECTED: --------------------------------------------"; qWarning().nospace().noquote() << contextString << ", " << className << ": " << description << " " << valueString; qWarning().nospace() << "\r\n" << "-------------------------------------------- MINOR BUG"; break; } } } <commit_msg>feature(Global): Improved debug printing format and fixed errors.<commit_after> #include "common.h" // Didn't find sleep in QCore #ifdef Q_OS_WIN #include <winsock2.h> // for windows.h #include <windows.h> // for Sleep #endif #include <QDebug> // TODO move this to a different file from common.h void qSleep(int ms) { #ifdef Q_OS_WIN Sleep(uint(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, nullptr); #endif } const int BEGIN_LENGTH = 30; //TODO use cryptographically secure callID generation to avoid collisions. const QString alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789"; QString generateRandomString(uint32_t length) { // TODO make this cryptographically secure to avoid collisions QString string; for( unsigned int i = 0; i < length; ++i ) { string.append(alphabet.at(qrand()%alphabet.size())); } return string; } const std::map<DebugContext, QString> contextToString = {{DC_NO_CONTEXT, ""}, {DC_STARTUP, "Startup"}, {DC_SHUTDOWN, "Shutdown"}, {DC_SETTINGS, "Settings"}, {DC_START_CALL, "Starting call"}, {DC_END_CALL, "Ending a call"}, {DC_RINGING, "Ringing"}, {DC_ACCEPT, "Accepting"}, {DC_NEGOTIATING, "Negotiating the call"}, {DC_SIP_CONTENT, "SIP Content"}, {DC_ADD_MEDIA, "Creating Media"}, {DC_REMOVE_MEDIA, "Removing Media"}, {DC_PROCESS_MEDIA, "Processing Media"}, {DC_AUDIO, "Audio"}, {DC_FULLSCREEN, "Fullscreen"}, {DC_DRAWING, "Drawing"}, {DC_TCP, "TCP connection"}, {DC_SEND_SIP, "Sending SIP"}, {DC_SEND_SIP_REQUEST, "Sending SIP Request"}, {DC_SEND_SIP_RESPONSE, "Sending SIP Response"}, {DC_RECEIVE_SIP, "Receiving SIP"}, {DC_RECEIVE_SIP_REQUEST, "Receiving SIP Request"}, {DC_RECEIVE_SIP_RESPONSE, "Receiving SIP Response"}}; void printDebug(DebugType type, QObject* object, DebugContext context, QString description, QStringList valueNames, QStringList values) { printDebug(type, object->metaObject()->className(), context, description, valueNames, values); } void printDebug(DebugType type, QString className, DebugContext context, QString description, QStringList valueNames, QStringList values) { QString valueString = ""; // do we have values. if( values.size() != 0) { // Add "name: value" because equal number of both. if (valueNames.size() == values.size()) // equal number of names and values { for (int i = 0; i < valueNames.size(); ++i) { valueString.append(valueNames.at(i)); valueString.append(": "); valueString.append(values.at(i)); if (i != valueNames.size() - 1) { valueString.append("\r\n"); } } } else if (valueNames.size() == 1) // if we have one name, add it { valueString.append(valueNames.at(0)); valueString.append(": "); } // If we have one or zero names, just add all values, unless we have 1 of both // in which case they were added earlier. if (valueNames.empty() || (valueNames.size() == 1 && values.size() != 1)) { for (int i = 0; i < values.size(); ++i) { valueString.append(values.at(i)); if (i != values.size() - 1) { valueString.append(", "); } } valueString.append("\r\n"); } else if (valueNames.size() != values.size()) { qDebug() << "Debug printing could not figure how to print error values." << "Names:" << valueNames.size() << "values: " << values.size(); } } QString contextString = "No context"; if (contextToString.find(context) != contextToString.end()) { contextString = contextToString.at(context); } // TODO: Set a constant length for everything before description. QString beginString = contextString + ", " + className + ": "; if (beginString.length() < BEGIN_LENGTH) { beginString = beginString.leftJustified(BEGIN_LENGTH, ' '); } // This could be reduced, but it might change so not worth probably at the moment. // Choose which text to print based on type. switch (type) { case DEBUG_NORMAL: { qDebug().nospace().noquote() << beginString << description; if (!valueString.isEmpty()) { qDebug().nospace().noquote() << valueString; } break; } case DEBUG_ERROR: { qCritical() << "ERROR: " << description << " " << valueString; break; } case DEBUG_WARNING: { qCritical() << "Warning: " << description << " " << valueString; break; } case DEBUG_PEER_ERROR: { qWarning().nospace().noquote() << "PEER ERROR: --------------------------------------------"; qWarning().nospace().noquote() << beginString << description; if (!valueString.isEmpty()) { qWarning().nospace().noquote() << valueString; } qWarning().nospace().noquote() << "-------------------------------------------- PEER ERROR"; break; } case DEBUG_PROGRAM_ERROR: { qCritical().nospace().noquote() << "BUG DETECTED: --------------------------------------------"; qCritical().nospace().noquote() << beginString << description; if (!valueString.isEmpty()) { qCritical().nospace().noquote() << valueString; } qCritical().nospace().noquote() << "-------------------------------------------- BUG"; break; } case DEBUG_PROGRAM_WARNING: { qWarning().nospace().noquote() << "MINOR BUG DETECTED: --------------------------------------------"; qWarning().nospace().noquote() << beginString << description; if (!valueString.isEmpty()) { qWarning().nospace().noquote() << valueString; } qWarning().nospace() << "\r\n" << "-------------------------------------------- MINOR BUG"; break; } } } <|endoftext|>
<commit_before>#include "measure.h" #include "sleep.h" //TODO: Fix comments... QList<qreal> sm_diff(QByteArray data, int nr)//nr - Depth of smoothing in one direction { QList<qreal> diff; for (int i=0;i<data.count();i++) { if(i<nr || i>=data.count()-nr) { diff<<0; continue; } double a=0; double b=0; for (int k=-nr;k<=nr;k++) { a+=k*data[i+k]-k*data[i+k]/nr; b+=k*k; } diff<<a/b*10; } return diff; } cmeasure::cmeasure(QString oscstr, QString genstr, QString volstr, double sf, double ff, double epsilon, QObject *parent) { connect(this,SIGNAL(path(QList<qreal>,QPen)),parent,SLOT(path(QList<qreal>,QPen)),Qt::QueuedConnection); connect(this,SIGNAL(path(QByteArray,QPen)),parent,SLOT(path(QByteArray,QPen)),Qt::QueuedConnection); connect(this,SIGNAL(line(qreal,qreal,qreal,qreal,QPen)),parent,SLOT(line(qreal,qreal,qreal,qreal,QPen)),Qt::QueuedConnection); this->oscstr=oscstr; gen = new genctrl(genstr); vol = new volctrl(volstr); fsf=sf; fff=ff; this->epsilon=epsilon; findresonance(); } cmeasure::~cmeasure() { delete gen; delete vol; } QByteArray cmeasure::sweep() { osc = new oscctrl((char*)oscstr.toAscii().data()); int mini=0; int maxi=0; int starti, stopi; QByteArray data; while(!(mini>maxi)) { gen->setsweep(fsf,fff); osc->wait("READY"); gen->startsweep(); osc->wait("READY"); data = osc->readcurve(); /* max * _ * / \ * ___/ | _______ * \_/ * min * * /\ _ * --- \ / ------- * \_/ * diff_min/ * */ QList<qreal> diff = sm_diff(data,2); double min_diff_val=0; int min_diff_index; //find diff_min for (int i=0;i<diff.count();i++) if (diff[i]<min_diff_val) { min_diff_val = diff[i]; min_diff_index = i; } //find diff=0 right from diff_min <=> min for (int i=min_diff_index;i<diff.count()-1;i++) if (diff[i]<=0 && diff[i+1]>0) { mini = i; break; } //find diff=0 left from diff_min <=> max for (int i=min_diff_index;i>0;i--) if (diff[i]>=0 && diff[i-1]<0) { maxi = i; break; } // starti=2*maxi-min_diff_index;//double interval // stopi=2*mini-min_diff_index; starti=2*maxi-mini; stopi=2*mini-maxi; } //calculate coefficents to convert index to frequency double kt = (fff-fsf)/data.count(); sff = kt*(stopi)+fsf; ssf = kt*(starti)+fsf; k = (sff-ssf)/data.count(); k2=osc->setch1(data[maxi]); //qDebug()<<1; sleep(1);//TODO: no idea why it dies without this gen->setsweep(ssf,sff); osc->wait("READY"); gen->startsweep(); //qDebug()<<4; osc->wait("READY"); //qDebug()<<5; QByteArray data2 = osc->readcurve(); delete osc; return data2; } float cmeasure::getamplonf(float freq) { gen->setfreq(freq); return vol->acquire(); } float cmeasure::golden(float a, float b, float epsilon, bool max) { //Метод золотого сечения const double phi = 1.61803398874989484; float x1=b-(b-a)/phi; float x2=a+(b-a)/phi; float y1=getamplonf(x1); float y2=getamplonf(x2); while ((b-a)>=epsilon*2) { if ( (y1>y2 && max) || (y1<y2 && !max)) { b=x2; x2=x1; y2=y1; x1=a+b-x2; y1=getamplonf(x1); } else { a=x1; x1=x2; y1=y2; x2=b-(x1-a); y2=getamplonf(x2); } } return (a+b)/2; } void cmeasure::findresonance() { int xmin=0,xmax1=0,xfmax=0,xmax2=0; QByteArray dat; QList<qreal> diff; while ((xfmax <= xmax1)||(xfmax >= xmin)) { dat = sweep(); int fmax=0; for (int i=0; i<dat.count();i++) { if (fmax<dat[i]) { fmax=dat[i]; xfmax=i; } } emit path(dat,QPen(Qt::blue)); emit line(0,0,dat.count(),0,Qt::SolidLine); diff=sm_diff(dat,12); emit path(diff, QPen(Qt::red)); float min=255; float max1=0; float max2=0; for (int i=0;i<dat.count();i++) if (min>diff[i]) { min=diff[i]; xmin=i; } for (int i=0;i<xmin;i++) if (max1<diff[i]) { max1=diff[i]; xmax1=i; } for (int i=xmin;i<dat.count();i++) if (max2<diff[i]) { max2=diff[i]; xmax2=i; } emit line(xmin,0,xmin,-127,Qt::SolidLine); emit line(xmax1,0,xmax1,-127,Qt::SolidLine); emit line(xmax2,0,xmax2,-127,Qt::SolidLine); } for(int i=0; i<dat.count(); i++) { curve<<QPair<double,double>(k*i+ssf, dat[i]*k2); } gen->sweepoff(); #ifdef GOLDEN rf = golden(k*xmax1+newsf,k*xmin+newsf,epsilon,true); #else rf=0; for(int i=xmax1;i<xmin;i++) { if(diff[i]<0) { rf=i; break; } } rf=k*rf+ssf; #endif ra=getamplonf(rf); emit line((rf-ssf)/k,0,(rf-ssf)/k,-127,Qt::SolidLine); #ifdef GOLDEN af = golden(k*xmin+newsf,k*xmax2+newsf,epsilon,false); #else af=0; for(int i=xmin;i<xmax2;i++) { if(diff[i]>0) { af=i; break; } } af=k*af+ssf; #endif aa=getamplonf(af); emit line((af-ssf)/k,0,(af-ssf)/k,-127,Qt::SolidLine); } <commit_msg>changed peak detection algorithm a little. It now calculates median of edge points.<commit_after>#include "measure.h" #include "sleep.h" //TODO: Fix comments... QList<qreal> sm_diff(QByteArray data, int nr)//nr - Depth of smoothing in one direction { QList<qreal> diff; for (int i=0;i<data.count();i++) { if(i<nr || i>=data.count()-nr) { diff<<0; continue; } double a=0; double b=0; for (int k=-nr;k<=nr;k++) { a+=k*data[i+k]-k*data[i+k]/nr; b+=k*k; } diff<<a/b*10; } return diff; } cmeasure::cmeasure(QString oscstr, QString genstr, QString volstr, double sf, double ff, double epsilon, QObject *parent) { connect(this,SIGNAL(path(QList<qreal>,QPen)),parent,SLOT(path(QList<qreal>,QPen)),Qt::QueuedConnection); connect(this,SIGNAL(path(QByteArray,QPen)),parent,SLOT(path(QByteArray,QPen)),Qt::QueuedConnection); connect(this,SIGNAL(line(qreal,qreal,qreal,qreal,QPen)),parent,SLOT(line(qreal,qreal,qreal,qreal,QPen)),Qt::QueuedConnection); this->oscstr=oscstr; gen = new genctrl(genstr); vol = new volctrl(volstr); fsf=sf; fff=ff; this->epsilon=epsilon; findresonance(); } cmeasure::~cmeasure() { delete gen; delete vol; } QByteArray cmeasure::sweep() { osc = new oscctrl((char*)oscstr.toAscii().data()); int mini=0; int maxi=0; int starti, stopi; QByteArray data; while(!(mini>maxi)) { gen->setsweep(fsf,fff); osc->wait("READY"); gen->startsweep(); osc->wait("READY"); data = osc->readcurve(); /* max * _ * / \ * ___/ | _______ * \_/ * min * * /\ _ * --- \ / ------- * \_/ * diff_min/ * */ QList<qreal> diff = sm_diff(data,2); double min_diff_val=0; int min_diff_index; //find diff_min for (int i=0;i<diff.count();i++) if (diff[i]<min_diff_val) { min_diff_val = diff[i]; min_diff_index = i; } //find diff=0 right from diff_min <=> min for (int i=min_diff_index;i<diff.count()-1;i++) if (diff[i]<=0 && diff[i+1]>0) { mini = i; break; } //find diff=0 left from diff_min <=> max for (int i=min_diff_index;i>0;i--) if (diff[i]>=0 && diff[i-1]<0) { maxi = i; break; } // starti=2*maxi-min_diff_index;//double interval // stopi=2*mini-min_diff_index; starti=2*maxi-mini; stopi=2*mini-maxi; } //calculate coefficents to convert index to frequency double kt = (fff-fsf)/data.count(); sff = kt*(stopi)+fsf; ssf = kt*(starti)+fsf; k = (sff-ssf)/data.count(); k2=osc->setch1(data[maxi]); //qDebug()<<1; sleep(1);//TODO: no idea why it dies without this gen->setsweep(ssf,sff); osc->wait("READY"); gen->startsweep(); //qDebug()<<4; osc->wait("READY"); //qDebug()<<5; QByteArray data2 = osc->readcurve(); delete osc; return data2; } float cmeasure::getamplonf(float freq) { gen->setfreq(freq); return vol->acquire(); } float cmeasure::golden(float a, float b, float epsilon, bool max) { //Метод золотого сечения const double phi = 1.61803398874989484; float x1=b-(b-a)/phi; float x2=a+(b-a)/phi; float y1=getamplonf(x1); float y2=getamplonf(x2); while ((b-a)>=epsilon*2) { if ( (y1>y2 && max) || (y1<y2 && !max)) { b=x2; x2=x1; y2=y1; x1=a+b-x2; y1=getamplonf(x1); } else { a=x1; x1=x2; y1=y2; x2=b-(x1-a); y2=getamplonf(x2); } } return (a+b)/2; } void cmeasure::findresonance() { int xmin=0,xmax1=0,xfmax=0,xmax2=0; QByteArray dat; QList<qreal> diff; while ((xfmax <= xmax1)||(xfmax >= xmin)) { dat = sweep(); int fmax=0; for (int i=0; i<dat.count();i++) { if (fmax<dat[i]) { fmax=dat[i]; xfmax=i; } } emit path(dat,QPen(Qt::blue)); emit line(0,0,dat.count(),0,Qt::SolidLine); diff=sm_diff(dat,12); emit path(diff, QPen(Qt::red)); float min=255; float max1=0; float max2=0; for (int i=0;i<dat.count();i++) if (min>diff[i]) { min=diff[i]; xmin=i; } for (int i=0;i<xmin;i++) if (max1<diff[i]) { max1=diff[i]; xmax1=i; } for (int i=xmin;i<dat.count();i++) if (max2<diff[i]) { max2=diff[i]; xmax2=i; } emit line(xmin,0,xmin,-127,Qt::SolidLine); emit line(xmax1,0,xmax1,-127,Qt::SolidLine); emit line(xmax2,0,xmax2,-127,Qt::SolidLine); } for(int i=0; i<dat.count(); i++) { curve<<QPair<double,double>(k*i+ssf, dat[i]*k2); } gen->sweepoff(); #ifdef GOLDEN rf = golden(k*xmax1+newsf,k*xmin+newsf,epsilon,true); #else rf=0; //left to right for(int i=xmax1;i<xmin;i++) { if(diff[i]<0) { rf=(qreal)i/(qreal)2; break; } } //right to left for(int i=xmin;i>xmax1;i--) { if(diff[i]>0) { rf+=(qreal)i/(qreal)2; break; } } /* rf= median of two points closest to edges of * segment xmax1-xmin, where diff changes sign. */ rf=k*rf+ssf; #endif ra=getamplonf(rf); emit line((rf-ssf)/k,0,(rf-ssf)/k,-127,Qt::SolidLine); #ifdef GOLDEN af = golden(k*xmin+newsf,k*xmax2+newsf,epsilon,false); #else af=0; //left to right for(int i=xmin;i<xmax2;i++) { if(diff[i]>0) { af+=(qreal)i/(qreal)2; break; } } //right to left for(int i=xmax2;i>xmin;i--) { if(diff[i]<0) { af+=(qreal)i/(qreal)2; break; } } /* af= median of two points closest to edges of * segment xmin-xmax2, where diff changes sign. */ af=k*af+ssf; #endif aa=getamplonf(af); emit line((af-ssf)/k,0,(af-ssf)/k,-127,Qt::SolidLine); } <|endoftext|>
<commit_before>#include <cstdlib> #include <SimpleIni.h> #include "config.hpp" #include "gui.hpp" namespace GUI { /* Settings */ CSimpleIniA ini(true, false, false); /* Window settings */ int last_window_size = 1; /* Controls settings */ SDL_Scancode KEY_A [] = { SDL_SCANCODE_A, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_B [] = { SDL_SCANCODE_S, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_SELECT[] = { SDL_SCANCODE_SPACE, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_START [] = { SDL_SCANCODE_RETURN, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_UP [] = { SDL_SCANCODE_UP, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_DOWN [] = { SDL_SCANCODE_DOWN, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_LEFT [] = { SDL_SCANCODE_LEFT, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_RIGHT [] = { SDL_SCANCODE_RIGHT, SDL_SCANCODE_ESCAPE }; int BTN_UP [] = { -1, -1 }; int BTN_DOWN [] = { -1, -1 }; int BTN_LEFT [] = { -1, -1 }; int BTN_RIGHT [] = { -1, -1 }; int BTN_A [] = { -1, -1 }; int BTN_B [] = { -1, -1 }; int BTN_SELECT[] = { -1, -1 }; int BTN_START [] = { -1, -1 }; bool useJoystick[] = { false, false }; /* Ensure config directory exists */ const char* get_config_path(char * buf, int buflen) { /* Bail on the complex stuff if we don't need it */ if (!USE_CONFIG_DIR) { return CONFIG_FALLBACK; } /* First, get the home directory */ char homepath[CONFIG_PATH_MAX]; char path[CONFIG_PATH_MAX]; char * home = getenv("HOME"); if (home == NULL) return CONFIG_FALLBACK; snprintf(homepath, sizeof(homepath), "%s/.config", home); /* Then, .config as a folder */ int res = mkdir(homepath, CONFIG_DIR_DEFAULT_MODE); int err = errno; if (res == -1 && err != EEXIST) return CONFIG_FALLBACK; snprintf(path, sizeof(path), "%s/%s", homepath, CONFIG_DIR_NAME); /* Finally, CONFIG_DIR_NAME as a sub-folder */ res = mkdir(path, CONFIG_DIR_DEFAULT_MODE); err = errno; if (res == -1 && err != EEXIST) return CONFIG_FALLBACK; snprintf(buf, buflen, "%s/settings", path); return buf; } /* Load settings */ void load_settings() { /* Files */ char path[CONFIG_PATH_MAX]; ini.LoadFile(get_config_path(path, sizeof(path))); /* Screen settings */ int screen_size = atoi(ini.GetValue("screen", "size", "1")); if (screen_size < 1 || screen_size > 4) screen_size = 1; set_size(screen_size); /* Control settings */ for (int p = 0; p <= 1; p++) { const char* section = (p == 0) ?"controls p1":"controls p2"; useJoystick[p] = (ini.GetValue(section, "usejoy", "no"))[0] == 'y'; if (useJoystick[p]) { BTN_UP[p] = atoi(ini.GetValue(section, "UP", "-1")); BTN_DOWN[p] = atoi(ini.GetValue(section, "DOWN", "-1")); BTN_LEFT[p] = atoi(ini.GetValue(section, "LEFT", "-1")); BTN_RIGHT[p] = atoi(ini.GetValue(section, "RIGHT", "-1")); BTN_A[p] = atoi(ini.GetValue(section, "A", "-1")); BTN_B[p] = atoi(ini.GetValue(section, "B", "-1")); BTN_SELECT[p] = atoi(ini.GetValue(section, "SELECT", "-1")); BTN_START[p] = atoi(ini.GetValue(section, "START", "-1")); } else { KEY_UP[p] = (SDL_Scancode)atoi(ini.GetValue(section, "UP", "82")); KEY_DOWN[p] = (SDL_Scancode)atoi(ini.GetValue(section, "DOWN", "81")); KEY_LEFT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "LEFT", "80")); KEY_RIGHT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "RIGHT", "79")); KEY_A[p] = (SDL_Scancode)atoi(ini.GetValue(section, "A", "4")); KEY_B[p] = (SDL_Scancode)atoi(ini.GetValue(section, "B", "22")); KEY_SELECT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "SELECT", "44")); KEY_START[p] = (SDL_Scancode)atoi(ini.GetValue(section, "START", "40")); } } } /* Save settings */ void save_settings() { /* Screen settings */ char buf[10]; sprintf(buf, "%d", last_window_size); ini.SetValue("screen", "size", buf); /* Control settings */ for (int p = 0; p <= 1; p++) { const char* section = (p == 0) ? "controls p1" : "controls p2"; sprintf(buf, "%d", useJoystick[p] ? BTN_UP[p]:KEY_UP[p]); ini.SetValue(section, "UP", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_DOWN[p]:KEY_DOWN[p]); ini.SetValue(section, "DOWN", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_LEFT[p]:KEY_LEFT[p]); ini.SetValue(section, "LEFT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_RIGHT[p]:KEY_RIGHT[p]); ini.SetValue(section, "RIGHT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_A[p]:KEY_A[p]); ini.SetValue(section, "A", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_B[p]:KEY_B[p]); ini.SetValue(section, "B", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_SELECT[p]:KEY_SELECT[p]); ini.SetValue(section, "SELECT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_START[p]:KEY_START[p]); ini.SetValue(section, "START", buf); ini.SetValue(section, "usejoy", useJoystick[p]? "yes":"no"); } char path[CONFIG_PATH_MAX]; ini.SaveFile(get_config_path(path, sizeof(path))); } } <commit_msg>Minor style changes<commit_after>#include <cstdlib> #include <SimpleIni.h> #include "config.hpp" #include "gui.hpp" namespace GUI { /* Settings */ CSimpleIniA ini(true, false, false); /* Window settings */ int last_window_size = 1; /* Controls settings */ SDL_Scancode KEY_A [] = { SDL_SCANCODE_A, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_B [] = { SDL_SCANCODE_S, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_SELECT[] = { SDL_SCANCODE_SPACE, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_START [] = { SDL_SCANCODE_RETURN, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_UP [] = { SDL_SCANCODE_UP, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_DOWN [] = { SDL_SCANCODE_DOWN, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_LEFT [] = { SDL_SCANCODE_LEFT, SDL_SCANCODE_ESCAPE }; SDL_Scancode KEY_RIGHT [] = { SDL_SCANCODE_RIGHT, SDL_SCANCODE_ESCAPE }; int BTN_UP [] = { -1, -1 }; int BTN_DOWN [] = { -1, -1 }; int BTN_LEFT [] = { -1, -1 }; int BTN_RIGHT [] = { -1, -1 }; int BTN_A [] = { -1, -1 }; int BTN_B [] = { -1, -1 }; int BTN_SELECT[] = { -1, -1 }; int BTN_START [] = { -1, -1 }; bool useJoystick[] = { false, false }; /* Ensure config directory exists */ const char* get_config_path(char* buf, int buflen) { /* Bail on the complex stuff if we don't need it */ if (!USE_CONFIG_DIR) { return CONFIG_FALLBACK; } /* First, get the home directory */ char homepath[CONFIG_PATH_MAX]; char path[CONFIG_PATH_MAX]; char * home = getenv("HOME"); if (home == NULL) return CONFIG_FALLBACK; snprintf(homepath, sizeof(homepath), "%s/.config", home); /* Then, .config as a folder */ int res = mkdir(homepath, CONFIG_DIR_DEFAULT_MODE); int err = errno; if (res == -1 && err != EEXIST) return CONFIG_FALLBACK; snprintf(path, sizeof(path), "%s/%s", homepath, CONFIG_DIR_NAME); /* Finally, CONFIG_DIR_NAME as a sub-folder */ res = mkdir(path, CONFIG_DIR_DEFAULT_MODE); err = errno; if (res == -1 && err != EEXIST) return CONFIG_FALLBACK; snprintf(buf, buflen, "%s/settings", path); return buf; } /* Load settings */ void load_settings() { /* Files */ char path[CONFIG_PATH_MAX]; ini.LoadFile(get_config_path(path, sizeof(path))); /* Screen settings */ int screen_size = atoi(ini.GetValue("screen", "size", "1")); if (screen_size < 1 || screen_size > 4) screen_size = 1; set_size(screen_size); /* Control settings */ for (int p = 0; p <= 1; p++) { const char* section = (p == 0) ? "controls p1" : "controls p2"; useJoystick[p] = (ini.GetValue(section, "usejoy", "no"))[0] == 'y'; if (useJoystick[p]) { BTN_UP[p] = atoi(ini.GetValue(section, "UP", "-1")); BTN_DOWN[p] = atoi(ini.GetValue(section, "DOWN", "-1")); BTN_LEFT[p] = atoi(ini.GetValue(section, "LEFT", "-1")); BTN_RIGHT[p] = atoi(ini.GetValue(section, "RIGHT", "-1")); BTN_A[p] = atoi(ini.GetValue(section, "A", "-1")); BTN_B[p] = atoi(ini.GetValue(section, "B", "-1")); BTN_SELECT[p] = atoi(ini.GetValue(section, "SELECT", "-1")); BTN_START[p] = atoi(ini.GetValue(section, "START", "-1")); } else { KEY_UP[p] = (SDL_Scancode)atoi(ini.GetValue(section, "UP", "82")); KEY_DOWN[p] = (SDL_Scancode)atoi(ini.GetValue(section, "DOWN", "81")); KEY_LEFT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "LEFT", "80")); KEY_RIGHT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "RIGHT", "79")); KEY_A[p] = (SDL_Scancode)atoi(ini.GetValue(section, "A", "4")); KEY_B[p] = (SDL_Scancode)atoi(ini.GetValue(section, "B", "22")); KEY_SELECT[p] = (SDL_Scancode)atoi(ini.GetValue(section, "SELECT", "44")); KEY_START[p] = (SDL_Scancode)atoi(ini.GetValue(section, "START", "40")); } } } /* Save settings */ void save_settings() { /* Screen settings */ char buf[10]; sprintf(buf, "%d", last_window_size); ini.SetValue("screen", "size", buf); /* Control settings */ for (int p = 0; p < 2; p++) { const char* section = (p == 0) ? "controls p1" : "controls p2"; sprintf(buf, "%d", useJoystick[p] ? BTN_UP[p] : KEY_UP[p]); ini.SetValue(section, "UP", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_DOWN[p] : KEY_DOWN[p]); ini.SetValue(section, "DOWN", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_LEFT[p] : KEY_LEFT[p]); ini.SetValue(section, "LEFT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_RIGHT[p] : KEY_RIGHT[p]); ini.SetValue(section, "RIGHT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_A[p] : KEY_A[p]); ini.SetValue(section, "A", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_B[p] : KEY_B[p]); ini.SetValue(section, "B", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_SELECT[p] : KEY_SELECT[p]); ini.SetValue(section, "SELECT", buf); sprintf(buf, "%d", useJoystick[p] ? BTN_START[p] : KEY_START[p]); ini.SetValue(section, "START", buf); ini.SetValue(section, "usejoy", useJoystick[p] ? "yes" : "no"); } char path[CONFIG_PATH_MAX]; ini.SaveFile(get_config_path(path, sizeof(path))); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskd - Task Server // // Copyright 2010 - 2013, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <stdlib.h> #include <ConfigFile.h> #include <Directory.h> #include <taskd.h> #include <text.h> #include <util.h> //////////////////////////////////////////////////////////////////////////////// // taskd config --data <root> [<name> [<value>]] int command_config (Config& config, const std::vector <std::string>& args) { int status = 0; std::string root; std::string name; std::string value; bool verbose = true; bool debug = false; bool nonNull = false; bool confirmation = true; std::vector <std::string>::const_iterator i; for (i = ++(args.begin ()); i != args.end (); ++i) { if (closeEnough ("--quiet", *i, 3)) verbose = false; else if (closeEnough ("--debug", *i, 3)) debug = true; else if (closeEnough ("--data", *i, 3)) root = *(++i); else if (closeEnough ("--force", *i, 3)) confirmation = false; else if (taskd_applyOverride (config, *i)) ; else if (name == "") name = *i; else if (value == "") { nonNull = true; if (value != "") value += ' '; value += *i; } } if (root == "") { char* root_env = getenv ("TASKDDATA"); if (root_env) root = root_env; } Directory root_dir (root); if (!root_dir.exists ()) throw std::string ("ERROR: The '--data' path does not exist."); // Load the config file. config.load (root_dir._data + "/config"); config.set ("root", root_dir._data); // taskd config <name> <value> // - set <name> to <value> if (name != "" && nonNull) { bool change = false; // Read .taskd/config std::vector <std::string> contents; File::read (config._original_file, contents); bool found = false; std::vector <std::string>::iterator line; for (line = contents.begin (); line != contents.end (); ++line) { // If there is a comment on the line, it must follow the pattern. std::string::size_type comment = line->find ("#"); std::string::size_type pos = line->find (name + "="); if (pos != std::string::npos && (comment == std::string::npos || comment > pos)) { found = true; if (!confirmation || confirm (format ("Are you sure you want to change the value of '{1}' from '{2}' to '{3}'?", name, config.get (name), value))) { if (comment != std::string::npos) *line = name + "=" + value + " " + line->substr (comment); else *line = name + "=" + value; change = true; } } } // Not found, so append instead. if (!found && (!confirmation || confirm (format ("Are you sure you want to add '{1}' with a value of '{2}'?", name, value)))) { contents.push_back (name + "=" + value); change = true; } // Write .taskd (or equivalent) if (change) { File::write (config._original_file, contents); std::cout << format ("Config file {1} modified.", config._original_file._data) << "\n"; } else std::cout << "No changes made.\n"; } // taskd config <name> // - remove <name> else if (name != "") { // Read .taskd/config std::vector <std::string> contents; File::read (config._original_file, contents); bool change = false; bool found = false; std::vector <std::string>::iterator line; for (line = contents.begin (); line != contents.end (); ++line) { // If there is a comment on the line, it must follow the pattern. std::string::size_type comment = line->find ("#"); std::string::size_type pos = line->find (name + "="); if (pos != std::string::npos && (comment == std::string::npos || comment > pos)) { found = true; // Remove name if (!confirmation || confirm (format ("Are you sure you want to remove '{1}'?", name))) { *line = ""; change = true; } } } if (!found) throw format ("ERROR: No entry named '{1}' found.", name); // Write .taskd (or equivalent) if (change) { File::write (config._original_file, contents); std::cout << format ("Config file {1} modified.", config._original_file._data) << "\n"; } else std::cout << "No changes made.\n"; } // taskd config // - list all settings. else { std::cout << "\nConfiguration read from " << config._original_file._data << "\n\n"; taskd_renderMap (config, "Variable", "Value"); } return status; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Code Cleanup<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskd - Task Server // // Copyright 2010 - 2013, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <stdlib.h> #include <ConfigFile.h> #include <Directory.h> #include <taskd.h> #include <text.h> #include <util.h> //////////////////////////////////////////////////////////////////////////////// // taskd config --data <root> [<name> [<value>]] int command_config (Config& config, const std::vector <std::string>& args) { int status = 0; std::string root; std::string name; std::string value; bool verbose = true; bool nonNull = false; bool confirmation = true; std::vector <std::string>::const_iterator i; for (i = ++(args.begin ()); i != args.end (); ++i) { if (closeEnough ("--quiet", *i, 3)) verbose = false; else if (closeEnough ("--debug", *i, 3)) ; // TODO Is this necessary? else if (closeEnough ("--data", *i, 3)) root = *(++i); else if (closeEnough ("--force", *i, 3)) confirmation = false; else if (taskd_applyOverride (config, *i)) ; else if (name == "") name = *i; else if (value == "") { nonNull = true; if (value != "") value += ' '; value += *i; } } if (root == "") { char* root_env = getenv ("TASKDDATA"); if (root_env) root = root_env; } Directory root_dir (root); if (!root_dir.exists ()) throw std::string ("ERROR: The '--data' path does not exist."); // Load the config file. config.load (root_dir._data + "/config"); config.set ("root", root_dir._data); // taskd config <name> <value> // - set <name> to <value> if (name != "" && nonNull) { bool change = false; // Read .taskd/config std::vector <std::string> contents; File::read (config._original_file, contents); bool found = false; std::vector <std::string>::iterator line; for (line = contents.begin (); line != contents.end (); ++line) { // If there is a comment on the line, it must follow the pattern. std::string::size_type comment = line->find ("#"); std::string::size_type pos = line->find (name + "="); if (pos != std::string::npos && (comment == std::string::npos || comment > pos)) { found = true; if (!confirmation || confirm (format ("Are you sure you want to change the value of '{1}' from '{2}' to '{3}'?", name, config.get (name), value))) { if (comment != std::string::npos) *line = name + "=" + value + " " + line->substr (comment); else *line = name + "=" + value; change = true; } } } // Not found, so append instead. if (!found && (!confirmation || confirm (format ("Are you sure you want to add '{1}' with a value of '{2}'?", name, value)))) { contents.push_back (name + "=" + value); change = true; } // Write .taskd (or equivalent) if (change) { File::write (config._original_file, contents); if (verbose) std::cout << format ("Config file {1} modified.", config._original_file._data) << "\n"; } else { if (verbose) std::cout << "No changes made.\n"; } } // taskd config <name> // - remove <name> else if (name != "") { // Read .taskd/config std::vector <std::string> contents; File::read (config._original_file, contents); bool change = false; bool found = false; std::vector <std::string>::iterator line; for (line = contents.begin (); line != contents.end (); ++line) { // If there is a comment on the line, it must follow the pattern. std::string::size_type comment = line->find ("#"); std::string::size_type pos = line->find (name + "="); if (pos != std::string::npos && (comment == std::string::npos || comment > pos)) { found = true; // Remove name if (!confirmation || confirm (format ("Are you sure you want to remove '{1}'?", name))) { *line = ""; change = true; } } } if (!found) throw format ("ERROR: No entry named '{1}' found.", name); // Write .taskd (or equivalent) if (change) { File::write (config._original_file, contents); if (verbose) std::cout << format ("Config file {1} modified.", config._original_file._data) << "\n"; } else { if (verbose) std::cout << "No changes made.\n"; } } // taskd config // - list all settings. else { if (verbose) std::cout << "\nConfiguration read from " << config._original_file._data << "\n\n"; taskd_renderMap (config, "Variable", "Value"); } return status; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <dennis@moellegaard.dk> 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 <wx/fileconf.h> #include "config.h" Config appConfig; Config::Config() { } Config::~Config() { } // FIXME - i hate to use this // This is a macro that will allocate and deallocate the wxConfig, since // our app crashes if we let it live too long (for some reason). This // is a temporary hack, which should be fixed ASAP. #define CFG_OP(cfg,op) \ wxFileConfig* cfg = new wxFileConfig(_T("bzlauncher")); \ { op } while(0); \ delete cfg; \ cfg = NULL; wxString Config::getBZFlagCommand(const wxString& proto) const { // first try bzflag/proto (eg bzflag/bzfs0026) // then try bzflag/default wxString key = wxString::Format(_T("bzflag/%s"), proto.Lower().c_str()); wxString cmd; CFG_OP(cfg, if(! cfg->Read(key, &cmd)) { if(! cfg->Read(_T("bzflag/default"), &cmd)) { return _T(""); } } ); return cmd; } void Config::versionCheck() { int version = 0; CFG_OP(cfg, cfg->Read(_T("cfgversion"), &version); // Migrate if needed switch(version) { case 0: { long sortmode = 0; cfg->Read(_T("window/sortmode"), &sortmode); cfg->DeleteEntry(_T("window/sortmode")); cfg->Write(_T("views/0.sortmode"), sortmode); cfg->Write(_T("views/0.query"), _T("`All`")); cfg->Write(_T("cfgversion"), 1); } break; case 1: // Current break; } ); } void Config::setBZFlagCommand(const wxString& cmd, const wxString& proto) { CFG_OP(cfg, cfg->Write(wxString::Format(_T("bzflag/%s"), proto.c_str()), cmd);); } wxRect Config::getWindowDimensions() const { wxRect wanted; CFG_OP(cfg, wanted.x = cfg->Read(_T("window/x"), 10); wanted.y = cfg->Read(_T("window/y"), 10); wanted.width = cfg->Read(_T("window/w"), 600); wanted.height = cfg->Read(_T("window/h"), 600); ); return wanted; } void Config::setWindowDimensions(wxRect r) { CFG_OP(cfg, cfg->Write(_T("window/x"), r.x); cfg->Write(_T("window/y"), r.y); cfg->Write(_T("window/h"), r.height); cfg->Write(_T("window/w"), r.width); ); } wxString Config::getColumnName(ColType t) const { static const wxString names [] = { _T("server"), _T("name"), _T("type"), _T("players"), _T("ping"), _T("favorite") }; return names[t]; } wxString Config::getColumnKey(ColType type) const { wxString key; key += _T("window/col_"); key += this->getColumnName(type); key += _T("_width"); return key; } int Config::getColumnDefaultWidth(ColType t) const { const int widths[] = { 157, 300, 47, 30, 46, 46 }; return widths[t]; } int Config::getColumnWidth(ColType type) const { int w; wxString key = this->getColumnKey(type); CFG_OP(cfg, w = cfg->Read(key, this->getColumnDefaultWidth(type)); ); return w; } void Config::setColumnWidth(ColType type, int w) { wxString key = this->getColumnKey(type); CFG_OP(cfg, cfg->Write(key,w);); } wxArrayString Config::getFavorites() const { wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("favorites/%d"), count), &str)) { list.Add(str); count++; } ); return list; } void Config::setFavorites(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++) cfg->Write(wxString::Format(_T("favorites/%d"), i), list.Item(i)); ); } wxString Config::getListServerURL(int n) const { int count = 0; wxString str; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("listserver/%d"), count), &str)) { if(count == n) return str; count++; } ); if(count == 0 && n == 1) return _T("http://bzstats.strayer.de/stuff/listserver.php"); else return _T("http://my.bzflag.org/db?action=LIST"); } viewlist_t Config::getViews() const { int count = 0; wxString query; long sortmode; viewlist_t list; CFG_OP(cfg, while( cfg->Read(wxString::Format(_T("views/%d.query"), count), &query) && cfg->Read(wxString::Format(_T("views/%d.sortmode"), count), &sortmode) ) { // Read it into serverlist-thingy ServerListView* view = new ServerListView(Query(query), sortmode); list.push_back(view); count++; } ); return list; } void Config::setViews(viewlist_t list) { int count = 0; wxString query; long sortmode; viewlist_t old_list = this->getViews(); CFG_OP(cfg, for(viewlist_t::iterator i = list.begin(); i != list.end(); ++i ) { sortmode = (*i)->currentSortMode; query = (*i)->query.get(); cfg->Write(wxString::Format(_T("views/%d.query"), count), query); cfg->Write(wxString::Format(_T("views/%d.sortmode"), count), sortmode); count++; } for(;count < old_list.size(); count++) { cfg->DeleteEntry(wxString::Format(_T("views/%d.query"), count)); cfg->DeleteEntry(wxString::Format(_T("views/%d.sortmode"), count)); } ); } bool Config::getToolbarVisible() { bool rc = true; CFG_OP(cfg, cfg->Read(_T("window/toolbar"), &rc); ); return rc; } void Config::setToolbarVisible(bool b) { CFG_OP(cfg, cfg->Write(_T("window/toolbar"), b); ); } wxArrayString Config::getRecentServers() const { wxLogDebug(_T("getRecentservers()")); wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("recent/%d"), count), &str)) { wxLogDebug(str); list.Insert(str,0); count++; } ); return list; } void Config::setRecentServers(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++ ) cfg->Write(wxString::Format(_T("recent/%d"), i), list.Item(i)); ); } <commit_msg>If there no views defined in configuration file, then default to two views: All and Recent<commit_after>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <dennis@moellegaard.dk> 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 <wx/fileconf.h> #include "config.h" Config appConfig; Config::Config() { } Config::~Config() { } // FIXME - i hate to use this // This is a macro that will allocate and deallocate the wxConfig, since // our app crashes if we let it live too long (for some reason). This // is a temporary hack, which should be fixed ASAP. #define CFG_OP(cfg,op) \ wxFileConfig* cfg = new wxFileConfig(_T("bzlauncher")); \ { op } while(0); \ delete cfg; \ cfg = NULL; wxString Config::getBZFlagCommand(const wxString& proto) const { // first try bzflag/proto (eg bzflag/bzfs0026) // then try bzflag/default wxString key = wxString::Format(_T("bzflag/%s"), proto.Lower().c_str()); wxString cmd; CFG_OP(cfg, if(! cfg->Read(key, &cmd)) { if(! cfg->Read(_T("bzflag/default"), &cmd)) { return _T(""); } } ); return cmd; } void Config::versionCheck() { int version = 0; CFG_OP(cfg, cfg->Read(_T("cfgversion"), &version); // Migrate if needed switch(version) { case 0: { long sortmode = 0; cfg->Read(_T("window/sortmode"), &sortmode); cfg->DeleteEntry(_T("window/sortmode")); cfg->Write(_T("cfgversion"), 1); } break; case 1: // Current break; } ); } void Config::setBZFlagCommand(const wxString& cmd, const wxString& proto) { CFG_OP(cfg, cfg->Write(wxString::Format(_T("bzflag/%s"), proto.c_str()), cmd);); } wxRect Config::getWindowDimensions() const { wxRect wanted; CFG_OP(cfg, wanted.x = cfg->Read(_T("window/x"), 10); wanted.y = cfg->Read(_T("window/y"), 10); wanted.width = cfg->Read(_T("window/w"), 600); wanted.height = cfg->Read(_T("window/h"), 600); ); return wanted; } void Config::setWindowDimensions(wxRect r) { CFG_OP(cfg, cfg->Write(_T("window/x"), r.x); cfg->Write(_T("window/y"), r.y); cfg->Write(_T("window/h"), r.height); cfg->Write(_T("window/w"), r.width); ); } wxString Config::getColumnName(ColType t) const { static const wxString names [] = { _T("server"), _T("name"), _T("type"), _T("players"), _T("ping"), _T("favorite") }; return names[t]; } wxString Config::getColumnKey(ColType type) const { wxString key; key += _T("window/col_"); key += this->getColumnName(type); key += _T("_width"); return key; } int Config::getColumnDefaultWidth(ColType t) const { const int widths[] = { 157, 300, 47, 30, 46, 46 }; return widths[t]; } int Config::getColumnWidth(ColType type) const { int w; wxString key = this->getColumnKey(type); CFG_OP(cfg, w = cfg->Read(key, this->getColumnDefaultWidth(type)); ); return w; } void Config::setColumnWidth(ColType type, int w) { wxString key = this->getColumnKey(type); CFG_OP(cfg, cfg->Write(key,w);); } wxArrayString Config::getFavorites() const { wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("favorites/%d"), count), &str)) { list.Add(str); count++; } ); return list; } void Config::setFavorites(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++) cfg->Write(wxString::Format(_T("favorites/%d"), i), list.Item(i)); ); } wxString Config::getListServerURL(int n) const { int count = 0; wxString str; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("listserver/%d"), count), &str)) { if(count == n) return str; count++; } ); if(count == 0 && n == 1) return _T("http://bzstats.strayer.de/stuff/listserver.php"); else return _T("http://my.bzflag.org/db?action=LIST"); } viewlist_t Config::getViews() const { int count = 0; wxString query; long sortmode; viewlist_t list; CFG_OP(cfg, while( cfg->Read(wxString::Format(_T("views/%d.query"), count), &query) && cfg->Read(wxString::Format(_T("views/%d.sortmode"), count), &sortmode) ) { // Read it into serverlist-thingy ServerListView* view = new ServerListView(Query(query), sortmode); list.push_back(view); count++; } // Make sure we got at least one view if(list.size() == 0) { ServerListView* viewAll = new ServerListView(Query(_T("All")), sortmode); list.push_back(viewAll); ServerListView* viewRecent = new ServerListView(Query(_T("Recent")), sortmode); list.push_back(viewRecent); } ); return list; } void Config::setViews(viewlist_t list) { int count = 0; wxString query; long sortmode; viewlist_t old_list = this->getViews(); CFG_OP(cfg, for(viewlist_t::iterator i = list.begin(); i != list.end(); ++i ) { sortmode = (*i)->currentSortMode; query = (*i)->query.get(); cfg->Write(wxString::Format(_T("views/%d.query"), count), query); cfg->Write(wxString::Format(_T("views/%d.sortmode"), count), sortmode); count++; } for(;count < old_list.size(); count++) { cfg->DeleteEntry(wxString::Format(_T("views/%d.query"), count)); cfg->DeleteEntry(wxString::Format(_T("views/%d.sortmode"), count)); } ); } bool Config::getToolbarVisible() { bool rc = true; CFG_OP(cfg, cfg->Read(_T("window/toolbar"), &rc); ); return rc; } void Config::setToolbarVisible(bool b) { CFG_OP(cfg, cfg->Write(_T("window/toolbar"), b); ); } wxArrayString Config::getRecentServers() const { wxLogDebug(_T("getRecentservers()")); wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("recent/%d"), count), &str)) { wxLogDebug(str); list.Insert(str,0); count++; } ); return list; } void Config::setRecentServers(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++ ) cfg->Write(wxString::Format(_T("recent/%d"), i), list.Item(i)); ); } <|endoftext|>
<commit_before>struct Point { int x; int y; }; struct Base1 { int b1; }; struct Base2 { int b2; }; struct DerivedSI : Base1 { int dsi; }; struct DerivedMI : Base1, Base2 { int dmi; }; struct DerivedVI : virtual Base1 { int dvi; }; void Locals() { Point pt = { //$ussa=pt 1, //$ussa=pt[0..4)<int> 2 //$ussa=pt[4..8)<int> }; int i = pt.x; //$ussa=pt[0..4)<int> i = pt.y; //$ussa=pt[4..8)<int> int* p = &pt.x; i = *p; //$ussa=pt[0..4)<int> p = &pt.y; i = *p; //$ussa=pt[4..8)<int> } void PointsTo( int a, //$raw,ussa=a Point& b, //$raw,ussa=b ussa=*b Point* c, //$raw,ussa=c ussa=*c int* d, //$raw,ussa=d ussa=*d DerivedSI* e, //$raw,ussa=e ussa=*e DerivedMI* f, //$raw,ussa=f ussa=*f DerivedVI* g //$raw,ussa=g ussa=*g ) { int i = a; //$raw,ussa=a i = *&a; //$raw,ussa=a i = *(&a + 0); //$raw,ussa=a i = b.x; //$raw,ussa=b ussa=*b[0..4)<int> i = b.y; //$raw,ussa=b ussa=*b[4..8)<int> i = c->x; //$raw,ussa=c ussa=*c[0..4)<int> i = c->y; //$raw,ussa=c ussa=*c[4..8)<int> i = *d; //$raw,ussa=d ussa=*d[0..4)<int> i = *(d + 0); //$raw,ussa=d ussa=*d[0..4)<int> i = d[5]; //$raw,ussa=d ussa=*d[20..24)<int> i = 5[d]; //$raw,ussa=d ussa=*d[20..24)<int> i = d[a]; //$raw,ussa=d raw,ussa=a ussa=*d[?..?)<int> i = a[d]; //$raw,ussa=d raw,ussa=a ussa=*d[?..?)<int> int* p = &b.x; //$raw,ussa=b i = *p; //$ussa=*b[0..4)<int> p = &b.y; //$raw,ussa=b i = *p; //$ussa=*b[4..8)<int> p = &c->x; //$raw,ussa=c i = *p; //$ussa=*c[0..4)<int> p = &c->y; //$raw,ussa=c i = *p; //$ussa=*c[4..8)<int> p = &d[5]; //$raw,ussa=d i = *p; //$ussa=*d[20..24)<int> p = &d[a]; //$raw,ussa=d raw,ussa=a i = *p; //$ussa=*d[?..?)<int> Point* q = &c[a]; //$raw,ussa=c raw,ussa=a i = q->x; //$ussa=*c[?..?)<int> i = q->y; //$ussa=*c[?..?)<int> i = e->b1; //$raw,ussa=e ussa=*e[0..4)<int> i = e->dsi; //$raw,ussa=e ussa=*e[4..8)<int> i = f->b1; //$raw,ussa=f ussa=*f[0..4)<int> i = f->b2; //$raw,ussa=f ussa=*f[4..8)<int> i = f->dmi; //$raw,ussa=f ussa=*f[8..12)<int> i = g->b1; //$raw,ussa=g ussa=*g[?..?)<int> i = g->dvi; //$raw,ussa=g ussa=*g[8..12)<int> }<commit_msg>C++: remove points-to expectations for reused SSA<commit_after>struct Point { int x; int y; }; struct Base1 { int b1; }; struct Base2 { int b2; }; struct DerivedSI : Base1 { int dsi; }; struct DerivedMI : Base1, Base2 { int dmi; }; struct DerivedVI : virtual Base1 { int dvi; }; void Locals() { Point pt = { //$ussa=pt 1, //$ussa=pt[0..4)<int> 2 //$ussa=pt[4..8)<int> }; int i = pt.x; //$ussa=pt[0..4)<int> i = pt.y; //$ussa=pt[4..8)<int> int* p = &pt.x; i = *p; //$ussa=pt[0..4)<int> p = &pt.y; i = *p; //$ussa=pt[4..8)<int> } void PointsTo( int a, //$raw=a Point& b, //$raw=b ussa=*b Point* c, //$raw=c ussa=*c int* d, //$raw=d ussa=*d DerivedSI* e, //$raw=e ussa=*e DerivedMI* f, //$raw=f ussa=*f DerivedVI* g //$raw=g ussa=*g ) { int i = a; //$raw=a i = *&a; //$raw=a i = *(&a + 0); //$raw=a i = b.x; //$raw=b ussa=*b[0..4)<int> i = b.y; //$raw=b ussa=*b[4..8)<int> i = c->x; //$raw=c ussa=*c[0..4)<int> i = c->y; //$raw=c ussa=*c[4..8)<int> i = *d; //$raw=d ussa=*d[0..4)<int> i = *(d + 0); //$raw=d ussa=*d[0..4)<int> i = d[5]; //$raw=d ussa=*d[20..24)<int> i = 5[d]; //$raw=d ussa=*d[20..24)<int> i = d[a]; //$raw=d raw=a ussa=*d[?..?)<int> i = a[d]; //$raw=d raw=a ussa=*d[?..?)<int> int* p = &b.x; //$raw=b i = *p; //$ussa=*b[0..4)<int> p = &b.y; //$raw=b i = *p; //$ussa=*b[4..8)<int> p = &c->x; //$raw=c i = *p; //$ussa=*c[0..4)<int> p = &c->y; //$raw=c i = *p; //$ussa=*c[4..8)<int> p = &d[5]; //$raw=d i = *p; //$ussa=*d[20..24)<int> p = &d[a]; //$raw=d raw=a i = *p; //$ussa=*d[?..?)<int> Point* q = &c[a]; //$raw=c raw=a i = q->x; //$ussa=*c[?..?)<int> i = q->y; //$ussa=*c[?..?)<int> i = e->b1; //$raw=e ussa=*e[0..4)<int> i = e->dsi; //$raw=e ussa=*e[4..8)<int> i = f->b1; //$raw=f ussa=*f[0..4)<int> i = f->b2; //$raw=f ussa=*f[4..8)<int> i = f->dmi; //$raw=f ussa=*f[8..12)<int> i = g->b1; //$raw=g ussa=*g[?..?)<int> i = g->dvi; //$raw=g ussa=*g[8..12)<int> }<|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * 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 <inviwopy/pypickingmapper.h> #include <inviwo/core/interaction/pickingmapper.h> #include <inviwo/core/interaction/pickingstate.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/processors/processor.h> #include <pybind11/stl.h> #include <pybind11/functional.h> namespace inviwo { void exposePickingMapper(pybind11::module &m) { namespace py = pybind11; py::enum_<PickingState>(m, "PickingState") .value("None", PickingState::None) .value("Started", PickingState::Started) .value("Updated", PickingState::Updated) .value("Finished", PickingState::Finished); py::class_<PickingEvent>(m, "PickingEvent") .def_property_readonly("pickedId", &PickingEvent::getPickedId) .def_property_readonly("position", &PickingEvent::getPosition) .def_property_readonly("depth", &PickingEvent::getDepth) .def_property_readonly("previousPosition", &PickingEvent::getPreviousPosition) .def_property_readonly("previousDepth", &PickingEvent::getPreviousDepth) .def_property_readonly("pressedPosition", &PickingEvent::getPressedPosition) .def_property_readonly("pressedDepth", &PickingEvent::getPressedDepth) .def_property_readonly("deltaPosition", &PickingEvent::getDeltaPosition) .def_property_readonly("deltaDepth", &PickingEvent::getDeltaDepth) .def_property_readonly("deltaPressedPosition", &PickingEvent::getDeltaPressedPosition) .def_property_readonly("deltaPressedDepth", &PickingEvent::getDeltaPressedDepth) .def_property_readonly("ndc", &PickingEvent::getNDC) .def_property_readonly("previousNDC", &PickingEvent::getPreviousNDC) .def_property_readonly("pressedNDC", &PickingEvent::getPressedNDC) .def_property_readonly("canvasSize", &PickingEvent::getCanvasSize) .def_property_readonly("state", &PickingEvent::getState) .def_property("used", &PickingEvent::hasBeenUsed, [](PickingEvent *e, bool used) { if (used) { e->markAsUsed(); } else { e->markAsUnused(); } }) .def("markkAsUsed", &PickingEvent::markAsUsed) .def("markkAsUnused", &PickingEvent::markAsUnused); py::class_<PickingMapper>(m, "PickingMapper") .def(py::init([](Processor *p, size_t size, pybind11::function callback) { return new PickingMapper(p, size, [callback](PickingEvent *e) { callback(py::cast(e)); }); })) .def("resize", &PickingMapper::resize) .def_property("enabled", &PickingMapper::isEnabled, &PickingMapper::setEnabled) .def("pickingId", &PickingMapper::getPickingId) .def_property_readonly("color", &PickingMapper::getColor) .def_property("size", &PickingMapper::getSize, &PickingMapper::resize); } } // namespace inviwo <commit_msg>added picking event enums and methods<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * 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 <inviwopy/pypickingmapper.h> #include <inviwo/core/interaction/pickingmapper.h> #include <inviwo/core/interaction/pickingstate.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/processors/processor.h> #include <pybind11/stl.h> #include <pybind11/functional.h> namespace inviwo { void exposePickingMapper(pybind11::module &m) { namespace py = pybind11; py::enum_<PickingState>(m, "PickingState") .value("None", PickingState::None) .value("Started", PickingState::Started) .value("Updated", PickingState::Updated) .value("Finished", PickingState::Finished); py::enum_<PickingPressState>(m, "PickingPressState") .value("DoubleClick", PickingPressState::DoubleClick) .value("Move", PickingPressState::Move) .value("None", PickingPressState::None) .value("Press", PickingPressState::Press) .value("Release", PickingPressState::Release); py::enum_<PickingPressItem>(m, "PickingPressItem") .value("None", PickingPressItem::None) .value("Primary", PickingPressItem::Primary) .value("Secondary", PickingPressItem::Secondary) .value("Tertiary", PickingPressItem::Tertiary); py::enum_<PickingHoverState>(m, "PickingHoverState") .value("Enter", PickingHoverState::Enter) .value("Exit", PickingHoverState::Exit) .value("Move", PickingHoverState::Move) .value("None", PickingHoverState::None); py::class_<PickingEvent>(m, "PickingEvent") .def_property_readonly("pickedId", &PickingEvent::getPickedId) .def_property_readonly("globalPickingId", &PickingEvent::getGlobalPickingId) .def_property_readonly("currentGlobalPickingId", &PickingEvent::getCurrentGlobalPickingId) .def_property_readonly("currentLocalPickingId", &PickingEvent::getCurrentLocalPickingId) .def_property_readonly("position", &PickingEvent::getPosition) .def_property_readonly("depth", &PickingEvent::getDepth) .def_property_readonly("previousGlobalPickingId", &PickingEvent::getPreviousGlobalPickingId) .def_property_readonly("previousLocalPickingId", &PickingEvent::getPreviousLocalPickingId) .def_property_readonly("previousPosition", &PickingEvent::getPreviousPosition) .def_property_readonly("previousDepth", &PickingEvent::getPreviousDepth) .def_property_readonly("pressedGlobalPickingId", &PickingEvent::getPressedGlobalPickingId) .def_property_readonly("pressedLocalPickingId", &PickingEvent::getPressedLocalPickingId) .def_property_readonly("pressedPosition", &PickingEvent::getPressedPosition) .def_property_readonly("pressedDepth", &PickingEvent::getPressedDepth) .def_property_readonly("deltaPosition", &PickingEvent::getDeltaPosition) .def_property_readonly("deltaDepth", &PickingEvent::getDeltaDepth) .def_property_readonly("deltaPressedPosition", &PickingEvent::getDeltaPressedPosition) .def_property_readonly("deltaPressedDepth", &PickingEvent::getDeltaPressedDepth) .def_property_readonly("ndc", &PickingEvent::getNDC) .def_property_readonly("previousNDC", &PickingEvent::getPreviousNDC) .def_property_readonly("pressedNDC", &PickingEvent::getPressedNDC) .def_property_readonly("canvasSize", &PickingEvent::getCanvasSize) .def_property_readonly("state", &PickingEvent::getState) .def_property_readonly("pressState", &PickingEvent::getPressState) .def_property_readonly("pressItem", &PickingEvent::getPressItem) .def_property_readonly("pressItems", &PickingEvent::getPressItems) .def_property_readonly("hoverState", &PickingEvent::getHoverState) .def_property("used", &PickingEvent::hasBeenUsed, [](PickingEvent *e, bool used) { if (used) { e->markAsUsed(); } else { e->markAsUnused(); } }) .def("markkAsUsed", &PickingEvent::markAsUsed) .def("markkAsUnused", &PickingEvent::markAsUnused); py::class_<PickingMapper>(m, "PickingMapper") .def(py::init([](Processor *p, size_t size, pybind11::function callback) { return new PickingMapper(p, size, [callback](PickingEvent *e) { callback(py::cast(e)); }); })) .def("resize", &PickingMapper::resize) .def_property("enabled", &PickingMapper::isEnabled, &PickingMapper::setEnabled) .def("pickingId", &PickingMapper::getPickingId) .def_property_readonly("color", &PickingMapper::getColor) .def_property("size", &PickingMapper::getSize, &PickingMapper::resize); } } // namespace inviwo <|endoftext|>
<commit_before>#pragma once #include <memory> #include "Runtime/CToken.hpp" #include "Runtime/RetroTypes.hpp" #include "Runtime/Character/CAnimData.hpp" #include "Runtime/Graphics/CModel.hpp" #include <zeus/CAABox.hpp> #include <zeus/CColor.hpp> #include <zeus/CVector3f.hpp> namespace urde { class CActorLights; class CAnimData; class CCharAnimTime; class CModel; class CRandom16; class CSkinnedModel; class CStateManager; struct CModelFlags; struct SAdvancementDeltas; class CStaticRes { CAssetId x0_cmdlId = 0; zeus::CVector3f x4_scale; public: constexpr CStaticRes() = default; CStaticRes(CAssetId id, const zeus::CVector3f& scale) : x0_cmdlId(id), x4_scale(scale) {} CAssetId GetId() const { return x0_cmdlId; } const zeus::CVector3f& GetScale() const { return x4_scale; } explicit operator bool() const { return x0_cmdlId.IsValid(); } }; class CAnimRes { CAssetId x0_ancsId; s32 x4_charIdx = -1; zeus::CVector3f x8_scale; bool x14_canLoop = false; /* NOTE: x18_bodyType - Removed in retail */ s32 x18_defaultAnim = -1; /* NOTE: used to be x1c in demo */ public: CAnimRes() = default; CAnimRes(CAssetId ancs, s32 charIdx, const zeus::CVector3f& scale, const s32 defaultAnim, bool loop) : x0_ancsId(ancs), x4_charIdx(charIdx), x8_scale(scale), x14_canLoop(loop), x18_defaultAnim(defaultAnim) {} CAssetId GetId() const { return x0_ancsId; } s32 GetCharacterNodeId() const { return x4_charIdx; } void SetCharacterNodeId(s32 id) { x4_charIdx = id; } const zeus::CVector3f& GetScale() const { return x8_scale; } bool CanLoop() const { return x14_canLoop; } void SetCanLoop(bool l) { x14_canLoop = l; } s32 GetDefaultAnim() const { return x18_defaultAnim; } void SetDefaultAnim(s32 anim) { x18_defaultAnim = anim; } }; class CModelData { friend class CActor; zeus::CVector3f x0_scale; bool xc_ = false; std::unique_ptr<CAnimData> x10_animData; union { struct { bool x14_24_renderSorted : 1; bool x14_25_sortThermal : 1; }; u32 _flags = 0; }; zeus::CColor x18_ambientColor; TLockedToken<CModel> x1c_normalModel; TLockedToken<CModel> x2c_xrayModel; TLockedToken<CModel> x3c_infraModel; std::unique_ptr<CBooModel> m_normalModelInst; std::unique_ptr<CBooModel> m_xrayModelInst; std::unique_ptr<CBooModel> m_infraModelInst; int m_drawInstCount = 0; public: enum class EWhichModel { Normal, XRay, Thermal, ThermalHot }; void SetSortThermal(bool v) { x14_25_sortThermal = v; } bool GetSortThermal() const { return x14_25_sortThermal; } ~CModelData(); explicit CModelData(const CStaticRes& res, int instCount = 1); explicit CModelData(const CAnimRes& res, int instCount = 1); CModelData(CModelData&&) = default; CModelData& operator=(CModelData&&) = default; CModelData(); static CModelData CModelDataNull(); SAdvancementDeltas GetAdvancementDeltas(const CCharAnimTime& a, const CCharAnimTime& b) const; void Render(const CStateManager& stateMgr, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; bool IsLoaded(int shaderIdx) const; static EWhichModel GetRenderingModel(const CStateManager& stateMgr); CSkinnedModel& PickAnimatedModel(EWhichModel which) const; const std::unique_ptr<CBooModel>& PickStaticModel(EWhichModel which) const; void SetXRayModel(const std::pair<CAssetId, CAssetId>& modelSkin); void SetInfraModel(const std::pair<CAssetId, CAssetId>& modelSkin); bool IsDefinitelyOpaque(EWhichModel) const; bool GetIsLoop() const; float GetAnimationDuration(int) const; void EnableLooping(bool); void AdvanceParticles(const zeus::CTransform& xf, float, CStateManager& stateMgr); zeus::CAABox GetBounds() const; zeus::CAABox GetBounds(const zeus::CTransform& xf) const; zeus::CTransform GetScaledLocatorTransformDynamic(std::string_view name, const CCharAnimTime* time) const; zeus::CTransform GetScaledLocatorTransform(std::string_view name) const; zeus::CTransform GetLocatorTransformDynamic(std::string_view name, const CCharAnimTime* time) const; zeus::CTransform GetLocatorTransform(std::string_view name) const; SAdvancementDeltas AdvanceAnimationIgnoreParticles(float dt, CRandom16&, bool advTree); SAdvancementDeltas AdvanceAnimation(float dt, CStateManager& stateMgr, TAreaId aid, bool advTree); bool IsAnimating() const; bool IsInFrustum(const zeus::CTransform& xf, const zeus::CFrustum& frustum) const; void RenderParticles(const zeus::CFrustum& frustum) const; void Touch(EWhichModel, int shaderIdx) const; void Touch(const CStateManager& stateMgr, int shaderIdx) const; void RenderThermal(const zeus::CColor& mulColor, const zeus::CColor& addColor, const CModelFlags& flags) const; void RenderThermal(const zeus::CTransform& xf, const zeus::CColor& mulColor, const zeus::CColor& addColor, const CModelFlags& flags) const; void RenderUnsortedParts(EWhichModel, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; void Render(EWhichModel, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; void InvSuitDraw(EWhichModel which, const zeus::CTransform& xf, const CActorLights* lights, const zeus::CColor& color0, const zeus::CColor& color1); void DisintegrateDraw(const CStateManager& mgr, const zeus::CTransform& xf, const CTexture& tex, const zeus::CColor& addColor, float t); void DisintegrateDraw(EWhichModel which, const zeus::CTransform& xf, const CTexture& tex, const zeus::CColor& addColor, float t); CAnimData* GetAnimationData() { return x10_animData.get(); } const CAnimData* GetAnimationData() const { return x10_animData.get(); } const TLockedToken<CModel>& GetNormalModel() const { return x1c_normalModel; } const TLockedToken<CModel>& GetXRayModel() const { return x2c_xrayModel; } const TLockedToken<CModel>& GetThermalModel() const { return x3c_infraModel; } bool IsNull() const { return !x10_animData && !x1c_normalModel; } u32 GetNumMaterialSets() const; const zeus::CVector3f& GetScale() const { return x0_scale; } void SetScale(const zeus::CVector3f& scale) { x0_scale = scale; } bool HasAnimData() const { return x10_animData != nullptr; } bool HasNormalModel() const { return x1c_normalModel.HasReference(); } bool HasModel(EWhichModel which) const { if (x10_animData) { switch (which) { case EWhichModel::Normal: return true; case EWhichModel::XRay: return x10_animData->GetXRayModel() != nullptr; case EWhichModel::Thermal: return x10_animData->GetInfraModel() != nullptr; default: return false; } } switch (which) { case EWhichModel::Normal: return x1c_normalModel.HasReference(); case EWhichModel::XRay: return x2c_xrayModel.HasReference(); case EWhichModel::Thermal: return x3c_infraModel.HasReference(); default: return false; } } }; } // namespace urde <commit_msg>CModelData: Give all function prototype parameters names<commit_after>#pragma once #include <memory> #include "Runtime/CToken.hpp" #include "Runtime/RetroTypes.hpp" #include "Runtime/Character/CAnimData.hpp" #include "Runtime/Graphics/CModel.hpp" #include <zeus/CAABox.hpp> #include <zeus/CColor.hpp> #include <zeus/CVector3f.hpp> namespace urde { class CActorLights; class CAnimData; class CCharAnimTime; class CModel; class CRandom16; class CSkinnedModel; class CStateManager; struct CModelFlags; struct SAdvancementDeltas; class CStaticRes { CAssetId x0_cmdlId = 0; zeus::CVector3f x4_scale; public: constexpr CStaticRes() = default; CStaticRes(CAssetId id, const zeus::CVector3f& scale) : x0_cmdlId(id), x4_scale(scale) {} CAssetId GetId() const { return x0_cmdlId; } const zeus::CVector3f& GetScale() const { return x4_scale; } explicit operator bool() const { return x0_cmdlId.IsValid(); } }; class CAnimRes { CAssetId x0_ancsId; s32 x4_charIdx = -1; zeus::CVector3f x8_scale; bool x14_canLoop = false; /* NOTE: x18_bodyType - Removed in retail */ s32 x18_defaultAnim = -1; /* NOTE: used to be x1c in demo */ public: CAnimRes() = default; CAnimRes(CAssetId ancs, s32 charIdx, const zeus::CVector3f& scale, const s32 defaultAnim, bool loop) : x0_ancsId(ancs), x4_charIdx(charIdx), x8_scale(scale), x14_canLoop(loop), x18_defaultAnim(defaultAnim) {} CAssetId GetId() const { return x0_ancsId; } s32 GetCharacterNodeId() const { return x4_charIdx; } void SetCharacterNodeId(s32 id) { x4_charIdx = id; } const zeus::CVector3f& GetScale() const { return x8_scale; } bool CanLoop() const { return x14_canLoop; } void SetCanLoop(bool loop) { x14_canLoop = loop; } s32 GetDefaultAnim() const { return x18_defaultAnim; } void SetDefaultAnim(s32 anim) { x18_defaultAnim = anim; } }; class CModelData { friend class CActor; zeus::CVector3f x0_scale; bool xc_ = false; std::unique_ptr<CAnimData> x10_animData; union { struct { bool x14_24_renderSorted : 1; bool x14_25_sortThermal : 1; }; u32 _flags = 0; }; zeus::CColor x18_ambientColor; TLockedToken<CModel> x1c_normalModel; TLockedToken<CModel> x2c_xrayModel; TLockedToken<CModel> x3c_infraModel; std::unique_ptr<CBooModel> m_normalModelInst; std::unique_ptr<CBooModel> m_xrayModelInst; std::unique_ptr<CBooModel> m_infraModelInst; int m_drawInstCount = 0; public: enum class EWhichModel { Normal, XRay, Thermal, ThermalHot }; void SetSortThermal(bool sort) { x14_25_sortThermal = sort; } bool GetSortThermal() const { return x14_25_sortThermal; } ~CModelData(); explicit CModelData(const CStaticRes& res, int instCount = 1); explicit CModelData(const CAnimRes& res, int instCount = 1); CModelData(CModelData&&) = default; CModelData& operator=(CModelData&&) = default; CModelData(); static CModelData CModelDataNull(); SAdvancementDeltas GetAdvancementDeltas(const CCharAnimTime& a, const CCharAnimTime& b) const; void Render(const CStateManager& stateMgr, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; bool IsLoaded(int shaderIdx) const; static EWhichModel GetRenderingModel(const CStateManager& stateMgr); CSkinnedModel& PickAnimatedModel(EWhichModel which) const; const std::unique_ptr<CBooModel>& PickStaticModel(EWhichModel which) const; void SetXRayModel(const std::pair<CAssetId, CAssetId>& modelSkin); void SetInfraModel(const std::pair<CAssetId, CAssetId>& modelSkin); bool IsDefinitelyOpaque(EWhichModel) const; bool GetIsLoop() const; float GetAnimationDuration(int idx) const; void EnableLooping(bool enable); void AdvanceParticles(const zeus::CTransform& xf, float dt, CStateManager& stateMgr); zeus::CAABox GetBounds() const; zeus::CAABox GetBounds(const zeus::CTransform& xf) const; zeus::CTransform GetScaledLocatorTransformDynamic(std::string_view name, const CCharAnimTime* time) const; zeus::CTransform GetScaledLocatorTransform(std::string_view name) const; zeus::CTransform GetLocatorTransformDynamic(std::string_view name, const CCharAnimTime* time) const; zeus::CTransform GetLocatorTransform(std::string_view name) const; SAdvancementDeltas AdvanceAnimationIgnoreParticles(float dt, CRandom16& rand, bool advTree); SAdvancementDeltas AdvanceAnimation(float dt, CStateManager& stateMgr, TAreaId aid, bool advTree); bool IsAnimating() const; bool IsInFrustum(const zeus::CTransform& xf, const zeus::CFrustum& frustum) const; void RenderParticles(const zeus::CFrustum& frustum) const; void Touch(EWhichModel, int shaderIdx) const; void Touch(const CStateManager& stateMgr, int shaderIdx) const; void RenderThermal(const zeus::CColor& mulColor, const zeus::CColor& addColor, const CModelFlags& flags) const; void RenderThermal(const zeus::CTransform& xf, const zeus::CColor& mulColor, const zeus::CColor& addColor, const CModelFlags& flags) const; void RenderUnsortedParts(EWhichModel, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; void Render(EWhichModel, const zeus::CTransform& xf, const CActorLights* lights, const CModelFlags& drawFlags) const; void InvSuitDraw(EWhichModel which, const zeus::CTransform& xf, const CActorLights* lights, const zeus::CColor& color0, const zeus::CColor& color1); void DisintegrateDraw(const CStateManager& mgr, const zeus::CTransform& xf, const CTexture& tex, const zeus::CColor& addColor, float t); void DisintegrateDraw(EWhichModel which, const zeus::CTransform& xf, const CTexture& tex, const zeus::CColor& addColor, float t); CAnimData* GetAnimationData() { return x10_animData.get(); } const CAnimData* GetAnimationData() const { return x10_animData.get(); } const TLockedToken<CModel>& GetNormalModel() const { return x1c_normalModel; } const TLockedToken<CModel>& GetXRayModel() const { return x2c_xrayModel; } const TLockedToken<CModel>& GetThermalModel() const { return x3c_infraModel; } bool IsNull() const { return !x10_animData && !x1c_normalModel; } u32 GetNumMaterialSets() const; const zeus::CVector3f& GetScale() const { return x0_scale; } void SetScale(const zeus::CVector3f& scale) { x0_scale = scale; } bool HasAnimData() const { return x10_animData != nullptr; } bool HasNormalModel() const { return x1c_normalModel.HasReference(); } bool HasModel(EWhichModel which) const { if (x10_animData) { switch (which) { case EWhichModel::Normal: return true; case EWhichModel::XRay: return x10_animData->GetXRayModel() != nullptr; case EWhichModel::Thermal: return x10_animData->GetInfraModel() != nullptr; default: return false; } } switch (which) { case EWhichModel::Normal: return x1c_normalModel.HasReference(); case EWhichModel::XRay: return x2c_xrayModel.HasReference(); case EWhichModel::Thermal: return x3c_infraModel.HasReference(); default: return false; } } }; } // namespace urde <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libpagemaker project. * * 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 <cstdio> #include <libpagemaker/libpagemaker.h> #include <boost/scoped_ptr.hpp> #include "PMDCollector.h" #include "PMDParser.h" #include "libpagemaker_utils.h" namespace libpagemaker { bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try { // TODO: Fix this. return true; } catch (...) { return false; } bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter) { PMDCollector collector; PMD_DEBUG_MSG(("About to start parsing...\n")); boost::scoped_ptr<librevenge::RVNGInputStream> pmdStream(input->getSubStreamByName("PageMaker")); PMDParser(pmdStream.get(), &collector).parse(); PMD_DEBUG_MSG(("About to start drawing...\n")); collector.draw(painter); return true; } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>PMDocument::parse can never throw<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libpagemaker project. * * 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 <cstdio> #include <libpagemaker/libpagemaker.h> #include <boost/scoped_ptr.hpp> #include "PMDCollector.h" #include "PMDParser.h" #include "libpagemaker_utils.h" namespace libpagemaker { bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try { // TODO: Fix this. return true; } catch (...) { return false; } bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter) try { PMDCollector collector; PMD_DEBUG_MSG(("About to start parsing...\n")); boost::scoped_ptr<librevenge::RVNGInputStream> pmdStream(input->getSubStreamByName("PageMaker")); PMDParser(pmdStream.get(), &collector).parse(); PMD_DEBUG_MSG(("About to start drawing...\n")); collector.draw(painter); return true; } catch (...) { return false; } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>/* * Copyright (C) 2018-2021 Nagisa Sekiguchi * * 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 "frontend.h" #include <cerrno> namespace ydsh { // ###################### // ## FrontEnd ## // ###################### static auto wrapModLoadingError(const Node &node, const char *path, ModLoadingError e) { if (e.isCircularLoad()) { return createTCError<CircularMod>(node, path); } else if (e.isFileNotFound()) { return createTCError<NotFoundMod>(node, path); } else { return createTCError<NotOpenMod>(node, path, strerror(e.getErrNo())); } } FrontEnd::FrontEnd(ModuleProvider &provider, std::unique_ptr<Context> &&ctx, FrontEndOption option) : provider(provider), option(option) { this->contexts.push_back(std::move(ctx)); this->curScope()->clearLocalSize(); } std::unique_ptr<Node> FrontEnd::tryToParse() { std::unique_ptr<Node> node; if (this->parser()) { node = this->parser()(); if (this->parser().hasError()) { this->listener &&this->listener->handleParseError(this->contexts, this->parser().getError()); } else if (this->uastDumper) { this->uastDumper(*node); } } return node; } bool FrontEnd::tryToCheckType(std::unique_ptr<Node> &node) { if (hasFlag(this->option, FrontEndOption::PARSE_ONLY)) { return true; } node = this->checker()(this->prevType, std::move(node), this->curScope()); this->prevType = &node->getType(); if (this->checker().hasError()) { auto &errors = this->checker().getErrors(); if (this->listener) { for (size_t i = 0; i < errors.size(); i++) { this->listener->handleTypeError(this->contexts, errors[i], i == 0); } } if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY) && !this->checker().hasReachedCompNode()) { return true; } return false; } else if (this->astDumper) { this->astDumper(*node); } return true; } FrontEndResult FrontEnd::operator()() { do { // load module auto ret = this->enterModule(); if (!ret || ret.kind == FrontEndResult::Kind::ENTER_MODULE) { return ret; } // parse if (!ret.node) { ret.node = this->tryToParse(); if (this->parser().hasError()) { return FrontEndResult::failed(); } } if (!ret.node) { // when parse reach EOS ret.node = this->exitModule(); } // check type if (!this->tryToCheckType(ret.node)) { return FrontEndResult::failed(); } if (isa<SourceListNode>(*ret.node)) { auto &src = cast<SourceListNode>(*ret.node); if (!src.getPathList().empty()) { this->getCurSrcListNode().reset(cast<SourceListNode>(ret.node.release())); continue; } } if (isa<SourceNode>(*ret.node) && cast<SourceNode>(*ret.node).isFirstAppear()) { ret.kind = FrontEndResult::Kind::EXIT_MODULE; } return ret; } while (true); } void FrontEnd::setupASTDump() { if (this->uastDumper) { this->uastDumper->initialize(this->getCurrentLexer()->getSourceName(), "### dump untyped AST ###"); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->initialize(this->getCurrentLexer()->getSourceName(), "### dump typed AST ###"); } } void FrontEnd::teardownASTDump() { if (this->uastDumper) { this->uastDumper->finalize(*this->curScope()); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->finalize(*this->curScope()); } } FrontEndResult FrontEnd::enterModule() { if (!this->hasUnconsumedPath()) { this->getCurSrcListNode().reset(); return FrontEndResult::inModule(nullptr); } auto &node = *this->getCurSrcListNode(); unsigned int pathIndex = node.getCurIndex(); const char *modPath = node.getPathList()[pathIndex]->c_str(); node.setCurIndex(pathIndex + 1); const char *scriptDir = node.getPathNode().getType().is(TYPE::String) ? this->getCurScriptDir() : nullptr; auto ret = this->provider.load(scriptDir, modPath, this->option); if (is<ModLoadingError>(ret)) { auto e = get<ModLoadingError>(ret); if (e.isFileNotFound() && node.isOptional()) { return FrontEndResult::inModule(std::make_unique<EmptyNode>()); } auto error = wrapModLoadingError(node.getPathNode(), modPath, e); this->listener &&this->listener->handleTypeError(this->contexts, error, true); if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY)) { return FrontEndResult::inModule(std::make_unique<ErrorNode>(error.getToken())); } return FrontEndResult::failed(); } else if (is<std::unique_ptr<Context>>(ret)) { auto &v = get<std::unique_ptr<Context>>(ret); const char *fullPath = v->lexer->getSourceName().c_str(); this->contexts.push_back(std::move(v)); if (this->uastDumper) { this->uastDumper->enterModule(fullPath); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->enterModule(fullPath); } return FrontEndResult::enterModule(); } else { assert(is<const ModType *>(ret)); auto &modType = *get<const ModType *>(ret); if (this->curScope()->modId == modType.getModId()) { // when load module from completion context auto error = wrapModLoadingError(node.getPathNode(), modPath, ModLoadingError(0)); this->listener &&this->listener->handleTypeError(this->contexts, error, true); if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY)) { return FrontEndResult::inModule(std::make_unique<ErrorNode>(error.getToken())); } return FrontEndResult::failed(); } return FrontEndResult::inModule(node.create(modType, false)); } } std::unique_ptr<SourceNode> FrontEnd::exitModule() { assert(!this->contexts.empty()); const unsigned int varNum = this->contexts.back()->scope->getMaxLocalVarIndex(); auto &modType = this->provider.newModTypeFromCurContext(this->contexts); this->contexts.pop_back(); auto node = this->getCurSrcListNode()->create(modType, true); if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY)) { node->setMaxVarNum(varNum); if (this->prevType != nullptr && this->prevType->isNothingType()) { this->prevType = &this->getTypePool().get(TYPE::Void); node->setNothing(true); } } if (this->uastDumper) { this->uastDumper->leaveModule(); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->leaveModule(); } return node; } // ################################### // ## DefaultModuleProvider ## // ################################### std::unique_ptr<FrontEnd::Context> DefaultModuleProvider::newContext(LexerPtr lexer, FrontEndOption option, ObserverPtr<CodeCompletionHandler> ccHandler) { return std::make_unique<FrontEnd::Context>(this->loader.getSysConfig(), this->pool, std::move(lexer), this->scope, option, ccHandler); } const ModType &DefaultModuleProvider::newModTypeFromCurContext( const std::vector<std::unique_ptr<FrontEnd::Context>> &ctx) { return this->loader.createModType(this->pool, *ctx.back()->scope); } FrontEnd::ModuleProvider::Ret DefaultModuleProvider::load(const char *scriptDir, const char *modPath, FrontEndOption option) { return this->load(scriptDir, modPath, option, ModLoadOption::IGNORE_NON_REG_FILE); } FrontEnd::ModuleProvider::Ret DefaultModuleProvider::load(const char *scriptDir, const char *modPath, FrontEndOption option, ModLoadOption loadOption) { FilePtr filePtr; auto ret = this->loader.load(scriptDir, modPath, filePtr, loadOption); if (is<ModLoadingError>(ret)) { return get<ModLoadingError>(ret); } else if (is<const char *>(ret)) { ByteBuffer buf; if (!readAll(filePtr, buf)) { return ModLoadingError(errno); } const char *fullPath = get<const char *>(ret); auto lex = Lexer::fromFullPath(fullPath, std::move(buf)); auto newScope = this->loader.createGlobalScopeFromFullPath(this->pool, fullPath, this->pool.getBuiltinModType()); return std::make_unique<FrontEnd::Context>(this->loader.getSysConfig(), this->pool, std::move(lex), std::move(newScope), option, nullptr); } else { assert(is<unsigned int>(ret)); auto &type = this->pool.get(get<unsigned int>(ret)); assert(type.isModType()); return cast<ModType>(&type); } } const SysConfig &DefaultModuleProvider::getSysConfig() const { return this->loader.getSysConfig(); } } // namespace ydsh <commit_msg>fix script dir in module loading<commit_after>/* * Copyright (C) 2018-2021 Nagisa Sekiguchi * * 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 "frontend.h" #include <cerrno> namespace ydsh { // ###################### // ## FrontEnd ## // ###################### static auto wrapModLoadingError(const Node &node, const char *path, ModLoadingError e) { if (e.isCircularLoad()) { return createTCError<CircularMod>(node, path); } else if (e.isFileNotFound()) { return createTCError<NotFoundMod>(node, path); } else { return createTCError<NotOpenMod>(node, path, strerror(e.getErrNo())); } } FrontEnd::FrontEnd(ModuleProvider &provider, std::unique_ptr<Context> &&ctx, FrontEndOption option) : provider(provider), option(option) { this->contexts.push_back(std::move(ctx)); this->curScope()->clearLocalSize(); } std::unique_ptr<Node> FrontEnd::tryToParse() { std::unique_ptr<Node> node; if (this->parser()) { node = this->parser()(); if (this->parser().hasError()) { this->listener &&this->listener->handleParseError(this->contexts, this->parser().getError()); } else if (this->uastDumper) { this->uastDumper(*node); } } return node; } bool FrontEnd::tryToCheckType(std::unique_ptr<Node> &node) { if (hasFlag(this->option, FrontEndOption::PARSE_ONLY)) { return true; } node = this->checker()(this->prevType, std::move(node), this->curScope()); this->prevType = &node->getType(); if (this->checker().hasError()) { auto &errors = this->checker().getErrors(); if (this->listener) { for (size_t i = 0; i < errors.size(); i++) { this->listener->handleTypeError(this->contexts, errors[i], i == 0); } } if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY) && !this->checker().hasReachedCompNode()) { return true; } return false; } else if (this->astDumper) { this->astDumper(*node); } return true; } FrontEndResult FrontEnd::operator()() { do { // load module auto ret = this->enterModule(); if (!ret || ret.kind == FrontEndResult::Kind::ENTER_MODULE) { return ret; } // parse if (!ret.node) { ret.node = this->tryToParse(); if (this->parser().hasError()) { return FrontEndResult::failed(); } } if (!ret.node) { // when parse reach EOS ret.node = this->exitModule(); } // check type if (!this->tryToCheckType(ret.node)) { return FrontEndResult::failed(); } if (isa<SourceListNode>(*ret.node)) { auto &src = cast<SourceListNode>(*ret.node); if (!src.getPathList().empty()) { this->getCurSrcListNode().reset(cast<SourceListNode>(ret.node.release())); continue; } } if (isa<SourceNode>(*ret.node) && cast<SourceNode>(*ret.node).isFirstAppear()) { ret.kind = FrontEndResult::Kind::EXIT_MODULE; } return ret; } while (true); } void FrontEnd::setupASTDump() { if (this->uastDumper) { this->uastDumper->initialize(this->getCurrentLexer()->getSourceName(), "### dump untyped AST ###"); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->initialize(this->getCurrentLexer()->getSourceName(), "### dump typed AST ###"); } } void FrontEnd::teardownASTDump() { if (this->uastDumper) { this->uastDumper->finalize(*this->curScope()); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->finalize(*this->curScope()); } } FrontEndResult FrontEnd::enterModule() { if (!this->hasUnconsumedPath()) { this->getCurSrcListNode().reset(); return FrontEndResult::inModule(nullptr); } auto &node = *this->getCurSrcListNode(); unsigned int pathIndex = node.getCurIndex(); const char *modPath = node.getPathList()[pathIndex]->c_str(); node.setCurIndex(pathIndex + 1); auto ret = this->provider.load(this->getCurScriptDir(), modPath, this->option); if (is<ModLoadingError>(ret)) { auto e = get<ModLoadingError>(ret); if (e.isFileNotFound() && node.isOptional()) { return FrontEndResult::inModule(std::make_unique<EmptyNode>()); } auto error = wrapModLoadingError(node.getPathNode(), modPath, e); this->listener &&this->listener->handleTypeError(this->contexts, error, true); if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY)) { return FrontEndResult::inModule(std::make_unique<ErrorNode>(error.getToken())); } return FrontEndResult::failed(); } else if (is<std::unique_ptr<Context>>(ret)) { auto &v = get<std::unique_ptr<Context>>(ret); const char *fullPath = v->lexer->getSourceName().c_str(); this->contexts.push_back(std::move(v)); if (this->uastDumper) { this->uastDumper->enterModule(fullPath); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->enterModule(fullPath); } return FrontEndResult::enterModule(); } else { assert(is<const ModType *>(ret)); auto &modType = *get<const ModType *>(ret); if (this->curScope()->modId == modType.getModId()) { // when load module from completion context auto error = wrapModLoadingError(node.getPathNode(), modPath, ModLoadingError(0)); this->listener &&this->listener->handleTypeError(this->contexts, error, true); if (hasFlag(this->option, FrontEndOption::ERROR_RECOVERY)) { return FrontEndResult::inModule(std::make_unique<ErrorNode>(error.getToken())); } return FrontEndResult::failed(); } return FrontEndResult::inModule(node.create(modType, false)); } } std::unique_ptr<SourceNode> FrontEnd::exitModule() { assert(!this->contexts.empty()); const unsigned int varNum = this->contexts.back()->scope->getMaxLocalVarIndex(); auto &modType = this->provider.newModTypeFromCurContext(this->contexts); this->contexts.pop_back(); auto node = this->getCurSrcListNode()->create(modType, true); if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY)) { node->setMaxVarNum(varNum); if (this->prevType != nullptr && this->prevType->isNothingType()) { this->prevType = &this->getTypePool().get(TYPE::Void); node->setNothing(true); } } if (this->uastDumper) { this->uastDumper->leaveModule(); } if (!hasFlag(this->option, FrontEndOption::PARSE_ONLY) && this->astDumper) { this->astDumper->leaveModule(); } return node; } // ################################### // ## DefaultModuleProvider ## // ################################### std::unique_ptr<FrontEnd::Context> DefaultModuleProvider::newContext(LexerPtr lexer, FrontEndOption option, ObserverPtr<CodeCompletionHandler> ccHandler) { return std::make_unique<FrontEnd::Context>(this->loader.getSysConfig(), this->pool, std::move(lexer), this->scope, option, ccHandler); } const ModType &DefaultModuleProvider::newModTypeFromCurContext( const std::vector<std::unique_ptr<FrontEnd::Context>> &ctx) { return this->loader.createModType(this->pool, *ctx.back()->scope); } FrontEnd::ModuleProvider::Ret DefaultModuleProvider::load(const char *scriptDir, const char *modPath, FrontEndOption option) { return this->load(scriptDir, modPath, option, ModLoadOption::IGNORE_NON_REG_FILE); } FrontEnd::ModuleProvider::Ret DefaultModuleProvider::load(const char *scriptDir, const char *modPath, FrontEndOption option, ModLoadOption loadOption) { FilePtr filePtr; auto ret = this->loader.load(scriptDir, modPath, filePtr, loadOption); if (is<ModLoadingError>(ret)) { return get<ModLoadingError>(ret); } else if (is<const char *>(ret)) { ByteBuffer buf; if (!readAll(filePtr, buf)) { return ModLoadingError(errno); } const char *fullPath = get<const char *>(ret); auto lex = Lexer::fromFullPath(fullPath, std::move(buf)); auto newScope = this->loader.createGlobalScopeFromFullPath(this->pool, fullPath, this->pool.getBuiltinModType()); return std::make_unique<FrontEnd::Context>(this->loader.getSysConfig(), this->pool, std::move(lex), std::move(newScope), option, nullptr); } else { assert(is<unsigned int>(ret)); auto &type = this->pool.get(get<unsigned int>(ret)); assert(type.isModType()); return cast<ModType>(&type); } } const SysConfig &DefaultModuleProvider::getSysConfig() const { return this->loader.getSysConfig(); } } // namespace ydsh <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <stdlib.h> #include <boost/concept_check.hpp> #include <cluster/ClusterManager.h> #include <vrj/Display/DisplayManager.h> #include <vrj/Kernel/Kernel.h> #include <vrj/Display/Display.h> #include <vrj/Display/Viewport.h> #include <vrj/Display/SimViewport.h> #include <vrj/Display/SurfaceViewport.h> #include <vrj/Draw/OGL/GlApp.h> #include <vrj/Draw/OGL/GlPipe.h> #include <vrj/Draw/OGL/GlWindow.h> #include <vrj/Draw/OGL/GlSimInterfaceFactory.h> #include <gmtl/Vec.h> #include <gmtl/Output.h> //#include <gadget/Type/Glove.h> //#include <gadget/Type/GloveProxy.h> #include <vrj/Draw/OGL/GlDrawManager.h> namespace vrj { vprSingletonImp(GlDrawManager); GlDrawManager::GlDrawManager() : mApp(NULL) , drawTriggerSema(0) , drawDoneSema(0) // , mRuntimeConfigSema(0) , mRunning(false) , mMemberFunctor(NULL) , mControlThread(NULL) { } /** Sets the app the draw should interact with. */ void GlDrawManager::setApp(App* _app) { mApp = dynamic_cast<GlApp*>(_app); // We have a new app, so the contexts must be re-initialized // so... dirty them all. dirtyAllWindows(); vprASSERT(mApp != NULL); } /** Returns the app we are rednering. */ GlApp* GlDrawManager::getApp() { return mApp; } /** * Do initial configuration for the draw manager. * Doesn't do anything right now. */ /* void GlDrawManager::configInitial(jccl::Configuration* cfg) { // Setup any config data } */ /** Starts the control loop. */ void GlDrawManager::start() { // --- Setup Multi-Process stuff --- // // Create a new thread to handle the control mRunning = true; mMemberFunctor = new vpr::ThreadMemberFunctor<GlDrawManager>(this, &GlDrawManager::main, NULL); mControlThread = new vpr::Thread(mMemberFunctor); vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_CONFIG_LVL) << "vrj::GlDrawManager started (thread: " << std::hex << mControlThread << std::dec << ")\n" << vprDEBUG_FLUSH; } // Enable a frame to be drawn // Trigger draw void GlDrawManager::draw() { drawTriggerSema.release(); } /** * Blocks until the end of the frame. * @post The frame has been drawn. */ void GlDrawManager::sync() { drawDoneSema.acquire(); } /** This is the control loop for the manager. */ void GlDrawManager::main(void* nullParam) { boost::ignore_unused_variable_warning(nullParam); while(mRunning) { //**// Runtime config will happen here // Because the kernel is the only one that can trigger it // we will be waiting here at that time // Wait for trigger drawTriggerSema.acquire(); // While closing the GlDrawManager this thread will be waiting at // drawTriggerSema.acquire(). To properly stop this thread we must // allow it to fall through the semaphore and not execute drawAllPipes() if (mRunning) { // THEN --- Do Rendering --- // drawAllPipes(); } // -- Done rendering --- // drawDoneSema.release(); // Allow run-time config //**//mRuntimeConfigSema.release(); // This is the time that reconfig can happen // configProcessPending(); //**//mRuntimeConfigSema.acquire(); } } void GlDrawManager::drawAllPipes() { vprDEBUG_BEGIN(vrjDBG_DRAW_MGR,vprDBG_HVERB_LVL) << "vjGLDrawManager::drawAllPipes: " << std::endl << std::flush << vprDEBUG_FLUSH; unsigned int pipeNum; // RENDER // Start rendering all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->triggerRender(); // Wait for rendering to finish on all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->completeRender(); // Barrier for Cluster //vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "BARRIER: Going to sleep for: " << num << std::endl << vprDEBUG_FLUSH; cluster::ClusterManager::instance()->createBarrier(); //vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "BARRIER: IS DONE" << std::endl << vprDEBUG_FLUSH; // SWAP // Start swapping all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->triggerSwap(); // Wait for swapping to finish on all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->completeSwap(); vprDEBUG_END(vrjDBG_DRAW_MGR,vprDBG_HVERB_LVL) << "vjGLDrawManager::drawAllPipes: Done" << std::endl << std::flush << vprDEBUG_FLUSH; } /** * Initializes the drawing API (if not already running). * @post Control thread is started. */ void GlDrawManager::initAPI() { start(); } /** * Callback when display is added to display manager. * @pre Must be in kernel controlling thread. * @note This function can only be called by the display manager * functioning on behalf of a thread the holds the kernel * reconfiguration lock. * This guarantees that we are not rendering currently. * We will most likely be waiting for a render trigger. */ void GlDrawManager::addDisplay(Display* disp) { vprASSERT(disp != NULL); // Can't add a null display vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_STATE_LVL) << "vrj::GlDrawManager:addDisplay: " << disp << std::endl << vprDEBUG_FLUSH; // -- Finish Simulator setup int num_vp(disp->getNumViewports()); for (int i = 0 ; i < num_vp ; i++) { Viewport* vp = disp->getViewport(i); if (vp->isSimulator()) { jccl::ConfigElementPtr vp_element = vp->getConfigElement(); SimViewport* sim_vp(NULL); sim_vp = dynamic_cast<SimViewport*>(vp); vprASSERT(NULL != sim_vp); sim_vp->setDrawSimInterface(NULL); // Create the simulator stuff vprASSERT(1 == vp_element->getNum("simulator_plugin") && "You must supply a simulator plugin."); // Create the simulator stuff jccl::ConfigElementPtr sim_element = vp_element->getProperty<jccl::ConfigElementPtr>("simulator_plugin"); vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_CONFIG_LVL) << "GlDrawManager::addDisplay() creating simulator of type '" << sim_element->getID() << "'\n" << vprDEBUG_FLUSH; DrawSimInterface* new_sim_i = GlSimInterfaceFactory::instance()->createObject(sim_element->getID()); // XXX: Change this to an error once the new simulator loading code is // more robust. -PH (4/13/2003) vprASSERT(NULL != new_sim_i && "Failed to create draw simulator"); sim_vp->setDrawSimInterface(new_sim_i); new_sim_i->initialize(sim_vp); new_sim_i->config(sim_element); } } // -- Create a window for new display // -- Store the window in the wins vector // Create the gl window object. NOTE: The glPipe actually "creates" the opengl window and context later GlWindow* new_win = getGLWindow(); new_win->configWindow(disp); // Configure it mWins.push_back(new_win); // Add to our local window list // -- Create any needed Pipes & Start them unsigned int pipe_num = new_win->getDisplay()->getPipe(); // Find pipe to add it too if(pipes.size() < (pipe_num+1)) // ASSERT: Max index of pipes is < our pipe { // +1 because if pipeNum = 0, I still need size() == 1 while(pipes.size() < (pipe_num+1)) // While we need more pipes { GlPipe* new_pipe = new GlPipe(pipes.size(), this); // Create a new pipe to use pipes.push_back(new_pipe); // Add the pipe new_pipe->start(); // Start the pipe running // NOTE: Run pipe even if no windows. Then it waits for windows. } } // -- Add window to the correct pipe GlPipe* pipe; // The pipe to assign it to pipe = pipes[pipe_num]; // ASSERT: pipeNum is in the valid range pipe->addWindow(new_win); // Window has been added vprASSERT(isValidWindow(new_win)); // Make sure it was added to draw manager } /** * Callback when display is removed to display manager. * @pre disp must be a valid display that we have. * @post window for disp is removed from the draw manager and child pipes. */ void GlDrawManager::removeDisplay(Display* disp) { GlPipe* pipe; pipe = NULL; GlWindow* win; win = NULL; // Window to remove for(unsigned int i=0;i<mWins.size();i++) { if(mWins[i]->getDisplay() == disp) // FOUND it { win = mWins[i]; pipe = pipes[win->getDisplay()->getPipe()]; } } // Remove the window from the pipe and our local list if(win != NULL) { vprASSERT(pipe != NULL); vprASSERT(isValidWindow(win)); pipe->removeWindow(win); // Remove from pipe mWins.erase(std::remove(mWins.begin(),mWins.end(),win), mWins.end()); // Remove from draw manager vprASSERT(!isValidWindow(win)); } else { vprDEBUG(vprDBG_ERROR, vprDBG_CRITICAL_LVL) << clrOutNORM(clrRED,"ERROR:") << "vrj::GlDrawManager::removeDisplay: Attempted to remove a display that was not found.\n" << vprDEBUG_FLUSH; vprASSERT(false); } } /** Shutdown the drawing API */ void GlDrawManager::closeAPI() { vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_STATE_LVL) << "vrj::GlDrawManager::closeAPI\n" << vprDEBUG_FLUSH; mRunning = false; drawTriggerSema.release(); drawDoneSema.acquire(); // TODO: Must shutdown and delete all pipes. // Stop and delete all pipes // TODO: We must fix the closing of EventWindows and GlWindows before we can do this. // Close and delete all glWindows } /** * Adds the element to the draw manager config. * @pre configCanHandle(element) == true. * @post The elements have reconfigured the system. */ bool GlDrawManager::configAdd(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Removes the element from the current configuration. * @pre configCanHandle(element) == true. * @return success. */ bool GlDrawManager::configRemove(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Can the handler handle the given element? * @return false: We can't handle anything. */ bool GlDrawManager::configCanHandle(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Sets the dirty bits off all the gl windows. * Dirty all the window contexts. */ void GlDrawManager::dirtyAllWindows() { // Create Pipes & Add all windows to the correct pipe for(unsigned int winId=0;winId<mWins.size();winId++) // For each window we created { mWins[winId]->setDirtyContext(true); } } bool GlDrawManager::isValidWindow(GlWindow* win) { bool ret_val = false; for(unsigned int i=0;i<mWins.size();i++) if(mWins[i] == win) ret_val = true; return ret_val; } /// dumps the object's internal state void GlDrawManager::outStream(std::ostream& out) { out << clrSetNORM(clrGREEN) << "========== GlDrawManager: " << (void*)this << " =========" << clrRESET << std::endl << clrOutNORM(clrCYAN,"\tapp: ") << (void*)mApp << std::endl << clrOutNORM(clrCYAN,"\tWindow count: ") << mWins.size() << std::endl << std::flush; for(unsigned int i = 0; i < mWins.size(); i++) { vprASSERT(mWins[i] != NULL); out << clrOutNORM(clrCYAN,"\tGlWindow:\n") << *(mWins[i]) << std::endl; } out << "=======================================" << std::endl; } } // end vrj namespace #if defined(VPR_OS_Win32) # include <vrj/Draw/OGL/GlWindowWin32.h> #elif defined(VPR_OS_Darwin) && ! defined(VRJ_USE_X11) # include <vrj/Draw/OGL/GlWindowOSX.h> #else # include <vrj/Draw/OGL/GlWindowXWin.h> #endif namespace vrj { vrj::GlWindow* GlDrawManager::getGLWindow() { #if defined(VPR_OS_Win32) return new vrj::GlWindowWin32; #elif defined(VPR_OS_Darwin) && ! defined(VRJ_USE_X11) return new vrj::GlWindowOSX; #else return new vrj::GlWindowXWin; #endif } } // end vrj namespace <commit_msg>Back out part of the last revision where I changed the output of mControlThread to be printed in hexadecimal. This is not the right way to display thread information.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <stdlib.h> #include <boost/concept_check.hpp> #include <cluster/ClusterManager.h> #include <vrj/Display/DisplayManager.h> #include <vrj/Kernel/Kernel.h> #include <vrj/Display/Display.h> #include <vrj/Display/Viewport.h> #include <vrj/Display/SimViewport.h> #include <vrj/Display/SurfaceViewport.h> #include <vrj/Draw/OGL/GlApp.h> #include <vrj/Draw/OGL/GlPipe.h> #include <vrj/Draw/OGL/GlWindow.h> #include <vrj/Draw/OGL/GlSimInterfaceFactory.h> #include <gmtl/Vec.h> #include <gmtl/Output.h> //#include <gadget/Type/Glove.h> //#include <gadget/Type/GloveProxy.h> #include <vrj/Draw/OGL/GlDrawManager.h> namespace vrj { vprSingletonImp(GlDrawManager); GlDrawManager::GlDrawManager() : mApp(NULL) , drawTriggerSema(0) , drawDoneSema(0) // , mRuntimeConfigSema(0) , mRunning(false) , mMemberFunctor(NULL) , mControlThread(NULL) { } /** Sets the app the draw should interact with. */ void GlDrawManager::setApp(App* _app) { mApp = dynamic_cast<GlApp*>(_app); // We have a new app, so the contexts must be re-initialized // so... dirty them all. dirtyAllWindows(); vprASSERT(mApp != NULL); } /** Returns the app we are rednering. */ GlApp* GlDrawManager::getApp() { return mApp; } /** * Do initial configuration for the draw manager. * Doesn't do anything right now. */ /* void GlDrawManager::configInitial(jccl::Configuration* cfg) { // Setup any config data } */ /** Starts the control loop. */ void GlDrawManager::start() { // --- Setup Multi-Process stuff --- // // Create a new thread to handle the control mRunning = true; mMemberFunctor = new vpr::ThreadMemberFunctor<GlDrawManager>(this, &GlDrawManager::main, NULL); mControlThread = new vpr::Thread(mMemberFunctor); vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_CONFIG_LVL) << "vrj::GlDrawManager started (thread: " << mControlThread << ")\n" << vprDEBUG_FLUSH; } // Enable a frame to be drawn // Trigger draw void GlDrawManager::draw() { drawTriggerSema.release(); } /** * Blocks until the end of the frame. * @post The frame has been drawn. */ void GlDrawManager::sync() { drawDoneSema.acquire(); } /** This is the control loop for the manager. */ void GlDrawManager::main(void* nullParam) { boost::ignore_unused_variable_warning(nullParam); while(mRunning) { //**// Runtime config will happen here // Because the kernel is the only one that can trigger it // we will be waiting here at that time // Wait for trigger drawTriggerSema.acquire(); // While closing the GlDrawManager this thread will be waiting at // drawTriggerSema.acquire(). To properly stop this thread we must // allow it to fall through the semaphore and not execute drawAllPipes() if (mRunning) { // THEN --- Do Rendering --- // drawAllPipes(); } // -- Done rendering --- // drawDoneSema.release(); // Allow run-time config //**//mRuntimeConfigSema.release(); // This is the time that reconfig can happen // configProcessPending(); //**//mRuntimeConfigSema.acquire(); } } void GlDrawManager::drawAllPipes() { vprDEBUG_BEGIN(vrjDBG_DRAW_MGR,vprDBG_HVERB_LVL) << "vjGLDrawManager::drawAllPipes: " << std::endl << std::flush << vprDEBUG_FLUSH; unsigned int pipeNum; // RENDER // Start rendering all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->triggerRender(); // Wait for rendering to finish on all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->completeRender(); // Barrier for Cluster //vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "BARRIER: Going to sleep for: " << num << std::endl << vprDEBUG_FLUSH; cluster::ClusterManager::instance()->createBarrier(); //vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL) << "BARRIER: IS DONE" << std::endl << vprDEBUG_FLUSH; // SWAP // Start swapping all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->triggerSwap(); // Wait for swapping to finish on all the pipes for(pipeNum=0; pipeNum<pipes.size(); pipeNum++) pipes[pipeNum]->completeSwap(); vprDEBUG_END(vrjDBG_DRAW_MGR,vprDBG_HVERB_LVL) << "vjGLDrawManager::drawAllPipes: Done" << std::endl << std::flush << vprDEBUG_FLUSH; } /** * Initializes the drawing API (if not already running). * @post Control thread is started. */ void GlDrawManager::initAPI() { start(); } /** * Callback when display is added to display manager. * @pre Must be in kernel controlling thread. * @note This function can only be called by the display manager * functioning on behalf of a thread the holds the kernel * reconfiguration lock. * This guarantees that we are not rendering currently. * We will most likely be waiting for a render trigger. */ void GlDrawManager::addDisplay(Display* disp) { vprASSERT(disp != NULL); // Can't add a null display vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_STATE_LVL) << "vrj::GlDrawManager:addDisplay: " << disp << std::endl << vprDEBUG_FLUSH; // -- Finish Simulator setup int num_vp(disp->getNumViewports()); for (int i = 0 ; i < num_vp ; i++) { Viewport* vp = disp->getViewport(i); if (vp->isSimulator()) { jccl::ConfigElementPtr vp_element = vp->getConfigElement(); SimViewport* sim_vp(NULL); sim_vp = dynamic_cast<SimViewport*>(vp); vprASSERT(NULL != sim_vp); sim_vp->setDrawSimInterface(NULL); // Create the simulator stuff vprASSERT(1 == vp_element->getNum("simulator_plugin") && "You must supply a simulator plugin."); // Create the simulator stuff jccl::ConfigElementPtr sim_element = vp_element->getProperty<jccl::ConfigElementPtr>("simulator_plugin"); vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_CONFIG_LVL) << "GlDrawManager::addDisplay() creating simulator of type '" << sim_element->getID() << "'\n" << vprDEBUG_FLUSH; DrawSimInterface* new_sim_i = GlSimInterfaceFactory::instance()->createObject(sim_element->getID()); // XXX: Change this to an error once the new simulator loading code is // more robust. -PH (4/13/2003) vprASSERT(NULL != new_sim_i && "Failed to create draw simulator"); sim_vp->setDrawSimInterface(new_sim_i); new_sim_i->initialize(sim_vp); new_sim_i->config(sim_element); } } // -- Create a window for new display // -- Store the window in the wins vector // Create the gl window object. NOTE: The glPipe actually "creates" the opengl window and context later GlWindow* new_win = getGLWindow(); new_win->configWindow(disp); // Configure it mWins.push_back(new_win); // Add to our local window list // -- Create any needed Pipes & Start them unsigned int pipe_num = new_win->getDisplay()->getPipe(); // Find pipe to add it too if(pipes.size() < (pipe_num+1)) // ASSERT: Max index of pipes is < our pipe { // +1 because if pipeNum = 0, I still need size() == 1 while(pipes.size() < (pipe_num+1)) // While we need more pipes { GlPipe* new_pipe = new GlPipe(pipes.size(), this); // Create a new pipe to use pipes.push_back(new_pipe); // Add the pipe new_pipe->start(); // Start the pipe running // NOTE: Run pipe even if no windows. Then it waits for windows. } } // -- Add window to the correct pipe GlPipe* pipe; // The pipe to assign it to pipe = pipes[pipe_num]; // ASSERT: pipeNum is in the valid range pipe->addWindow(new_win); // Window has been added vprASSERT(isValidWindow(new_win)); // Make sure it was added to draw manager } /** * Callback when display is removed to display manager. * @pre disp must be a valid display that we have. * @post window for disp is removed from the draw manager and child pipes. */ void GlDrawManager::removeDisplay(Display* disp) { GlPipe* pipe; pipe = NULL; GlWindow* win; win = NULL; // Window to remove for(unsigned int i=0;i<mWins.size();i++) { if(mWins[i]->getDisplay() == disp) // FOUND it { win = mWins[i]; pipe = pipes[win->getDisplay()->getPipe()]; } } // Remove the window from the pipe and our local list if(win != NULL) { vprASSERT(pipe != NULL); vprASSERT(isValidWindow(win)); pipe->removeWindow(win); // Remove from pipe mWins.erase(std::remove(mWins.begin(),mWins.end(),win), mWins.end()); // Remove from draw manager vprASSERT(!isValidWindow(win)); } else { vprDEBUG(vprDBG_ERROR, vprDBG_CRITICAL_LVL) << clrOutNORM(clrRED,"ERROR:") << "vrj::GlDrawManager::removeDisplay: Attempted to remove a display that was not found.\n" << vprDEBUG_FLUSH; vprASSERT(false); } } /** Shutdown the drawing API */ void GlDrawManager::closeAPI() { vprDEBUG(vrjDBG_DRAW_MGR, vprDBG_STATE_LVL) << "vrj::GlDrawManager::closeAPI\n" << vprDEBUG_FLUSH; mRunning = false; drawTriggerSema.release(); drawDoneSema.acquire(); // TODO: Must shutdown and delete all pipes. // Stop and delete all pipes // TODO: We must fix the closing of EventWindows and GlWindows before we can do this. // Close and delete all glWindows } /** * Adds the element to the draw manager config. * @pre configCanHandle(element) == true. * @post The elements have reconfigured the system. */ bool GlDrawManager::configAdd(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Removes the element from the current configuration. * @pre configCanHandle(element) == true. * @return success. */ bool GlDrawManager::configRemove(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Can the handler handle the given element? * @return false: We can't handle anything. */ bool GlDrawManager::configCanHandle(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** * Sets the dirty bits off all the gl windows. * Dirty all the window contexts. */ void GlDrawManager::dirtyAllWindows() { // Create Pipes & Add all windows to the correct pipe for(unsigned int winId=0;winId<mWins.size();winId++) // For each window we created { mWins[winId]->setDirtyContext(true); } } bool GlDrawManager::isValidWindow(GlWindow* win) { bool ret_val = false; for(unsigned int i=0;i<mWins.size();i++) if(mWins[i] == win) ret_val = true; return ret_val; } /// dumps the object's internal state void GlDrawManager::outStream(std::ostream& out) { out << clrSetNORM(clrGREEN) << "========== GlDrawManager: " << (void*)this << " =========" << clrRESET << std::endl << clrOutNORM(clrCYAN,"\tapp: ") << (void*)mApp << std::endl << clrOutNORM(clrCYAN,"\tWindow count: ") << mWins.size() << std::endl << std::flush; for(unsigned int i = 0; i < mWins.size(); i++) { vprASSERT(mWins[i] != NULL); out << clrOutNORM(clrCYAN,"\tGlWindow:\n") << *(mWins[i]) << std::endl; } out << "=======================================" << std::endl; } } // end vrj namespace #if defined(VPR_OS_Win32) # include <vrj/Draw/OGL/GlWindowWin32.h> #elif defined(VPR_OS_Darwin) && ! defined(VRJ_USE_X11) # include <vrj/Draw/OGL/GlWindowOSX.h> #else # include <vrj/Draw/OGL/GlWindowXWin.h> #endif namespace vrj { vrj::GlWindow* GlDrawManager::getGLWindow() { #if defined(VPR_OS_Win32) return new vrj::GlWindowWin32; #elif defined(VPR_OS_Darwin) && ! defined(VRJ_USE_X11) return new vrj::GlWindowOSX; #else return new vrj::GlWindowXWin; #endif } } // end vrj namespace <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _COMMON_RINGID_H_ #define _COMMON_RINGID_H_ #include <stdint.h> #include <stddef.h> #define TORV3_SUPPORT /////////////////////////////////////////////////////////////////////////////// // Declare assumptions - Begin // // // // // Various data type defs for enums. Serves following purposes: // - Reduces space since enum defaults to an int type. // - Enables using these types without the scope operator for // those enums that are namespaced, e.g. RingID. // NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM // INFRASTRUCT TEAM. (These defs affect packing assumptions // of ring structures that go into the image ringSections.) typedef uint16_t RingId_t; // Type for RingID enum typedef uint8_t ChipletType_t; // Type for CHIPLET_TYPE enum typedef uint8_t PpeType_t; // Type for PpeType typedef uint8_t ChipType_t; // Type for ChipType enum typedef uint8_t RingType_t; // Type for RingType enum typedef uint8_t RingVariant_t; // Type for RingVariant enum typedef uint8_t RingBlockType_t; // Type for RingBlockType enum, e.g. GET_SINGLE_RING typedef uint32_t TorCpltOffset_t; // Type for offset value to chiplet's CMN or INST section typedef uint8_t myBoolean_t; // false:0, true:1, undefined:UNDEFINED_BOOLEAN #define UNDEFINED_RING_ID (RingId_t)0xffff #define INVALID_RING_TYPE (RingType_t)0xff #define INVALID_CHIPLET_TYPE (ChipletType_t)0xff #define UNDEFINED_PPE_TYPE (PpeType_t)0xff #define UNDEFINED_CHIP_TYPE (ChipType_t)0xff #define UNDEFINED_RING_BLOCK_TYPE (RingBlockType_t)0xff; #define MAX_TOR_RING_OFFSET (uint16_t)(256*256-1) // Max val of uint16 #define MAX_RING_NAME_LENGTH (uint8_t)50 #define UNDEFINED_DD_LEVEL (uint8_t)0xff #define UNDEFINED_BOOLEAN (myBoolean_t)0xff // // // Declare assumptions - End // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // TOR layout definitions - Begin // // // // // TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section) // typedef struct { uint32_t magic; // =TOR_MAGIC_xyz uint8_t version; // =TOR_VERSION ChipType_t chipType; // Value from ChipType enum #ifdef TORV3_SUPPORT uint8_t ddLevel; // =0xff if MAGIC_HW, >0 all other MAGICs uint8_t numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs #else uint8_t ddLevel; // Actual DD level of ringSection uint8_t undefined; #endif uint32_t size; // Size of ringSection. } TorHeader_t; // // Subsequent TOR fields (listed in order they appear in TOR ringSections) // #ifdef TORV3_SUPPORT typedef struct { uint32_t offset; uint32_t size; uint8_t ddLevel; uint8_t reserved[3]; } TorDdBlock_t; #endif typedef struct { uint32_t offset; uint32_t size; } TorPpeBlock_t; typedef struct { TorCpltOffset_t cmnOffset; TorCpltOffset_t instOffset; } TorCpltBlock_t; typedef uint16_t TorRingOffset_t; // Offset value to actual ring // // // TOR layout definitions - End // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Key TOR constants - Begin // // // //#define TOR_VERSION 1 // Initial version. Large RS4 header. //#define TOR_VERSION 2 // Reduced RS4 header. //#define TOR_VERSION 3 // Added TOR magic header. //#define TOR_VERSION 4 // TOR API code restructuring. #define TOR_VERSION 5 // Removed TOR-level DD handling. // TOR Magic values for top-level TOR ringSection and sub-ringSections enum TorMagicNum { TOR_MAGIC = (uint32_t)0x544F52 , // "TOR" TOR_MAGIC_HW = (uint32_t)0x544F5248, // "TORH" TOR_MAGIC_SBE = (uint32_t)0x544F5242, // "TORB" TOR_MAGIC_SGPE = (uint32_t)0x544F5247, // "TORG" TOR_MAGIC_CME = (uint32_t)0x544F524D, // "TORM" TOR_MAGIC_OVRD = (uint32_t)0x544F5252, // "TORR" TOR_MAGIC_OVLY = (uint32_t)0x544F524C, // "TORL" TOR_MAGIC_CEN = (uint32_t)0x544F524E, // "TORN" }; // // // Key TOR constants - End // /////////////////////////////////////////////////////////////////////////////// // // Chip types and List to represent p9n, p9c, p9a, cen (centaur) // enum ChipType { CT_P9N, CT_P9C, CT_P9A, CT_CEN, NUM_CHIP_TYPES }; typedef struct { const char* name; ChipType_t type; } ChipTypeList_t; static const ChipTypeList_t CHIP_TYPE_LIST[] = { {"p9n", CT_P9N}, {"p9c", CT_P9C}, {"p9a", CT_P9A}, {"cen", CT_CEN}, }; // // Ring related data structs and types // typedef enum RingClass { EKB_RING, EKB_FSM_RING, EKB_STUMPED_RING, EKB_CMSK_RING, EKB_NONFLUSH_RING, VPD_RING, CEN_RING, NUM_RING_CLASSES } RingClass_t; // // General Ring ID list structure // typedef struct { const char* ringName; RingId_t ringId; uint8_t instanceIdMin; uint8_t instanceIdMax; RingClass_t ringClass; uint32_t scanScomAddress; } GenRingIdList; // PPE types supported. Note that this enum also reflects the // order with which they appear in the HW image's .rings section. enum PpeType { PT_SBE = 0x00, PT_CME = 0x01, PT_SGPE = 0x02, NUM_PPE_TYPES = 0x03 }; // Do NOT make changes to the values or order of this enum. Some user // codes, like xip_tool, make assumptions about range and order. enum RingVariant { BASE = 0x00, CC = 0x01, RL = 0x02, OVERRIDE = 0x03, OVERLAY = 0x04, NUM_RING_VARIANTS = 0x05, NOT_VALID = 0xff }; extern const char* ppeTypeName[]; extern const char* ringVariantName[]; typedef struct { RingVariant_t variant[3]; } RingVariantOrder; enum RingType { COMMON_RING = 0, INSTANCE_RING = 1, ALLRING = 2 }; enum RingBlockType { GET_SINGLE_RING = 0x00, #ifdef TORV3_SUPPORT GET_DD_LEVEL_RINGS = 0x01, #endif GET_PPE_LEVEL_RINGS = 0x02, PUT_SINGLE_RING = 0x03 }; typedef struct { // This is the chiplet-ID of the first instance of the Chiplet uint8_t iv_base_chiplet_number; // The no.of common rings for the Chiplet uint8_t iv_num_common_rings; // The no.of instance rings for the Chiplet (w/different ringId values) uint8_t iv_num_instance_rings; // The no.of instance rings for the Chiplet (w/different ringId values // AND different scanAddress values) uint8_t iv_num_instance_rings_scan_addrs; // The no.of ring variants uint8_t iv_num_ring_variants; } ChipletData_t; // This is used to Set (Mark) the left-most bit #define INSTANCE_RING_MARK (uint8_t)0x80 // // This is used to Set (Mark) the left-most bit #define INSTANCE_RING_MASK (uint8_t)0x7F // This is used to mark an invalid ring in the ring properties list #define INVALID_RING_OFFSET (uint8_t)0xFF // This structure is needed for mapping a RingID to it's corresponding name. // The names will be used by the build scripts when generating the TOR. typedef struct { uint8_t iv_torOffSet; #ifndef __PPE__ char iv_name[50]; #endif ChipletType_t iv_type; } RingProperties_t; // // Universal infrastructure error codes // #define INFRASTRUCT_RC_SUCCESS 0 #define INFRASTRUCT_RC_FAILURE 1 #define INFRASTRUCT_RC_CODE_BUG 2 #define INFRASTRUCT_RC_USER_ERROR 3 #define INFRASTRUCT_RC_NOOF_CODES 5 // Do not use as RC code // // TOR specific error codes // #define TOR_SUCCESS INFRASTRUCT_RC_SUCCESS #define TOR_FAILURE INFRASTRUCT_RC_FAILURE #define TOR_CODE_BUG INFRASTRUCT_RC_CODE_BUG #define TOR_USER_ERROR INFRASTRUCT_RC_USER_ERROR #define TOR_INVALID_MAGIC_NUMBER INFRASTRUCT_RC_NOOF_CODES + 1 #define TOR_INVALID_CHIPTYPE INFRASTRUCT_RC_NOOF_CODES + 3 #define TOR_INVALID_CHIPLET INFRASTRUCT_RC_NOOF_CODES + 4 #define TOR_INVALID_VARIANT INFRASTRUCT_RC_NOOF_CODES + 5 #define TOR_INVALID_RING_ID INFRASTRUCT_RC_NOOF_CODES + 6 #define TOR_INVALID_INSTANCE_ID INFRASTRUCT_RC_NOOF_CODES + 7 #define TOR_INVALID_RING_BLOCK_TYPE INFRASTRUCT_RC_NOOF_CODES + 8 #define TOR_UNSUPPORTED_RING_SECTION INFRASTRUCT_RC_NOOF_CODES + 9 #define TOR_RING_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 10 #define TOR_AMBIGUOUS_API_PARMS INFRASTRUCT_RC_NOOF_CODES + 11 #define TOR_SECTION_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 12 #define TOR_DD_LEVEL_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 13 #define TOR_OP_BUFFER_INVALID INFRASTRUCT_RC_NOOF_CODES + 14 #define TOR_OP_BUFFER_SIZE_EXCEEDED INFRASTRUCT_RC_NOOF_CODES + 15 #define TOR_IMAGE_DOES_NOT_SUPPORT_CME INFRASTRUCT_RC_NOOF_CODES + 16 #define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE INFRASTRUCT_RC_NOOF_CODES + 17 #define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL INFRASTRUCT_RC_NOOF_CODES + 18 #define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL INFRASTRUCT_RC_NOOF_CODES + 19 #define TOR_RING_AVAILABLE_IN_RINGSECTION INFRASTRUCT_RC_NOOF_CODES + 20 #define TOR_BUFFER_TOO_SMALL INFRASTRUCT_RC_NOOF_CODES + 21 #define TOR_TOO_MANY_DD_LEVELS INFRASTRUCT_RC_NOOF_CODES + 22 #define TOR_OFFSET_TOO_BIG INFRASTRUCT_RC_NOOF_CODES + 23 int ringid_get_noof_chiplets( ChipType_t i_chipType, uint32_t i_torMagic, uint8_t* o_numChiplets ); int ringid_get_properties( ChipType_t i_chipType, uint32_t i_torMagic, ChipletType_t i_chiplet, ChipletData_t** o_chipletData, GenRingIdList** o_ringIdListCommon, GenRingIdList** o_ringIdListInstance, RingVariantOrder** o_ringVariantOrder, RingProperties_t** o_ringProps, uint8_t* o_numVariants ); #endif // _COMMON_RINGID_H_ <commit_msg>Additional risk level support - (step 1) Backward compatibility<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _COMMON_RINGID_H_ #define _COMMON_RINGID_H_ #include <stdint.h> #include <stddef.h> #define TORV3_SUPPORT /////////////////////////////////////////////////////////////////////////////// // Declare assumptions - Begin // // // // // Various data type defs for enums. Serves following purposes: // - Reduces space since enum defaults to an int type. // - Enables using these types without the scope operator for // those enums that are namespaced, e.g. RingID. // NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM // INFRASTRUCT TEAM. (These defs affect packing assumptions // of ring structures that go into the image ringSections.) typedef uint16_t RingId_t; // Type for RingID enum typedef uint8_t ChipletType_t; // Type for CHIPLET_TYPE enum typedef uint8_t PpeType_t; // Type for PpeType typedef uint8_t ChipType_t; // Type for ChipType enum typedef uint8_t RingType_t; // Type for RingType enum typedef uint8_t RingVariant_t; // Type for RingVariant enum typedef uint8_t RingBlockType_t; // Type for RingBlockType enum, e.g. GET_SINGLE_RING typedef uint32_t TorCpltOffset_t; // Type for offset value to chiplet's CMN or INST section typedef uint8_t myBoolean_t; // false:0, true:1, undefined:UNDEFINED_BOOLEAN #define UNDEFINED_RING_ID (RingId_t)0xffff #define UNDEFINED_CHIPLET_TYPE (ChipletType_t)0xff #define UNDEFINED_PPE_TYPE (PpeType_t)0xff #define UNDEFINED_CHIP_TYPE (ChipType_t)0xff #define INVALID_RING_TYPE (RingType_t)0xff #define UNDEFINED_RING_VARIANT (RingVariant_t)0xff #define UNDEFINED_RING_BLOCK_TYPE (RingBlockType_t)0xff; #define UNDEFINED_DD_LEVEL (uint8_t)0xff #define MAX_TOR_RING_OFFSET (uint16_t)(256*256-1) // Max val of uint16 #define MAX_RING_PATH_LENGTH (uint8_t)500 #define MAX_RING_NAME_LENGTH (uint8_t)50 #define UNDEFINED_BOOLEAN (myBoolean_t)0xff // // // Declare assumptions - End // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // TOR layout definitions - Begin // // // // // TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section) // typedef struct { uint32_t magic; // =TOR_MAGIC_xyz uint8_t version; // =TOR_VERSION ChipType_t chipType; // Value from ChipType enum #ifdef TORV3_SUPPORT uint8_t ddLevel; // =0xff if MAGIC_HW, >0 all other MAGICs uint8_t numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs #else uint8_t ddLevel; // Actual DD level of ringSection uint8_t undefined; #endif uint32_t size; // Size of ringSection. } TorHeader_t; // // Subsequent TOR fields (listed in order they appear in TOR ringSections) // #ifdef TORV3_SUPPORT typedef struct { uint32_t offset; uint32_t size; uint8_t ddLevel; uint8_t reserved[3]; } TorDdBlock_t; #endif typedef struct { uint32_t offset; uint32_t size; } TorPpeBlock_t; typedef struct { TorCpltOffset_t cmnOffset; TorCpltOffset_t instOffset; } TorCpltBlock_t; typedef uint16_t TorRingOffset_t; // Offset value to actual ring // // // TOR layout definitions - End // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Key TOR constants - Begin // // // //#define TOR_VERSION 1 // Initial version. Large RS4 header. //#define TOR_VERSION 2 // Reduced RS4 header. //#define TOR_VERSION 3 // Added TOR magic header. //#define TOR_VERSION 4 // TOR API code restructuring. #define TOR_VERSION 5 // Removed TOR-level DD handling. //#define TOR_VERSION 6 // Added additional runtime risk level (RL2) // TOR Magic values for top-level TOR ringSection and sub-ringSections enum TorMagicNum { TOR_MAGIC = (uint32_t)0x544F52 , // "TOR" TOR_MAGIC_HW = (uint32_t)0x544F5248, // "TORH" TOR_MAGIC_SBE = (uint32_t)0x544F5242, // "TORB" TOR_MAGIC_SGPE = (uint32_t)0x544F5247, // "TORG" TOR_MAGIC_CME = (uint32_t)0x544F524D, // "TORM" TOR_MAGIC_OVRD = (uint32_t)0x544F5252, // "TORR" TOR_MAGIC_OVLY = (uint32_t)0x544F524C, // "TORL" TOR_MAGIC_CEN = (uint32_t)0x544F524E, // "TORN" }; // // // Key TOR constants - End // /////////////////////////////////////////////////////////////////////////////// // // Chip types and List to represent p9n, p9c, p9a, cen (centaur) // enum ChipType { CT_P9N, CT_P9C, CT_P9A, CT_CEN, NUM_CHIP_TYPES }; typedef struct { const char* name; ChipType_t type; } ChipTypeList_t; static const ChipTypeList_t CHIP_TYPE_LIST[] = { {"p9n", CT_P9N}, {"p9c", CT_P9C}, {"p9a", CT_P9A}, {"cen", CT_CEN}, }; // // Ring related data structs and types // typedef enum RingClass { EKB_RING, EKB_FSM_RING, EKB_STUMPED_RING, EKB_CMSK_RING, EKB_NONFLUSH_RING, VPD_RING, CEN_RING, NUM_RING_CLASSES } RingClass_t; // // General Ring ID list structure // typedef struct { const char* ringName; RingId_t ringId; uint8_t instanceIdMin; uint8_t instanceIdMax; RingClass_t ringClass; uint32_t scanScomAddress; } GenRingIdList; // P9 PPE types supported. // - This enum also reflects the order with which they appear in the HW image's .rings section. // - Do NOT make changes to the values or order of this enum. enum PpeType { PT_SBE = 0x00, PT_CME = 0x01, PT_SGPE = 0x02, NUM_PPE_TYPES = 0x03 }; // P9 ring variants supported. // - This enum also reflects the order with which they appear in various images' .rings section. // - Do NOT make changes to the values or order of this enum. enum RingVariant { RV_BASE = 0x00, RV_CC = 0x01, RV_RL = 0x02, RV_RL2 = 0x03, NUM_RING_VARIANTS = 0x04, }; extern const char* ppeTypeName[]; extern const char* ringVariantName[]; typedef struct { RingVariant_t variant[4]; } RingVariantOrder; // P9 ring types supported. // - This enum also reflects the order with which they appear in various images' .rings section. // - Do NOT make changes to the values or order of this enum. enum RingType { COMMON_RING = 0, INSTANCE_RING = 1, ALLRING = 2 }; enum RingBlockType { GET_SINGLE_RING = 0x00, #ifdef TORV3_SUPPORT GET_DD_LEVEL_RINGS = 0x01, #endif GET_PPE_LEVEL_RINGS = 0x02, PUT_SINGLE_RING = 0x03 }; typedef struct { // This is the chiplet-ID of the first instance of the Chiplet uint8_t iv_base_chiplet_number; // The no.of common rings for the Chiplet uint8_t iv_num_common_rings; // The no.of instance rings for the Chiplet (w/different ringId values) uint8_t iv_num_instance_rings; // The no.of instance rings for the Chiplet (w/different ringId values // AND different scanAddress values) uint8_t iv_num_instance_rings_scan_addrs; // The no.of ring variants uint8_t iv_num_ring_variants; } ChipletData_t; // This is used to Set (Mark) the left-most bit #define INSTANCE_RING_MARK (uint8_t)0x80 // // This is used to Set (Mark) the left-most bit #define INSTANCE_RING_MASK (uint8_t)0x7F // This is used to mark an invalid ring in the ring properties list #define INVALID_RING_OFFSET (uint8_t)0xFF // This structure is needed for mapping a RingID to it's corresponding name. // The names will be used by the build scripts when generating the TOR. typedef struct { uint8_t iv_torOffSet; #ifndef __PPE__ char iv_name[MAX_RING_NAME_LENGTH]; #endif ChipletType_t iv_type; } RingProperties_t; // // Universal infrastructure error codes // #define INFRASTRUCT_RC_SUCCESS 0 #define INFRASTRUCT_RC_FAILURE 1 #define INFRASTRUCT_RC_CODE_BUG 2 #define INFRASTRUCT_RC_USER_ERROR 3 #define INFRASTRUCT_RC_ENV_ERROR 4 #define INFRASTRUCT_RC_NOOF_CODES 5 // Do not use as RC code // // TOR specific error codes // #define TOR_SUCCESS INFRASTRUCT_RC_SUCCESS #define TOR_FAILURE INFRASTRUCT_RC_FAILURE #define TOR_CODE_BUG INFRASTRUCT_RC_CODE_BUG #define TOR_USER_ERROR INFRASTRUCT_RC_USER_ERROR #define TOR_INVALID_MAGIC_NUMBER INFRASTRUCT_RC_NOOF_CODES + 1 #define TOR_INVALID_CHIPTYPE INFRASTRUCT_RC_NOOF_CODES + 3 #define TOR_INVALID_CHIPLET INFRASTRUCT_RC_NOOF_CODES + 4 #define TOR_INVALID_VARIANT INFRASTRUCT_RC_NOOF_CODES + 5 #define TOR_INVALID_RING_ID INFRASTRUCT_RC_NOOF_CODES + 6 #define TOR_INVALID_INSTANCE_ID INFRASTRUCT_RC_NOOF_CODES + 7 #define TOR_INVALID_RING_BLOCK_TYPE INFRASTRUCT_RC_NOOF_CODES + 8 #define TOR_UNSUPPORTED_RING_SECTION INFRASTRUCT_RC_NOOF_CODES + 9 #define TOR_RING_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 10 #define TOR_AMBIGUOUS_API_PARMS INFRASTRUCT_RC_NOOF_CODES + 11 #define TOR_SECTION_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 12 #define TOR_DD_LEVEL_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 13 #define TOR_OP_BUFFER_INVALID INFRASTRUCT_RC_NOOF_CODES + 14 #define TOR_OP_BUFFER_SIZE_EXCEEDED INFRASTRUCT_RC_NOOF_CODES + 15 #define TOR_IMAGE_DOES_NOT_SUPPORT_CME INFRASTRUCT_RC_NOOF_CODES + 16 #define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE INFRASTRUCT_RC_NOOF_CODES + 17 #define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL INFRASTRUCT_RC_NOOF_CODES + 18 #define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL INFRASTRUCT_RC_NOOF_CODES + 19 #define TOR_RING_AVAILABLE_IN_RINGSECTION INFRASTRUCT_RC_NOOF_CODES + 20 #define TOR_BUFFER_TOO_SMALL INFRASTRUCT_RC_NOOF_CODES + 21 #define TOR_TOO_MANY_DD_LEVELS INFRASTRUCT_RC_NOOF_CODES + 22 #define TOR_OFFSET_TOO_BIG INFRASTRUCT_RC_NOOF_CODES + 23 #define TOR_NO_RINGS_FOR_VARIANT INFRASTRUCT_RC_NOOF_CODES + 24 #ifndef __HOSTBOOT_MODULE // Only needed by ring_apply in EKB int ringid_get_raw_ring_file_path( uint32_t i_magic, RingVariant_t i_ringVariant, char* io_directory ); #endif int ringid_get_noof_chiplets( ChipType_t i_chipType, uint32_t i_torMagic, uint8_t* o_numChiplets ); int ringid_get_properties( ChipType_t i_chipType, uint32_t i_torMagic, uint8_t i_torVersion, ChipletType_t i_chipletType, ChipletData_t** o_chipletData, GenRingIdList** o_ringIdListCommon, GenRingIdList** o_ringIdListInstance, RingVariantOrder** o_ringVariantOrder, RingProperties_t** o_ringProps, uint8_t* o_numVariants ); #endif // _COMMON_RINGID_H_ <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC 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. */ #include <system.hh> #include "convert.h" #include "csv.h" #include "scope.h" #include "iterators.h" #include "report.h" #include "xact.h" #include "print.h" #include "lookup.h" namespace ledger { value_t convert_command(call_scope_t& args) { report_t& report(args.context<report_t>()); journal_t& journal(*report.session.journal.get()); string bucket_name; if (report.HANDLED(account_)) bucket_name = report.HANDLER(account_).str(); else bucket_name = _("Equity:Unknown"); account_t * bucket = journal.master->find_account(bucket_name); account_t * unknown = journal.master->find_account(_("Expenses:Unknown")); // Make an amounts mapping for the account under consideration typedef std::map<value_t, std::list<post_t *> > post_map_t; post_map_t post_map; xacts_iterator journal_iter(journal); while (xact_t * xact = journal_iter()) { post_t * post = NULL; xact_posts_iterator xact_iter(*xact); while ((post = xact_iter()) != NULL) { if (post->account == bucket) break; } if (post) { post_map_t::iterator i = post_map.find(post->amount); if (i == post_map.end()) { std::list<post_t *> post_list; post_list.push_back(post); post_map.insert(post_map_t::value_type(post->amount, post_list)); } else { (*i).second.push_back(post); } } } // Create a flat list xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end()); // Read in the series of transactions from the CSV file print_xacts formatter(report); ifstream data(path(args.get<string>(0))); csv_reader reader(data); while (xact_t * xact = reader.read_xact(journal, bucket)) { if (report.HANDLED(invert)) { foreach (post_t * post, xact->posts) post->amount.in_place_negate(); } bool matched = false; post_map_t::iterator i = post_map.find(- xact->posts.front()->amount); if (i != post_map.end()) { std::list<post_t *>& post_list((*i).second); foreach (post_t * post, post_list) { if (xact->code && post->xact->code && *xact->code == *post->xact->code) { matched = true; break; } else if (xact->actual_date() == post->actual_date()) { matched = true; break; } } } if (matched) { DEBUG("convert.csv", "Ignored xact with code: " << *xact->code); checked_delete(xact); // ignore it } else { if (xact->posts.front()->account == NULL) { xacts_iterator xi; xi.xacts_i = current_xacts.begin(); xi.xacts_end = current_xacts.end(); xi.xacts_uninitialized = false; // jww (2010-03-07): Bind this logic to an option: --auto-match if (account_t * acct = lookup_probable_account(xact->payee, xi, bucket).second) xact->posts.front()->account = acct; else xact->posts.front()->account = unknown; } if (! journal.add_xact(xact)) { checked_delete(xact); throw_(std::runtime_error, _("Failed to finalize derived transaction (check commodities)")); } else { xact_posts_iterator xact_iter(*xact); while (post_t * post = xact_iter()) formatter(*post); } } } formatter.flush(); // If not, transform the payee according to regexps // Set the account to a default vaule, then transform the account according // to the payee // Print out the final form of the transaction return true; } } // namespace ledger <commit_msg>Made "convert" command insensitive to null amounts<commit_after>/* * Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC 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. */ #include <system.hh> #include "convert.h" #include "csv.h" #include "scope.h" #include "iterators.h" #include "report.h" #include "xact.h" #include "print.h" #include "lookup.h" namespace ledger { value_t convert_command(call_scope_t& args) { report_t& report(args.context<report_t>()); journal_t& journal(*report.session.journal.get()); string bucket_name; if (report.HANDLED(account_)) bucket_name = report.HANDLER(account_).str(); else bucket_name = _("Equity:Unknown"); account_t * bucket = journal.master->find_account(bucket_name); account_t * unknown = journal.master->find_account(_("Expenses:Unknown")); // Make an amounts mapping for the account under consideration typedef std::map<value_t, std::list<post_t *> > post_map_t; post_map_t post_map; xacts_iterator journal_iter(journal); while (xact_t * xact = journal_iter()) { post_t * post = NULL; xact_posts_iterator xact_iter(*xact); while ((post = xact_iter()) != NULL) { if (post->account == bucket) break; } if (post) { post_map_t::iterator i = post_map.find(post->amount); if (i == post_map.end()) { std::list<post_t *> post_list; post_list.push_back(post); post_map.insert(post_map_t::value_type(post->amount, post_list)); } else { (*i).second.push_back(post); } } } // Create a flat list xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end()); // Read in the series of transactions from the CSV file print_xacts formatter(report); ifstream data(path(args.get<string>(0))); csv_reader reader(data); while (xact_t * xact = reader.read_xact(journal, bucket)) { if (report.HANDLED(invert)) { foreach (post_t * post, xact->posts) post->amount.in_place_negate(); } bool matched = false; if (! xact->posts.front()->amount.is_null()) { post_map_t::iterator i = post_map.find(- xact->posts.front()->amount); if (i != post_map.end()) { std::list<post_t *>& post_list((*i).second); foreach (post_t * post, post_list) { if (xact->code && post->xact->code && *xact->code == *post->xact->code) { matched = true; break; } else if (xact->actual_date() == post->actual_date()) { matched = true; break; } } } } if (matched) { DEBUG("convert.csv", "Ignored xact with code: " << *xact->code); checked_delete(xact); // ignore it } else { if (xact->posts.front()->account == NULL) { xacts_iterator xi; xi.xacts_i = current_xacts.begin(); xi.xacts_end = current_xacts.end(); xi.xacts_uninitialized = false; // jww (2010-03-07): Bind this logic to an option: --auto-match if (account_t * acct = lookup_probable_account(xact->payee, xi, bucket).second) xact->posts.front()->account = acct; else xact->posts.front()->account = unknown; } if (! journal.add_xact(xact)) { checked_delete(xact); throw_(std::runtime_error, _("Failed to finalize derived transaction (check commodities)")); } else { xact_posts_iterator xact_iter(*xact); while (post_t * post = xact_iter()) formatter(*post); } } } formatter.flush(); // If not, transform the payee according to regexps // Set the account to a default vaule, then transform the account according // to the payee // Print out the final form of the transaction return true; } } // namespace ledger <|endoftext|>
<commit_before>/* * RandomEdgeScore.cpp * * Created on: 11.08.2014 * Author: Gerd Lindner */ #include "RandomEdgeScore.h" namespace NetworKit { RandomEdgeScore::RandomEdgeScore(const Graph& G) : EdgeScore<double>(G) { } void RandomEdgeScore::run() { if (!G.hasEdgeIds()) { throw std::runtime_error("edges have not been indexed - call indexEdges first"); } scoreData.resize(G.upperEdgeIdBound(), 0.0); G.parallelForEdges([&](node u, node v, edgeid eid) { //double r = Aux::Random::probability(); //scoreData[eid] = randomness * r + (1 - randomness) * attribute[eid]; scoreData[eid] = Aux::Random::probability(); }); } double RandomEdgeScore::score(node u, node v) { throw std::runtime_error("Not implemented: Use scores() instead."); } double RandomEdgeScore::score(edgeid eid) { throw std::runtime_error("Not implemented: Use scores() instead."); } } /* namespace NetworKit */ <commit_msg>missing hasRun in RandomEdgeScore<commit_after>/* * RandomEdgeScore.cpp * * Created on: 11.08.2014 * Author: Gerd Lindner */ #include "RandomEdgeScore.h" namespace NetworKit { RandomEdgeScore::RandomEdgeScore(const Graph& G) : EdgeScore<double>(G) { } void RandomEdgeScore::run() { if (!G.hasEdgeIds()) { throw std::runtime_error("edges have not been indexed - call indexEdges first"); } scoreData.resize(G.upperEdgeIdBound(), 0.0); G.parallelForEdges([&](node u, node v, edgeid eid) { //double r = Aux::Random::probability(); //scoreData[eid] = randomness * r + (1 - randomness) * attribute[eid]; scoreData[eid] = Aux::Random::probability(); }); hasRun = true; } double RandomEdgeScore::score(node u, node v) { throw std::runtime_error("Not implemented: Use scores() instead."); } double RandomEdgeScore::score(edgeid eid) { throw std::runtime_error("Not implemented: Use scores() instead."); } } /* namespace NetworKit */ <|endoftext|>
<commit_before> #include <unistd.h> #include <sstream> #include "daemon/beanstalk.hpp" #include "daemon/uuid.h" #include "tclap/CmdLine.h" #include "alpr.h" #include "openalpr/simpleini/simpleini.h" #include "openalpr/cjson.h" #include "support/tinythread.h" #include "videobuffer.h" #include <curl/curl.h> #include "support/timing.h" #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include <log4cplus/configurator.h> #include <log4cplus/consoleappender.h> #include <log4cplus/fileappender.h> // prototypes void streamRecognitionThread(void* arg); bool writeToQueue(std::string jsonResult); bool uploadPost(std::string url, std::string data); void dataUploadThread(void* arg); // Constants const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log"; const std::string DAEMON_CONFIG_FILE_PATH="/etc/openalpr/alprd.conf"; const std::string BEANSTALK_QUEUE_HOST="127.0.0.1"; const int BEANSTALK_PORT=11300; const std::string BEANSTALK_TUBE_NAME="alprd"; struct CaptureThreadData { std::string stream_url; std::string site_id; int camera_id; std::string config_file; std::string country_code; bool output_images; std::string output_image_folder; int top_n; }; struct UploadThreadData { std::string upload_url; }; bool daemon_active; static log4cplus::Logger logger; int main( int argc, const char** argv ) { daemon_active = true; bool noDaemon = false; std::string logFile; int topn; std::string configFile; std::string country; TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion()); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=25",false, 25 ,"topN"); TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to. Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN"); TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off", cmd, false); try { cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( logFileArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } country = countryCodeArg.getValue(); configFile = configFileArg.getValue(); logFile = logFileArg.getValue(); topn = topNArg.getValue(); noDaemon = daemonOffSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } log4cplus::BasicConfigurator config; config.configure(); if (noDaemon == false) { // Fork off into a separate daemon daemon(0, 0); log4cplus::SharedAppenderPtr myAppender(new log4cplus::RollingFileAppender(logFile)); myAppender->setName("alprd_appender"); // Redirect std out to log file logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd")); logger.addAppender(myAppender); LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in daemon mode."); } else { //log4cplus::SharedAppenderPtr myAppender(new log4cplus::ConsoleAppender()); //myAppender->setName("alprd_appender"); // Redirect std out to log file logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd")); //logger.addAppender(myAppender); LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in the foreground."); } CSimpleIniA ini; ini.SetMultiKey(); ini.LoadFile(DAEMON_CONFIG_FILE_PATH.c_str()); std::vector<std::string> stream_urls; CSimpleIniA::TNamesDepend values; ini.GetAllValues("daemon", "stream", values); // sort the values into the original load order values.sort(CSimpleIniA::Entry::LoadOrder()); // output all of the items CSimpleIniA::TNamesDepend::const_iterator i; for (i = values.begin(); i != values.end(); ++i) { stream_urls.push_back(i->pItem); } if (stream_urls.size() == 0) { LOG4CPLUS_FATAL(logger, "No video streams defined in the configuration."); return 1; } bool storePlates = ini.GetBoolValue("daemon", "store_plates", false); std::string imageFolder = ini.GetValue("daemon", "store_plates_location", "/tmp/"); bool uploadData = ini.GetBoolValue("daemon", "upload_data", false); std::string upload_url = ini.GetValue("daemon", "upload_address", ""); std::string site_id = ini.GetValue("daemon", "site_id", ""); LOG4CPLUS_INFO(logger, "Using: " << imageFolder << " for storing valid plate images"); pid_t pid; for (int i = 0; i < stream_urls.size(); i++) { pid = fork(); if (pid == (pid_t) 0) { // This is the child process, kick off the capture data and upload threads CaptureThreadData* tdata = new CaptureThreadData(); tdata->stream_url = stream_urls[i]; tdata->camera_id = i + 1; tdata->config_file = configFile; tdata->output_images = storePlates; tdata->output_image_folder = imageFolder; tdata->country_code = country; tdata->site_id = site_id; tdata->top_n = topn; tthread::thread* thread_recognize = new tthread::thread(streamRecognitionThread, (void*) tdata); if (uploadData) { // Kick off the data upload thread UploadThreadData* udata = new UploadThreadData(); udata->upload_url = upload_url; tthread::thread* thread_upload = new tthread::thread(dataUploadThread, (void*) udata ); } break; } // Parent process will continue and spawn more children } while (daemon_active) { usleep(30000); } } void streamRecognitionThread(void* arg) { CaptureThreadData* tdata = (CaptureThreadData*) arg; LOG4CPLUS_INFO(logger, "country: " << tdata->country_code << " -- config file: " << tdata->config_file ); LOG4CPLUS_INFO(logger, "Stream " << tdata->camera_id << ": " << tdata->stream_url); Alpr alpr(tdata->country_code, tdata->config_file); alpr.setTopN(tdata->top_n); int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(tdata->stream_url, 5); cv::Mat latestFrame; std::vector<uchar> buffer; LOG4CPLUS_INFO(logger, "Starting camera " << tdata->camera_id); while (daemon_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { timespec startTime; getTime(&startTime); cv::imencode(".bmp", latestFrame, buffer ); std::vector<AlprResult> results = alpr.recognize(buffer); timespec endTime; getTime(&endTime); double totalProcessingTime = diffclock(startTime, endTime); std::stringstream ss; ss << "Processed frame in: " << totalProcessingTime << " ms."; LOG4CPLUS_INFO(logger, ss.str()); if (results.size() > 0) { // Create a UUID for the image std::string uuid = newUUID(); // Save the image to disk (using the UUID) if (tdata->output_images) { std::stringstream ss; ss << tdata->output_image_folder << "/" << uuid << ".jpg"; cv::imwrite(ss.str(), latestFrame); } // Update the JSON content to include UUID and camera ID std::string json = alpr.toJson(results, totalProcessingTime); cJSON *root = cJSON_Parse(json.c_str()); cJSON_AddStringToObject(root, "uuid", uuid.c_str()); cJSON_AddNumberToObject(root, "camera_id", tdata->camera_id); cJSON_AddStringToObject(root, "site_id", tdata->site_id.c_str()); cJSON_AddNumberToObject(root, "img_width", latestFrame.cols); cJSON_AddNumberToObject(root, "img_height", latestFrame.rows); char *out; out=cJSON_PrintUnformatted(root); cJSON_Delete(root); std::string response(out); free(out); // Push the results to the Beanstalk queue for (int j = 0; j < results.size(); j++) { LOG4CPLUS_DEBUG(logger, "Writing plate " << results[j].bestPlate.characters << " (" << uuid << ") to queue."); } writeToQueue(response); } } usleep(10000); } videoBuffer.disconnect(); LOG4CPLUS_INFO(logger, "Video processing ended"); delete tdata; } bool writeToQueue(std::string jsonResult) { try { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.use(BEANSTALK_TUBE_NAME); int id = client.put(jsonResult); if (id <= 0) { LOG4CPLUS_ERROR(logger, "Failed to write data to queue"); return false; } LOG4CPLUS_DEBUG(logger, "put job id: " << id ); } catch (const std::runtime_error& error) { LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Result has not been saved."); return false; } return true; } void dataUploadThread(void* arg) { /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); UploadThreadData* udata = (UploadThreadData*) arg; while(daemon_active) { try { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.watch(BEANSTALK_TUBE_NAME); while (daemon_active) { Beanstalk::Job job; client.reserve(job); if (job.id() > 0) { //LOG4CPLUS_DEBUG(logger, job.body() ); if (uploadPost(udata->upload_url, job.body())) { client.del(job.id()); LOG4CPLUS_INFO(logger, "Job: " << job.id() << " successfully uploaded" ); // Wait 10ms usleep(10000); } else { client.release(job); LOG4CPLUS_WARN(logger, "Job: " << job.id() << " failed to upload. Will retry." ); // Wait 2 seconds usleep(2000000); } } } } catch (const std::runtime_error& error) { LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Will retry." ); } // wait 5 seconds usleep(5000000); } curl_global_cleanup(); } bool uploadPost(std::string url, std::string data) { bool success = true; CURL *curl; CURLcode res; /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* Now specify the POST data */ //char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); //curl_free(escaped_data); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) { success = false; } /* always cleanup */ curl_easy_cleanup(curl); } return success; }<commit_msg>Added clock parameter<commit_after> #include <unistd.h> #include <sstream> #include "daemon/beanstalk.hpp" #include "daemon/uuid.h" #include "tclap/CmdLine.h" #include "alpr.h" #include "openalpr/simpleini/simpleini.h" #include "openalpr/cjson.h" #include "support/tinythread.h" #include "videobuffer.h" #include <curl/curl.h> #include "support/timing.h" #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include <log4cplus/configurator.h> #include <log4cplus/consoleappender.h> #include <log4cplus/fileappender.h> // prototypes void streamRecognitionThread(void* arg); bool writeToQueue(std::string jsonResult); bool uploadPost(std::string url, std::string data); void dataUploadThread(void* arg); // Constants const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log"; const std::string DAEMON_CONFIG_FILE_PATH="/etc/openalpr/alprd.conf"; const std::string BEANSTALK_QUEUE_HOST="127.0.0.1"; const int BEANSTALK_PORT=11300; const std::string BEANSTALK_TUBE_NAME="alprd"; struct CaptureThreadData { std::string stream_url; std::string site_id; int camera_id; bool clock_on; std::string config_file; std::string country_code; bool output_images; std::string output_image_folder; int top_n; }; struct UploadThreadData { std::string upload_url; }; bool daemon_active; static log4cplus::Logger logger; int main( int argc, const char** argv ) { daemon_active = true; bool noDaemon = false; bool clockOn = false; std::string logFile; int topn; std::string configFile; std::string country; TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion()); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=25",false, 25 ,"topN"); TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to. Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN"); TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off", cmd, false); TCLAP::SwitchArg clockSwitch("","clock","Display timing information to log. Default=off", cmd, false); try { cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( logFileArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } country = countryCodeArg.getValue(); configFile = configFileArg.getValue(); logFile = logFileArg.getValue(); topn = topNArg.getValue(); noDaemon = daemonOffSwitch.getValue(); clockOn = clockSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } log4cplus::BasicConfigurator config; config.configure(); if (noDaemon == false) { // Fork off into a separate daemon daemon(0, 0); log4cplus::SharedAppenderPtr myAppender(new log4cplus::RollingFileAppender(logFile)); myAppender->setName("alprd_appender"); // Redirect std out to log file logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd")); logger.addAppender(myAppender); LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in daemon mode."); } else { //log4cplus::SharedAppenderPtr myAppender(new log4cplus::ConsoleAppender()); //myAppender->setName("alprd_appender"); // Redirect std out to log file logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd")); //logger.addAppender(myAppender); LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in the foreground."); } CSimpleIniA ini; ini.SetMultiKey(); ini.LoadFile(DAEMON_CONFIG_FILE_PATH.c_str()); std::vector<std::string> stream_urls; CSimpleIniA::TNamesDepend values; ini.GetAllValues("daemon", "stream", values); // sort the values into the original load order values.sort(CSimpleIniA::Entry::LoadOrder()); // output all of the items CSimpleIniA::TNamesDepend::const_iterator i; for (i = values.begin(); i != values.end(); ++i) { stream_urls.push_back(i->pItem); } if (stream_urls.size() == 0) { LOG4CPLUS_FATAL(logger, "No video streams defined in the configuration."); return 1; } bool storePlates = ini.GetBoolValue("daemon", "store_plates", false); std::string imageFolder = ini.GetValue("daemon", "store_plates_location", "/tmp/"); bool uploadData = ini.GetBoolValue("daemon", "upload_data", false); std::string upload_url = ini.GetValue("daemon", "upload_address", ""); std::string site_id = ini.GetValue("daemon", "site_id", ""); LOG4CPLUS_INFO(logger, "Using: " << imageFolder << " for storing valid plate images"); pid_t pid; for (int i = 0; i < stream_urls.size(); i++) { pid = fork(); if (pid == (pid_t) 0) { // This is the child process, kick off the capture data and upload threads CaptureThreadData* tdata = new CaptureThreadData(); tdata->stream_url = stream_urls[i]; tdata->camera_id = i + 1; tdata->config_file = configFile; tdata->output_images = storePlates; tdata->output_image_folder = imageFolder; tdata->country_code = country; tdata->site_id = site_id; tdata->top_n = topn; tdata->clock_on = clockOn; tthread::thread* thread_recognize = new tthread::thread(streamRecognitionThread, (void*) tdata); if (uploadData) { // Kick off the data upload thread UploadThreadData* udata = new UploadThreadData(); udata->upload_url = upload_url; tthread::thread* thread_upload = new tthread::thread(dataUploadThread, (void*) udata ); } break; } // Parent process will continue and spawn more children } while (daemon_active) { usleep(30000); } } void streamRecognitionThread(void* arg) { CaptureThreadData* tdata = (CaptureThreadData*) arg; LOG4CPLUS_INFO(logger, "country: " << tdata->country_code << " -- config file: " << tdata->config_file ); LOG4CPLUS_INFO(logger, "Stream " << tdata->camera_id << ": " << tdata->stream_url); Alpr alpr(tdata->country_code, tdata->config_file); alpr.setTopN(tdata->top_n); int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(tdata->stream_url, 5); cv::Mat latestFrame; std::vector<uchar> buffer; LOG4CPLUS_INFO(logger, "Starting camera " << tdata->camera_id); while (daemon_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { timespec startTime; getTime(&startTime); cv::imencode(".bmp", latestFrame, buffer ); std::vector<AlprResult> results = alpr.recognize(buffer); timespec endTime; getTime(&endTime); double totalProcessingTime = diffclock(startTime, endTime); if (tdata->clock_on) { LOG4CPLUS_INFO(logger, "Camera " << tdata->camera_id << " processed frame in: " << totalProcessingTime << " ms."); } if (results.size() > 0) { // Create a UUID for the image std::string uuid = newUUID(); // Save the image to disk (using the UUID) if (tdata->output_images) { std::stringstream ss; ss << tdata->output_image_folder << "/" << uuid << ".jpg"; cv::imwrite(ss.str(), latestFrame); } // Update the JSON content to include UUID and camera ID std::string json = alpr.toJson(results, totalProcessingTime); cJSON *root = cJSON_Parse(json.c_str()); cJSON_AddStringToObject(root, "uuid", uuid.c_str()); cJSON_AddNumberToObject(root, "camera_id", tdata->camera_id); cJSON_AddStringToObject(root, "site_id", tdata->site_id.c_str()); cJSON_AddNumberToObject(root, "img_width", latestFrame.cols); cJSON_AddNumberToObject(root, "img_height", latestFrame.rows); char *out; out=cJSON_PrintUnformatted(root); cJSON_Delete(root); std::string response(out); free(out); // Push the results to the Beanstalk queue for (int j = 0; j < results.size(); j++) { LOG4CPLUS_DEBUG(logger, "Writing plate " << results[j].bestPlate.characters << " (" << uuid << ") to queue."); } writeToQueue(response); } } usleep(10000); } videoBuffer.disconnect(); LOG4CPLUS_INFO(logger, "Video processing ended"); delete tdata; } bool writeToQueue(std::string jsonResult) { try { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.use(BEANSTALK_TUBE_NAME); int id = client.put(jsonResult); if (id <= 0) { LOG4CPLUS_ERROR(logger, "Failed to write data to queue"); return false; } LOG4CPLUS_DEBUG(logger, "put job id: " << id ); } catch (const std::runtime_error& error) { LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Result has not been saved."); return false; } return true; } void dataUploadThread(void* arg) { /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); UploadThreadData* udata = (UploadThreadData*) arg; while(daemon_active) { try { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.watch(BEANSTALK_TUBE_NAME); while (daemon_active) { Beanstalk::Job job; client.reserve(job); if (job.id() > 0) { //LOG4CPLUS_DEBUG(logger, job.body() ); if (uploadPost(udata->upload_url, job.body())) { client.del(job.id()); LOG4CPLUS_INFO(logger, "Job: " << job.id() << " successfully uploaded" ); // Wait 10ms usleep(10000); } else { client.release(job); LOG4CPLUS_WARN(logger, "Job: " << job.id() << " failed to upload. Will retry." ); // Wait 2 seconds usleep(2000000); } } } } catch (const std::runtime_error& error) { LOG4CPLUS_WARN(logger, "Error connecting to Beanstalk. Will retry." ); } // wait 5 seconds usleep(5000000); } curl_global_cleanup(); } bool uploadPost(std::string url, std::string data) { bool success = true; CURL *curl; CURLcode res; /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* Now specify the POST data */ //char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); //curl_free(escaped_data); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) { success = false; } /* always cleanup */ curl_easy_cleanup(curl); } return success; }<|endoftext|>
<commit_before>/* * File: AlarmClockSpeedTest.cpp * Author: Amanda Carbonari * Created: January 6, 2015 9:00am * * WARNING: This only measures CPU time */ #include <ctime> #include <iostream> #include <AlarmClock.h> #include <chrono> #include <thread> using namespace std; using namespace std::chrono; typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while(!alerter.Expired()); } int main(int, const char**) { unsigned int us = 389; cout << "Creating Alarm Clock" << endl; AlarmClock<microseconds> alerter(us); cout << "Sleeping to allow countdown to start" << endl; // Give some time for the countdown to start this_thread::sleep_for(microseconds(50)); cout << "Starting clock and resetting" << endl; high_resolution_clock::time_point start = high_resolution_clock::now(); alerter.Reset(); high_resolution_clock::time_point end = high_resolution_clock::now(); auto reset_time = duration_cast<microseconds>(end - start).count(); cout << "Waiting for the clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "Time: " << reset_time << " us" << endl; }<commit_msg>Increased alarm time<commit_after>/* * File: AlarmClockSpeedTest.cpp * Author: Amanda Carbonari * Created: January 6, 2015 9:00am * * WARNING: This only measures CPU time */ #include <ctime> #include <iostream> #include <AlarmClock.h> #include <chrono> #include <thread> using namespace std; using namespace std::chrono; typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while(!alerter.Expired()); } int main(int, const char**) { unsigned int us = 1000; cout << "Creating Alarm Clock" << endl; AlarmClock<microseconds> alerter(us); cout << "Sleeping to allow countdown to start" << endl; // Give some time for the countdown to start this_thread::sleep_for(microseconds(50)); cout << "Starting clock and resetting" << endl; high_resolution_clock::time_point start = high_resolution_clock::now(); alerter.Reset(); high_resolution_clock::time_point end = high_resolution_clock::now(); auto reset_time = duration_cast<microseconds>(end - start).count(); cout << "Waiting for the clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "Time: " << reset_time << " us" << endl; }<|endoftext|>
<commit_before>#include "device.h" #include "sysex/communicationexception.h" #include "sysex/getcommandlist.h" #include "sysex/getdevice.h" #include "sysex/getethernetportinfo.h" #include "sysex/getinfo.h" #include "sysex/getinfolist.h" #include "sysex/getmidiinfo.h" #include "sysex/getmidiportinfo.h" #include "sysex/getsaverestorelist.h" #include "sysex/midi.h" #include "sysex/protocolexception.h" #include "sysex/retcommandlist.h" #include "sysex/retinfolist.h" #include "sysex/retsaverestorelist.h" #include "sysex/retsetmidiinfo.h" #include "sysex/retsetmidiportinfo.h" #include <array> #include <cstring> #include <iostream> #include <sstream> #include <stdexcept> #include <unistd.h> Device::Device(unsigned int inPortNumber, unsigned int outPortNumber, unsigned long serialNumber, unsigned int productId) { this->inPortNumber = inPortNumber; this->outPortNumber = outPortNumber; this->serialNumber = new MIDISysexValue(static_cast<long>(serialNumber), 5); this->productId = new MIDISysexValue(productId, 2); this->debug = true; this->informationTree = new DeviceStructure; try { connect(); } catch (CommunicationException *e) { throw e; } } Device::Device(Device *device) : Device( device->getInPortNumer(), device->getOutPortNumer(), static_cast<unsigned long>(device->getSerialNumber()->getLongValue()), static_cast<unsigned int>(device->getProductId()->getLongValue())) {} Device::~Device() { disconnect(); } BYTE_VECTOR *Device::getManufacturerHeader() { if (Device::manufacturerHeader == 0) { manufacturerHeader = new BYTE_VECTOR(); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]); } return manufacturerHeader; } BYTE_VECTOR *Device::getDeviceHeader() { if (deviceHeader == 0) { deviceHeader = new BYTE_VECTOR(); deviceHeader->reserve(productId->getByteValue()->size() + serialNumber->getByteValue()->size()); deviceHeader->insert(deviceHeader->end(), productId->getByteValue()->begin(), productId->getByteValue()->end()); deviceHeader->insert(deviceHeader->end(), serialNumber->getByteValue()->begin(), serialNumber->getByteValue()->end()); } return deviceHeader; } BYTE_VECTOR *Device::getFullHeader() { if (fullHeader == 0) { fullHeader = new BYTE_VECTOR(); fullHeader->reserve(Device::getManufacturerHeader()->size() + getDeviceHeader()->size() + 1); fullHeader->insert(fullHeader->end(), Device::getManufacturerHeader()->begin(), Device::getManufacturerHeader()->end()); fullHeader->push_back(Device::MESSAGE_CLASS); fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(), getDeviceHeader()->end()); } return fullHeader; } bool Device::setupMidi() { std::cout << "connect" << std::endl; std::stringstream nameIn; std::stringstream nameOut; if (!midiin) { nameIn << "MioConfig In " << serialNumber->getLongValue(); midiin = MIDI::createMidiIn(nameIn.str()); if (!midiin) return false; } if (!midiin->isPortOpen()) try { midiin->openPort(inPortNumber); } catch (...) { throw; } if (!midiout) { nameOut << "MioConfig Out " << serialNumber->getLongValue(); midiout = MIDI::createMidiOut(nameOut.str()); if (!midiout) return false; } if (!midiout->isPortOpen()) try { midiout->openPort(outPortNumber); } catch (...) { throw; } return midiin->isPortOpen() && midiout->isPortOpen(); } void Device::sentSysex(BYTE_VECTOR *data) { midiout->sendMessage(data); } void Device::disconnect() { std::cout << "disconnect" << std::endl; if (midiin) { if (midiin->isPortOpen()) midiin->closePort(); delete midiin; midiin = 0; } if (midiout) { if (midiout->isPortOpen()) midiout->closePort(); delete midiout; midiout = 0; } } void Device::connect() { bool deviceOpen = false; for (int i = 0; i < WAIT_LOOPS && !deviceOpen; i++) { SLEEP(WAIT_TIME); try { deviceOpen = setupMidi(); } catch (RtMidiError e) { throw new CommunicationException(e); } } } BYTE_VECTOR *Device::retrieveSysex() { BYTE_VECTOR *data = new BYTE_VECTOR(); int i = 0; for (i = 0; i < WAIT_LOOPS && data->size() == 0; ++i) { SLEEP(WAIT_TIME); int y = 0; midiin->getMessage(data); // if there are other messages, skip them while ((data->size() > 0) && (data->at(0) != 0xf0) && (y < 100)) { midiin->getMessage(data); if (debug) std::cout << "Skipping " << std::dec << y << " midi messages" << std::endl; y++; } } std::cout << "delay: " << i << std::endl; try { checkSysex(data); } catch (...) { throw; } return data; } bool Device::checkSysex(BYTE_VECTOR *data) { if (!data || data->size() <= 0) throw new CommunicationException( CommunicationException::ANSWER_TIMEOOUT); if (data->size() < 20) throw new ProtocolException(ProtocolException::MESSAGE_TO_SHORT); BYTE_VECTOR *dataHeader = new BYTE_VECTOR(data->begin() + 1, data->begin() + 12); BYTE_VECTOR *localHeader = getFullHeader(); if (!MIDI::compareByteVector(dataHeader, localHeader)) { throw new ProtocolException(ProtocolException::WRONG_HEADER); } return true; } void Device::requestMidiPortInfos() { int midiPorts = getMidiInfo()->getMidiPorts(); if (midiPortInfos == 0) { midiPortInfos = new std::map<int, std::vector<RetSetMidiPortInfo *> *>(); } GetMidiPortInfo *info = new GetMidiPortInfo(this); for (int i = 1; i <= midiPorts; ++i) { std::vector<RetSetMidiPortInfo *> *v = 0; info->setPortNumer(i); RetSetMidiPortInfo *midiPortInfo = dynamic_cast<RetSetMidiPortInfo *>(info->query()); int portType = static_cast<int>(midiPortInfo->getPortType()); portType <<= 8; portType += midiPortInfo->getJackNumberOfType(); try { v = midiPortInfos->at(portType); } catch (const std::out_of_range &oor) { v = new std::vector<RetSetMidiPortInfo *>(); midiPortInfos->insert( std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType, v)); } if (v == 0) { v = new std::vector<RetSetMidiPortInfo *>(); midiPortInfos->insert( std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType, v)); } v->push_back(midiPortInfo); } } void Device::addCommandToStructure( Command cmd, DeviceStructureContainer *structureContainer) { informationTree->insert(std::pair<Command, DeviceStructureContainer *>( cmd, structureContainer)); } bool Device::queryDeviceInfo() { GetCommandList *c = new GetCommandList(this); c->setDebug(true); try { SysExMessage *m = c->query(); commands = dynamic_cast<RetCommandList *>(m); addCommandToStructure(commands->getCommand(), new DeviceStructureContainer(commands)); } catch (...) { throw; } if (commands->isCommandSupported(Command::GET_INFO_LIST)) { GetInfoList *i = new GetInfoList(this); i->setDebug(true); try { ii = dynamic_cast<RetInfoList *>(i->query()); DeviceStructureContainer *c = new DeviceStructureContainer(); addCommandToStructure(ii->getCommand(), c); } catch (...) { throw; } } deviceInfo = new GetInfo(this, ii); if (ii->isInfoImplemented(GetInfo::DEVICE_NAME)) deviceName = deviceInfo->getItemValue(GetInfo::DEVICE_NAME); if (ii->isInfoImplemented(GetInfo::ACCESSORY_NAME)) modelName = deviceInfo->getItemValue(GetInfo::ACCESSORY_NAME); if (ii->isInfoImplemented(GetInfo::SERIAL_NUMBER)) serialNumberString = deviceInfo->getItemValue(GetInfo::SERIAL_NUMBER); if (ii->isInfoImplemented(GetInfo::FIRMWARE_VERSION)) firmwareVersion = deviceInfo->getItemValue(GetInfo::FIRMWARE_VERSION); if (ii->isInfoImplemented(GetInfo::HARDWARE_VERSION)) hardwareVersion = deviceInfo->getItemValue(GetInfo::HARDWARE_VERSION); if (ii->isInfoImplemented(GetInfo::MANUFACTURER_NAME)) manufacturerName = deviceInfo->getItemValue(GetInfo::MANUFACTURER_NAME); if (ii->isInfoImplemented(GetInfo::MODEL_NUMBER)) modelNumber = deviceInfo->getItemValue(GetInfo::MODEL_NUMBER); if (commands->isCommandSupported(Command::GET_MIDI_INFO)) { GetMidiInfo *getMidiInfo = new GetMidiInfo(this); this->midiInfo = dynamic_cast<RetSetMidiInfo *>(getMidiInfo->query()); } if (commands->isCommandSupported(Command::GET_MIDI_PORT_INFO) && this->midiInfo != 0) { requestMidiPortInfos(); } if (commands->isCommandSupported(Command::GET_SAVE_RESTORE_LIST)) { GetSaveRestoreList *getSaveRestoreList = new GetSaveRestoreList(this); RetSaveRestoreList *l = dynamic_cast<RetSaveRestoreList *>(getSaveRestoreList->query()); saveRestoreList = l->getSaveRestoreList(); } return true; } bool Device::isDeviceValid() { GetDevice *getDevice = new GetDevice(this); getDevice->setDebug(true); int ret = -3; for (int i = 0; i < WAIT_LOOPS; ++i) { ret = getDevice->execute(); if (ret == 0) { std::cout << "device is up and answers" << std::endl; return true; } SLEEP(1000); } return false; } SysExMessage *Device::getSysExMessage(Command cmd) { switch (cmd) { case Command::GET_ETHERNET_PORT_INFO: return new GetEthernetPortInfo(this); case Command::GET_INFO_LIST: return new GetInfoList(this); case Command::GET_MIDI_INFO: return new GetMidiInfo(this); default: return NULL; } } MIDI_PORT_INFOS *Device::getMidiPortInfos() const { return midiPortInfos; } void Device::setDeviceInformation(std::string modelName, std::string deviceName) { this->modelName = modelName; this->deviceName = deviceName; } bool Device::getDebug() const { return debug; } void Device::setDebug(bool value) { debug = value; } bool Device::hasMidiSupport() { return (getMidiInfo() != 0); } BYTE_VECTOR *Device::nextTransactionId() { if (transactionId > 16000) transactionId = 0; BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2); return v; } bool Device::loadConfigurationFromDevice() { getCommands(); return true; } BYTE_VECTOR *Device::manufacturerHeader = 0; <commit_msg>when there is an communication error in requesting the medi port info try to continue with the next port<commit_after>#include "device.h" #include "sysex/communicationexception.h" #include "sysex/getcommandlist.h" #include "sysex/getdevice.h" #include "sysex/getethernetportinfo.h" #include "sysex/getinfo.h" #include "sysex/getinfolist.h" #include "sysex/getmidiinfo.h" #include "sysex/getmidiportinfo.h" #include "sysex/getsaverestorelist.h" #include "sysex/midi.h" #include "sysex/protocolexception.h" #include "sysex/retcommandlist.h" #include "sysex/retinfolist.h" #include "sysex/retsaverestorelist.h" #include "sysex/retsetmidiinfo.h" #include "sysex/retsetmidiportinfo.h" #include <array> #include <cstring> #include <iostream> #include <sstream> #include <stdexcept> #include <unistd.h> Device::Device(unsigned int inPortNumber, unsigned int outPortNumber, unsigned long serialNumber, unsigned int productId) { this->inPortNumber = inPortNumber; this->outPortNumber = outPortNumber; this->serialNumber = new MIDISysexValue(static_cast<long>(serialNumber), 5); this->productId = new MIDISysexValue(productId, 2); this->debug = true; this->informationTree = new DeviceStructure; try { connect(); } catch (CommunicationException *e) { throw e; } } Device::Device(Device *device) : Device( device->getInPortNumer(), device->getOutPortNumer(), static_cast<unsigned long>(device->getSerialNumber()->getLongValue()), static_cast<unsigned int>(device->getProductId()->getLongValue())) {} Device::~Device() { disconnect(); } BYTE_VECTOR *Device::getManufacturerHeader() { if (Device::manufacturerHeader == 0) { manufacturerHeader = new BYTE_VECTOR(); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]); manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]); } return manufacturerHeader; } BYTE_VECTOR *Device::getDeviceHeader() { if (deviceHeader == 0) { deviceHeader = new BYTE_VECTOR(); deviceHeader->reserve(productId->getByteValue()->size() + serialNumber->getByteValue()->size()); deviceHeader->insert(deviceHeader->end(), productId->getByteValue()->begin(), productId->getByteValue()->end()); deviceHeader->insert(deviceHeader->end(), serialNumber->getByteValue()->begin(), serialNumber->getByteValue()->end()); } return deviceHeader; } BYTE_VECTOR *Device::getFullHeader() { if (fullHeader == 0) { fullHeader = new BYTE_VECTOR(); fullHeader->reserve(Device::getManufacturerHeader()->size() + getDeviceHeader()->size() + 1); fullHeader->insert(fullHeader->end(), Device::getManufacturerHeader()->begin(), Device::getManufacturerHeader()->end()); fullHeader->push_back(Device::MESSAGE_CLASS); fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(), getDeviceHeader()->end()); } return fullHeader; } bool Device::setupMidi() { std::cout << "connect" << std::endl; std::stringstream nameIn; std::stringstream nameOut; if (!midiin) { nameIn << "MioConfig In " << serialNumber->getLongValue(); midiin = MIDI::createMidiIn(nameIn.str()); if (!midiin) return false; } if (!midiin->isPortOpen()) try { midiin->openPort(inPortNumber); } catch (...) { throw; } if (!midiout) { nameOut << "MioConfig Out " << serialNumber->getLongValue(); midiout = MIDI::createMidiOut(nameOut.str()); if (!midiout) return false; } if (!midiout->isPortOpen()) try { midiout->openPort(outPortNumber); } catch (...) { throw; } return midiin->isPortOpen() && midiout->isPortOpen(); } void Device::sentSysex(BYTE_VECTOR *data) { midiout->sendMessage(data); } void Device::disconnect() { std::cout << "disconnect" << std::endl; if (midiin) { if (midiin->isPortOpen()) midiin->closePort(); delete midiin; midiin = 0; } if (midiout) { if (midiout->isPortOpen()) midiout->closePort(); delete midiout; midiout = 0; } } void Device::connect() { bool deviceOpen = false; for (int i = 0; i < WAIT_LOOPS && !deviceOpen; i++) { SLEEP(WAIT_TIME); try { deviceOpen = setupMidi(); } catch (RtMidiError e) { throw new CommunicationException(e); } } } BYTE_VECTOR *Device::retrieveSysex() { BYTE_VECTOR *data = new BYTE_VECTOR(); int i = 0; for (i = 0; i < WAIT_LOOPS && data->size() == 0; ++i) { SLEEP(WAIT_TIME); int y = 0; midiin->getMessage(data); // if there are other messages, skip them while ((data->size() > 0) && (data->at(0) != 0xf0) && (y < 100)) { midiin->getMessage(data); if (debug) std::cout << "Skipping " << std::dec << y << " midi messages" << std::endl; y++; } } std::cout << "delay: " << i << std::endl; try { checkSysex(data); } catch (...) { throw; } return data; } bool Device::checkSysex(BYTE_VECTOR *data) { if (!data || data->size() <= 0) throw new CommunicationException( CommunicationException::ANSWER_TIMEOOUT); if (data->size() < 20) throw new ProtocolException(ProtocolException::MESSAGE_TO_SHORT); BYTE_VECTOR *dataHeader = new BYTE_VECTOR(data->begin() + 1, data->begin() + 12); BYTE_VECTOR *localHeader = getFullHeader(); if (!MIDI::compareByteVector(dataHeader, localHeader)) { throw new ProtocolException(ProtocolException::WRONG_HEADER); } return true; } void Device::requestMidiPortInfos() { int midiPorts = getMidiInfo()->getMidiPorts(); if (midiPortInfos == 0) { midiPortInfos = new std::map<int, std::vector<RetSetMidiPortInfo *> *>(); } GetMidiPortInfo *info = new GetMidiPortInfo(this); for (int i = 1; i <= midiPorts; ++i) { std::vector<RetSetMidiPortInfo *> *v = 0; info->setPortNumer(i); RetSetMidiPortInfo *midiPortInfo = 0; try { midiPortInfo = dynamic_cast<RetSetMidiPortInfo *>(info->query()); } catch (CommunicationException *ce) { std::cerr << ce->getErrorMessage(); continue; } int portType = static_cast<int>(midiPortInfo->getPortType()); portType <<= 8; portType += midiPortInfo->getJackNumberOfType(); try { v = midiPortInfos->at(portType); } catch (const std::out_of_range &oor) { v = new std::vector<RetSetMidiPortInfo *>(); midiPortInfos->insert( std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType, v)); } if (v == 0) { v = new std::vector<RetSetMidiPortInfo *>(); midiPortInfos->insert( std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType, v)); } v->push_back(midiPortInfo); } } void Device::addCommandToStructure( Command cmd, DeviceStructureContainer *structureContainer) { informationTree->insert(std::pair<Command, DeviceStructureContainer *>( cmd, structureContainer)); } bool Device::queryDeviceInfo() { GetCommandList *c = new GetCommandList(this); c->setDebug(true); try { SysExMessage *m = c->query(); commands = dynamic_cast<RetCommandList *>(m); addCommandToStructure(commands->getCommand(), new DeviceStructureContainer(commands)); } catch (...) { throw; } if (commands->isCommandSupported(Command::GET_INFO_LIST)) { GetInfoList *i = new GetInfoList(this); i->setDebug(true); try { ii = dynamic_cast<RetInfoList *>(i->query()); DeviceStructureContainer *c = new DeviceStructureContainer(); addCommandToStructure(ii->getCommand(), c); } catch (...) { throw; } } deviceInfo = new GetInfo(this, ii); if (ii->isInfoImplemented(GetInfo::DEVICE_NAME)) deviceName = deviceInfo->getItemValue(GetInfo::DEVICE_NAME); if (ii->isInfoImplemented(GetInfo::ACCESSORY_NAME)) modelName = deviceInfo->getItemValue(GetInfo::ACCESSORY_NAME); if (ii->isInfoImplemented(GetInfo::SERIAL_NUMBER)) serialNumberString = deviceInfo->getItemValue(GetInfo::SERIAL_NUMBER); if (ii->isInfoImplemented(GetInfo::FIRMWARE_VERSION)) firmwareVersion = deviceInfo->getItemValue(GetInfo::FIRMWARE_VERSION); if (ii->isInfoImplemented(GetInfo::HARDWARE_VERSION)) hardwareVersion = deviceInfo->getItemValue(GetInfo::HARDWARE_VERSION); if (ii->isInfoImplemented(GetInfo::MANUFACTURER_NAME)) manufacturerName = deviceInfo->getItemValue(GetInfo::MANUFACTURER_NAME); if (ii->isInfoImplemented(GetInfo::MODEL_NUMBER)) modelNumber = deviceInfo->getItemValue(GetInfo::MODEL_NUMBER); if (commands->isCommandSupported(Command::GET_MIDI_INFO)) { GetMidiInfo *getMidiInfo = new GetMidiInfo(this); this->midiInfo = dynamic_cast<RetSetMidiInfo *>(getMidiInfo->query()); } if (commands->isCommandSupported(Command::GET_MIDI_PORT_INFO) && this->midiInfo != 0) { requestMidiPortInfos(); } if (commands->isCommandSupported(Command::GET_SAVE_RESTORE_LIST)) { GetSaveRestoreList *getSaveRestoreList = new GetSaveRestoreList(this); RetSaveRestoreList *l = dynamic_cast<RetSaveRestoreList *>(getSaveRestoreList->query()); saveRestoreList = l->getSaveRestoreList(); } return true; } bool Device::isDeviceValid() { GetDevice *getDevice = new GetDevice(this); getDevice->setDebug(true); int ret = -3; for (int i = 0; i < WAIT_LOOPS; ++i) { ret = getDevice->execute(); if (ret == 0) { std::cout << "device is up and answers" << std::endl; return true; } SLEEP(1000); } return false; } SysExMessage *Device::getSysExMessage(Command cmd) { switch (cmd) { case Command::GET_ETHERNET_PORT_INFO: return new GetEthernetPortInfo(this); case Command::GET_INFO_LIST: return new GetInfoList(this); case Command::GET_MIDI_INFO: return new GetMidiInfo(this); default: return NULL; } } MIDI_PORT_INFOS *Device::getMidiPortInfos() const { return midiPortInfos; } void Device::setDeviceInformation(std::string modelName, std::string deviceName) { this->modelName = modelName; this->deviceName = deviceName; } bool Device::getDebug() const { return debug; } void Device::setDebug(bool value) { debug = value; } bool Device::hasMidiSupport() { return (getMidiInfo() != 0); } BYTE_VECTOR *Device::nextTransactionId() { if (transactionId > 16000) transactionId = 0; BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2); return v; } bool Device::loadConfigurationFromDevice() { getCommands(); return true; } BYTE_VECTOR *Device::manufacturerHeader = 0; <|endoftext|>
<commit_before>//Apr.4 // inplace_merge example #include <iostream> // std::cout #include <algorithm> // std::inplace_merge, std::sort, std::copy #include <vector> // std::vector #include <time.h> #include <queue> // std::priority_queue #include <map> using namespace std; //sort //map //priority_que class Point{ public: int _a; int _b; Point(int a,int b):_a(a),_b(b){ } }; class mycomp{ public: int operator()(const Point& p1, const Point& p2)const{ return (p1._a + p1._b)>(p2._a + p2._b); } }; int main () { vector<Point> vp; vp.emplace_back(1, 2); vp.emplace_back(3, -222); vp.emplace_back(-1, 2); sort(vp.begin(),vp.end(),mycomp()); for(auto it:vp){ cout<<"[sort vector]"<<it._a<<" , "<<it._b<<endl; } map<Point,int,mycomp> mp; /* Point* p1=(new Point(1,2)); Point p1o=*p1; mp[p1o]=3;*/ mp.emplace(Point(1,2),1); mp.emplace(Point(3,-222),2); mp.emplace(Point(-1,2),3); for(auto it:mp){ cout<<"[order map]"<<it.first._a<<" , "<<it.first._b<<" = "<<it.second<<endl; } //min_heap priority_queue<Point,vector<Point>,mycomp> pq; pq.emplace(Point(1,2));//??? pq.emplace(Point(3,-222)); pq.emplace(Point(-1,2)); while(!pq.empty()){ auto tmp = pq.top(); pq.pop(); cout<<"[minHeap]"<<tmp._a<<" , "<<tmp._b<<endl; } return 0; } <commit_msg>Update main.cpp<commit_after>//Apr.4 // inplace_merge example #include <iostream> // std::cout #include <algorithm> // std::inplace_merge, std::sort, std::copy #include <vector> // std::vector #include <time.h> #include <queue> // std::priority_queue #include <map> using namespace std; //sort //map //priority_que class Point{ public: int _a; int _b; Point(int a,int b):_a(a),_b(b){ } }; class mycomp{ public: int operator()(const Point& p1, const Point& p2)const{ return (p1._a + p1._b)>(p2._a + p2._b);//c++:p1<p2 遞增 越右邊越大 //java:p1-p2 遞增 越右邊越大 } }; int main () { vector<Point> vp; vp.emplace_back(1, 2); vp.emplace_back(3, -222); vp.emplace_back(-1, 2); sort(vp.begin(),vp.end(),mycomp()); for(auto it:vp){ cout<<"[sort vector]"<<it._a<<" , "<<it._b<<endl; } map<Point,int,mycomp> mp; /* Point* p1=(new Point(1,2)); Point p1o=*p1; mp[p1o]=3;*/ mp.emplace(Point(1,2),1); mp.emplace(Point(3,-222),2); mp.emplace(Point(-1,2),3); for(auto it:mp){ cout<<"[order map]"<<it.first._a<<" , "<<it.first._b<<" = "<<it.second<<endl; } //min_heap priority_queue<Point,vector<Point>,mycomp> pq; pq.emplace(Point(1,2));//??? pq.emplace(Point(3,-222)); pq.emplace(Point(-1,2)); while(!pq.empty()){ auto tmp = pq.top(); pq.pop(); cout<<"[minHeap]"<<tmp._a<<" , "<<tmp._b<<endl; } return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libpagemaker project. * * 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 "yaml_utils.h" const unsigned int MAX_BUF = 10; namespace libpagemaker { char *getOutputValue(int value, int *printed) { std::fprintf(stderr, "Allocating.\n"); char *buf = new char[MAX_BUF]; int theoreticalPrinted = std::snprintf(buf, MAX_BUF, "%d", value); *printed = (theoreticalPrinted > (int)MAX_BUF) ? MAX_BUF : theoreticalPrinted; return buf; } /* This silly function is necessaryf because libyaml isn't const-correct. */ char *getOutputValue(const char *value, int *printed) { int len = strlen(value) + 1; std::fprintf(stderr, "Allocating.\n"); char *valOut = new char[len]; if (!valOut) { throw YamlException(); } *printed = len - 1; strncpy(valOut, value, len); return valOut; } char *getOutputValue(bool value, int *printed) { int length = value ? 4 : 5; char *valOut = new char[length + 1]; if (!valOut) { throw YamlException(); } strcpy(valOut, value ? "true" : "false"); *printed = length; return valOut; } void yamlTryEmit(yaml_emitter_t *emitter, yaml_event_t *event) { if (!yaml_emitter_emit(emitter, event)) { throw YamlException(); } } void yamlBeginMap(yaml_emitter_t *emitter) { yaml_event_t event; if (!yaml_mapping_start_event_initialize( &event, NULL, NULL, 1, YAML_ANY_MAPPING_STYLE)) { throw YamlException(); } yamlTryEmit(emitter, &event); yaml_event_delete(&event); } void yamlEndMap(yaml_emitter_t *emitter) { yaml_event_t event; if (!yaml_mapping_end_event_initialize(&event)) { throw YamlException(); } yamlTryEmit(emitter, &event); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>Remove debug messages<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libpagemaker project. * * 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 "yaml_utils.h" const unsigned int MAX_BUF = 10; namespace libpagemaker { char *getOutputValue(int value, int *printed) { char *buf = new char[MAX_BUF]; int theoreticalPrinted = std::snprintf(buf, MAX_BUF, "%d", value); *printed = (theoreticalPrinted > (int)MAX_BUF) ? MAX_BUF : theoreticalPrinted; return buf; } /* This silly function is necessaryf because libyaml isn't const-correct. */ char *getOutputValue(const char *value, int *printed) { int len = strlen(value) + 1; char *valOut = new char[len]; if (!valOut) { throw YamlException(); } *printed = len - 1; strncpy(valOut, value, len); return valOut; } char *getOutputValue(bool value, int *printed) { int length = value ? 4 : 5; char *valOut = new char[length + 1]; if (!valOut) { throw YamlException(); } strcpy(valOut, value ? "true" : "false"); *printed = length; return valOut; } void yamlTryEmit(yaml_emitter_t *emitter, yaml_event_t *event) { if (!yaml_emitter_emit(emitter, event)) { throw YamlException(); } } void yamlBeginMap(yaml_emitter_t *emitter) { yaml_event_t event; if (!yaml_mapping_start_event_initialize( &event, NULL, NULL, 1, YAML_ANY_MAPPING_STYLE)) { throw YamlException(); } yamlTryEmit(emitter, &event); yaml_event_delete(&event); } void yamlEndMap(yaml_emitter_t *emitter) { yaml_event_t event; if (!yaml_mapping_end_event_initialize(&event)) { throw YamlException(); } yamlTryEmit(emitter, &event); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>#ifndef TCL_WORK_GROUP_SETTINGS_HPP #define TCL_WORK_GROUP_SETTINGS_HPP #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL\cl.h> #endif #include <vector> #include "CLDeviceInformation.hpp" namespace tcl { /** * CLExecute::RunŃ[NO[v̐ݒ肷邽߂̃NX * \tparam WORK_DIM [NO[v̎ */ class CLWorkGroupSettings { protected: cl_uint workDimension; std::vector<size_t> globalWorker; std::vector<size_t> globalOffset; std::vector<size_t> localWorker; private: inline void OptimizeDimension(const CLDeviceInformation& device) { // ۂ߂ if (device.MaxWorkItemDimensions() < workDimension) workDimension = device.MaxWorkItemDimensions(); } inline void OptimizeVectors(const CLDeviceInformation& device, std::vector<size_t>& target) { const auto& itemSizes = device.MaxWorkItemSizes(); size_t dimension = device.MaxWorkItemDimensions(); if (target.size() < dimension) dimension = target.size(); for (size_t i = 0; i < dimension; ++i) { if (itemSizes[i] < target[i]) target[i] = itemSizes[i]; } } public: inline cl_uint Dimension() const { return workDimension; } inline size_t* WorkerSize() { return &globalWorker[0]; } inline size_t* Offset() { return &globalOffset[0]; } inline size_t* SplitSize() { return &localWorker[0]; } CLWorkGroupSettings& Optimize(const CLDeviceInformation& device) { OptimizeDimension(device); OptimizeVectors(device, globalWorker); OptimizeVectors(device, globalOffset); OptimizeVectors(device, localWorker); return *this; } public: /** * CLExecute::RunŃ[NO[v̐ݒ肷邽߂̃NX * \param[in] dimension [NACe̎ * \param[in] workerSize [NACȇ傫CƂ̃ACe̐ * \param[in] offset ɉsʒu * \param[in] splitSize [NACeŜ̋؂ */ CLWorkGroupSettings(const cl_uint dimension, const std::vector<size_t>& offset, const std::vector<size_t>& workerSize, const std::vector<size_t>& splitSize) : workDimension(dimension), globalWorker(workerSize), globalOffset(offset), localWorker(splitSize) { if (workerSize.size() != dimension || splitSize.size() != dimension || offset.size() != dimension) throw CLException("^ꂽɑ΂āC^ꂽ̒傫邩܂"); } }; } #endif<commit_msg>自身を返すプロパティを追加<commit_after>#ifndef TCL_WORK_GROUP_SETTINGS_HPP #define TCL_WORK_GROUP_SETTINGS_HPP #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL\cl.h> #endif #include <vector> #include "CLDeviceInformation.hpp" namespace tcl { /** * CLExecute::RunŃ[NO[v̐ݒ肷邽߂̃NX * \tparam WORK_DIM [NO[v̎ */ class CLWorkGroupSettings { protected: cl_uint workDimension; std::vector<size_t> globalWorker; std::vector<size_t> globalOffset; std::vector<size_t> localWorker; private: inline void OptimizeDimension(const CLDeviceInformation& device) { // ۂ߂ if (device.MaxWorkItemDimensions() < workDimension) workDimension = device.MaxWorkItemDimensions(); } inline void OptimizeVectors(const CLDeviceInformation& device, std::vector<size_t>& target) { const auto& itemSizes = device.MaxWorkItemSizes(); size_t dimension = device.MaxWorkItemDimensions(); if (target.size() < dimension) dimension = target.size(); for (size_t i = 0; i < dimension; ++i) { if (itemSizes[i] < target[i]) target[i] = itemSizes[i]; } } public: inline cl_uint Dimension() const { return workDimension; } /** * [J[̎ݒ肷 */ inline CLWorkGroupSettings& Dimension(const cl_uint dimention) { workDimension = dimention; return *this; } inline size_t* WorkerSize() { return &globalWorker[0]; } /** * [J[̐ݒ肷 */ inline CLWorkGroupSettings& WorkerSize(const std::vector<size_t>& workerSize) { globalWorker = std::vector<size_t>(workerSize); return *this; } inline size_t* Offset() { return &globalOffset[0]; } /** * [J[̏sʒuݒ肷 */ inline CLWorkGroupSettings& Offset(const std::vector<size_t>& offset) { globalOffset = std::vector<size_t>(offset); return *this; } inline size_t* SplitSize() { return &localWorker[0]; } /** * [J[鐔ݒ肷 */ inline CLWorkGroupSettings& SplitSize(const std::vector<size_t>& splitSize) { localWorker = std::vector<size_t>(splitSize); return *this; } CLWorkGroupSettings& Optimize(const CLDeviceInformation& device) { OptimizeDimension(device); OptimizeVectors(device, globalWorker); OptimizeVectors(device, globalOffset); OptimizeVectors(device, localWorker); return *this; } public: /** * CLExecute::RunŃ[NO[v̐ݒ肷邽߂̃NX * \param[in] dimension [NACe̎ * \param[in] workerSize [NACȇ傫CƂ̃ACe̐ * \param[in] offset ɉsʒu * \param[in] splitSize [NACeŜ̋؂ */ CLWorkGroupSettings(const cl_uint dimension = 0, const std::vector<size_t>& offset = {}, const std::vector<size_t>& workerSize = {}, const std::vector<size_t>& splitSize = {}) : workDimension(dimension), globalWorker(workerSize), globalOffset(offset), localWorker(splitSize) { if (workerSize.size() > dimension || splitSize.size() > dimension || offset.size() > dimension) throw CLException("^ꂽɑ΂āC^ꂽ̒܂"); } }; } #endif<|endoftext|>
<commit_before>/* Copyright 2016 Fixstars Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <libsgm_wrapper.h> namespace sgm { LibSGMWrapper::LibSGMWrapper(const sgm::StereoSGM::Parameters& param) : sgm_(nullptr), param_(param), prev_(nullptr) {} LibSGMWrapper::~LibSGMWrapper() = default; struct LibSGMWrapper::Info { int width; int height; int src_pitch; int dst_pitch; int input_depth_bits; sgm::EXECUTE_INOUT inout_type; bool operator==(const sgm::LibSGMWrapper::Info& rhs) const { return width == rhs.width && height == rhs.height && src_pitch == rhs.src_pitch && dst_pitch == rhs.dst_pitch && input_depth_bits == rhs.input_depth_bits && inout_type == rhs.inout_type; } bool operator!=(const sgm::LibSGMWrapper::Info& rhs) const { return !(*this == rhs); } }; #ifdef WITH_OPENCV void LibSGMWrapper::execute(const cv::cuda::GpuMat& I1, const cv::cuda::GpuMat& I2, cv::cuda::GpuMat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Info> info(new Info()); info->width = size.width; info->height = size.height; info->src_pitch = static_cast<int>(I1.step1()); info->dst_pitch = static_cast<int>(disparity.step1()); info->input_depth_bits = static_cast<int>(I1.elemSize1()) * 8; info->inout_type = sgm::EXECUTE_INOUT_CUDA2CUDA; if (sgm_.get() == nullptr || !prev_ || *info != *prev_) { sgm_.reset(new StereoSGM(info->width, info->height, DISPARITY_SIZE, info->input_depth_bits, OUTPUT_DEPTH_BITS, info->src_pitch, info->dst_pitch, info->inout_type, param_)); } prev_ = std::move(info); sgm_->execute(I1.data, I2.data, disparity.data); } void LibSGMWrapper::execute(const cv::Mat& I1, const cv::Mat& I2, cv::Mat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Info> info(new Info()); info->width = size.width; info->height = size.height; info->src_pitch = static_cast<int>(I1.step1()); info->dst_pitch = static_cast<int>(disparity.step1()); info->input_depth_bits = static_cast<int>(I1.elemSize1()) * 8; info->inout_type = sgm::EXECUTE_INOUT_HOST2HOST; if (sgm_.get() == nullptr || !prev_ || *info != *prev_) { sgm_.reset(new StereoSGM(info->width, info->height, DISPARITY_SIZE, info->input_depth_bits, OUTPUT_DEPTH_BITS, info->src_pitch, info->dst_pitch, info->inout_type, param_)); } prev_ = std::move(info); sgm_->execute(I1.data, I2.data, disparity.data); } #endif // WITH_OPENCV } <commit_msg>Clean checking resource of pointer type<commit_after>/* Copyright 2016 Fixstars Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <libsgm_wrapper.h> namespace sgm { LibSGMWrapper::LibSGMWrapper(const sgm::StereoSGM::Parameters& param) : sgm_(nullptr), param_(param), prev_(nullptr) {} LibSGMWrapper::~LibSGMWrapper() = default; struct LibSGMWrapper::Info { int width; int height; int src_pitch; int dst_pitch; int input_depth_bits; sgm::EXECUTE_INOUT inout_type; bool operator==(const sgm::LibSGMWrapper::Info& rhs) const { return width == rhs.width && height == rhs.height && src_pitch == rhs.src_pitch && dst_pitch == rhs.dst_pitch && input_depth_bits == rhs.input_depth_bits && inout_type == rhs.inout_type; } bool operator!=(const sgm::LibSGMWrapper::Info& rhs) const { return !(*this == rhs); } }; #ifdef WITH_OPENCV void LibSGMWrapper::execute(const cv::cuda::GpuMat& I1, const cv::cuda::GpuMat& I2, cv::cuda::GpuMat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Info> info(new Info()); info->width = size.width; info->height = size.height; info->src_pitch = static_cast<int>(I1.step1()); info->dst_pitch = static_cast<int>(disparity.step1()); info->input_depth_bits = static_cast<int>(I1.elemSize1()) * 8; info->inout_type = sgm::EXECUTE_INOUT_CUDA2CUDA; if (!sgm_ || !prev_ || *info != *prev_) { sgm_.reset(new StereoSGM(info->width, info->height, DISPARITY_SIZE, info->input_depth_bits, OUTPUT_DEPTH_BITS, info->src_pitch, info->dst_pitch, info->inout_type, param_)); } prev_ = std::move(info); sgm_->execute(I1.data, I2.data, disparity.data); } void LibSGMWrapper::execute(const cv::Mat& I1, const cv::Mat& I2, cv::Mat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Info> info(new Info()); info->width = size.width; info->height = size.height; info->src_pitch = static_cast<int>(I1.step1()); info->dst_pitch = static_cast<int>(disparity.step1()); info->input_depth_bits = static_cast<int>(I1.elemSize1()) * 8; info->inout_type = sgm::EXECUTE_INOUT_HOST2HOST; if (!sgm_ || !prev_ || *info != *prev_) { sgm_.reset(new StereoSGM(info->width, info->height, DISPARITY_SIZE, info->input_depth_bits, OUTPUT_DEPTH_BITS, info->src_pitch, info->dst_pitch, info->inout_type, param_)); } prev_ = std::move(info); sgm_->execute(I1.data, I2.data, disparity.data); } #endif // WITH_OPENCV } <|endoftext|>
<commit_before>//**************************************************************************** // GOERTZEL ALGORITHM For complex input data //**************************************************************************** #include <iostream> #include <iomanip> #include <fstream> // std::ofstream using namespace std; /* https://www.dsprelated.com/showthread/comp.dsp/44939-1.php The Goertzel gain is N/2, so if the signal has an amplitude of A, then the Goertzel output has a magnitude of A*N/2. Don't forget sometimes the magnitude^2 is used, so you now have (A*N/2)^2. In order for that gain term to be correct, the frequency that you are looking for needs to be an integer multiple of the sample rate divided by the block length. In other words, the block needs to be able to contain an integer number of cycles of the frequency you are looking for. */ #include <stdio.h> #include <math.h> #include <limits.h> // Number of input data points and // number of spectral points, i.e. number of bins all the interval is divided to #define SP 65536/16*4 #ifndef NDEBUG #define DEBUG_MODE #endif int64_t c64to48(int64_t x); int64_t resize_int(int64_t x, int16_t n) { int64_t mask = ~(0xFFFFFFFFFFFFFFFF << n-1); int64_t sign = (x >> n+1) & ~mask; // print out masks /*cout << hex << setw(16) << right << setfill('0') << sign << " | "; cout << hex << setw(16) << right << setfill('0') << mask << endl;*/ return sign + (mask & x); } #include <string.h> void checkForMinMax(int64_t lr, int64_t & lr_min, int64_t & lr_max) { if(lr < lr_min) lr_min = lr; if(lr > lr_max) lr_max = lr; } extern int fftBin; void CalcGoertzelI(int x[][2], int64_t real[], int64_t imag[], int Sp) { const int16_t a = 0; const int16_t b = 0; const int16_t register_length = 32; const int16_t trig_length = 16; const int16_t mul_length = register_length+trig_length-a-b; const int16_t add_length = register_length+2; memset(real, Sp, sizeof(int64_t)*Sp); memset(imag, Sp, sizeof(int64_t)*Sp); #ifdef DEBUG_MODE int64_t lr1_min, lr1_max; int64_t li1_min, li1_max; int64_t lr2_min, lr2_max; int64_t li2_min, li2_max; lr1_min = LLONG_MAX; lr1_max = LLONG_MIN; li1_min = LLONG_MAX; li1_max = LLONG_MIN; lr2_min = LLONG_MAX; lr2_max = LLONG_MIN; li2_min = LLONG_MAX; li2_max = LLONG_MIN; #endif int64_t c, s; // cosine and sine 16 bits registers int16_t x_n; // sample (bin) int64_t lr1, lr2, li1, li2, temp; // algorithm registers int64_t mul; float phi, wn; // algorithm variables for sine and cosine computation int n, k; // loop variables // Prepare for computation wn = M_PI/Sp; // Loop through all the bins //for(k=0; k<Sp; k++) k = fftBin; { lr1 = lr2 = 0; li1 = li2 = 0; temp = 0; mul = 0; // Precompute the constants for the current bin phi = wn * k; c = (cos(phi) * 32768 ); s = (sin(phi) * 32768 ); // Emulate data shift for(n=0; n<Sp; n++) { // first channel x_n = x[n][0]; temp = resize_int(lr1, register_length); mul = (c >> a) * (lr1 >> b); mul = resize_int(mul, mul_length); mul = (mul >> trig_length-a-b-2); lr1 = resize_int(mul, add_length) - resize_int(lr2, add_length) + resize_int(x_n, add_length); lr2 = temp; #ifdef DEBUG_MODE checkForMinMax(lr1, lr1_min, lr1_max); checkForMinMax(lr2, lr2_min, lr2_max); #endif lr1 = resize_int(lr1, register_length); // second channel x_n = x[n][1]; temp = resize_int(li1, register_length); mul = (c >> a) * (li1 >> b); mul = resize_int(mul, mul_length); mul = (mul >> trig_length-a-b-2); li1 = resize_int(mul, add_length) - resize_int(li2, add_length) + resize_int(x_n, add_length); li2 = temp; #ifdef DEBUG_MODE checkForMinMax(li1, li1_min, li1_max); checkForMinMax(li2, li2_min, li2_max); #endif li1 = resize_int(li1, register_length); } real[k] = (int64_t)( resize_int( resize_int( (c >> a)*(lr1 >> b), mul_length) >> trig_length-a-b-1, add_length) - resize_int(lr2, add_length) - resize_int( resize_int((s >> a) * (li1 >> b), mul_length )>> trig_length-a-b-1, add_length) ); imag[k] = (int64_t)( resize_int( resize_int( (c >> a)*(li1 >> b), mul_length) >> trig_length-a-b-1, add_length) - resize_int(li2, add_length) + resize_int( resize_int((s >> a) * (lr1 >> b), mul_length )>> trig_length-a-b-1, add_length) ); } #ifdef DEBUG_MODE /* cout << lr1_min << " | " << lr1_max << endl; cout << li1_min << " | " << lr1_max << endl; cout << lr2_min << " | " << lr1_max << endl; cout << li2_min << " | " << lr1_max << endl; */ #endif }; <commit_msg>Fix compilation on windows<commit_after>//**************************************************************************** // GOERTZEL ALGORITHM For complex input data //**************************************************************************** #include <iostream> #include <iomanip> #include <fstream> // std::ofstream using namespace std; /* https://www.dsprelated.com/showthread/comp.dsp/44939-1.php The Goertzel gain is N/2, so if the signal has an amplitude of A, then the Goertzel output has a magnitude of A*N/2. Don't forget sometimes the magnitude^2 is used, so you now have (A*N/2)^2. In order for that gain term to be correct, the frequency that you are looking for needs to be an integer multiple of the sample rate divided by the block length. In other words, the block needs to be able to contain an integer number of cycles of the frequency you are looking for. */ #include <stdio.h> #include <math.h> #include <limits.h> #include <stdint.h> static const double PI = 3.14159265359; // Number of input data points and // number of spectral points, i.e. number of bins all the interval is divided to #define SP 65536/16*4 #ifndef NDEBUG #define DEBUG_MODE #endif int64_t c64to48(int64_t x); int64_t resize_int(int64_t x, int16_t n) { int64_t mask = ~(0xFFFFFFFFFFFFFFFF << n-1); int64_t sign = (x >> n+1) & ~mask; // print out masks /*cout << hex << setw(16) << right << setfill('0') << sign << " | "; cout << hex << setw(16) << right << setfill('0') << mask << endl;*/ return sign + (mask & x); } #include <string.h> void checkForMinMax(int64_t lr, int64_t & lr_min, int64_t & lr_max) { if(lr < lr_min) lr_min = lr; if(lr > lr_max) lr_max = lr; } extern int fftBin; void CalcGoertzelI(int x[][2], int64_t real[], int64_t imag[], int Sp) { const int16_t a = 0; const int16_t b = 0; const int16_t register_length = 32; const int16_t trig_length = 16; const int16_t mul_length = register_length+trig_length-a-b; const int16_t add_length = register_length+2; memset(real, Sp, sizeof(int64_t)*Sp); memset(imag, Sp, sizeof(int64_t)*Sp); #ifdef DEBUG_MODE int64_t lr1_min, lr1_max; int64_t li1_min, li1_max; int64_t lr2_min, lr2_max; int64_t li2_min, li2_max; lr1_min = LLONG_MAX; lr1_max = LLONG_MIN; li1_min = LLONG_MAX; li1_max = LLONG_MIN; lr2_min = LLONG_MAX; lr2_max = LLONG_MIN; li2_min = LLONG_MAX; li2_max = LLONG_MIN; #endif int64_t c, s; // cosine and sine 16 bits registers int16_t x_n; // sample (bin) int64_t lr1, lr2, li1, li2, temp; // algorithm registers int64_t mul; float phi, wn; // algorithm variables for sine and cosine computation int n, k; // loop variables // Prepare for computation wn = PI/Sp; // Loop through all the bins //for(k=0; k<Sp; k++) k = fftBin; { lr1 = lr2 = 0; li1 = li2 = 0; temp = 0; mul = 0; // Precompute the constants for the current bin phi = wn * k; c = (cos(phi) * 32768 ); s = (sin(phi) * 32768 ); // Emulate data shift for(n=0; n<Sp; n++) { // first channel x_n = x[n][0]; temp = resize_int(lr1, register_length); mul = (c >> a) * (lr1 >> b); mul = resize_int(mul, mul_length); mul = (mul >> trig_length-a-b-2); lr1 = resize_int(mul, add_length) - resize_int(lr2, add_length) + resize_int(x_n, add_length); lr2 = temp; #ifdef DEBUG_MODE checkForMinMax(lr1, lr1_min, lr1_max); checkForMinMax(lr2, lr2_min, lr2_max); #endif lr1 = resize_int(lr1, register_length); // second channel x_n = x[n][1]; temp = resize_int(li1, register_length); mul = (c >> a) * (li1 >> b); mul = resize_int(mul, mul_length); mul = (mul >> trig_length-a-b-2); li1 = resize_int(mul, add_length) - resize_int(li2, add_length) + resize_int(x_n, add_length); li2 = temp; #ifdef DEBUG_MODE checkForMinMax(li1, li1_min, li1_max); checkForMinMax(li2, li2_min, li2_max); #endif li1 = resize_int(li1, register_length); } real[k] = (int64_t)( resize_int( resize_int( (c >> a)*(lr1 >> b), mul_length) >> trig_length-a-b-1, add_length) - resize_int(lr2, add_length) - resize_int( resize_int((s >> a) * (li1 >> b), mul_length )>> trig_length-a-b-1, add_length) ); imag[k] = (int64_t)( resize_int( resize_int( (c >> a)*(li1 >> b), mul_length) >> trig_length-a-b-1, add_length) - resize_int(li2, add_length) + resize_int( resize_int((s >> a) * (lr1 >> b), mul_length )>> trig_length-a-b-1, add_length) ); } #ifdef DEBUG_MODE /* cout << lr1_min << " | " << lr1_max << endl; cout << li1_min << " | " << lr1_max << endl; cout << lr2_min << " | " << lr1_max << endl; cout << li2_min << " | " << lr1_max << endl; */ #endif }; <|endoftext|>
<commit_before>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 "esidl.h" #include <sys/types.h> #include <sys/wait.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <string> namespace { std::string baseFilename; std::string filename; } const std::string getBaseFilename() { return baseFilename; } void setBaseFilename(const char* name) { baseFilename = name; if (baseFilename[0] == '"') { baseFilename = baseFilename.substr(1, baseFilename.length() - 2); } setFilename(name); } const std::string getFilename() { return filename; } void setFilename(const char* name) { filename = name; if (filename == "\"<stdin>\"") { filename = getBaseFilename(); } else if (filename[0] == '"') { filename = filename.substr(1, filename.length() - 2); } } int main(int argc, char* argv[]) { if (argc < 2) { return EXIT_FAILURE; } // Construct cpp options const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2))); if (!argCpp) { return EXIT_FAILURE; } int optCpp = 0; argCpp[optCpp++] = "cpp"; argCpp[optCpp++] = "-C"; // Use -C for cpp by default. bool skeleton = false; bool generic = false; bool isystem = false; bool useExceptions = true; const char* stringTypeName = "char*"; // C++ string type name to be used const char* indent = "es"; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (argv[i][1] == 'I') { argCpp[optCpp++] = argv[i]; if (argv[i][2] == '\0') { ++i; argCpp[optCpp++] = argv[i]; setIncludePath(argv[i]); } else { setIncludePath(&argv[i][2]); } } else if (strcmp(argv[i], "-fexceptions") == 0) { useExceptions = true; } else if (strcmp(argv[i], "-fno-exceptions") == 0) { useExceptions = false; } else if (strcmp(argv[i], "-include") == 0) { argCpp[optCpp++] = argv[i]; ++i; argCpp[optCpp++] = argv[i]; } else if (strcmp(argv[i], "-isystem") == 0) { argCpp[optCpp++] = argv[i]; ++i; argCpp[optCpp++] = argv[i]; setIncludePath(argv[i]); isystem = true; } else if (strcmp(argv[i], "-namespace") == 0) { ++i; Node::setFlatNamespace(argv[i]); } else if (strcmp(argv[i], "-object") == 0) { ++i; Node::setBaseObjectName(argv[i]); } else if (strcmp(argv[i], "-template") == 0) { generic = true; } else if (strcmp(argv[i], "-skeleton") == 0) { skeleton = true; } else if (strcmp(argv[i], "-string") == 0) { ++i; stringTypeName = argv[i]; } else if (strcmp(argv[i], "-indent") == 0) { ++i; indent = argv[i]; } } } argCpp[optCpp] = 0; // Set up the global module Module* node = new Module(""); setSpecification(node); setCurrent(node); if (strcmp(Node::getBaseObjectName(), "::Object") == 0) { // Manually install 'Object' interface forward declaration. Interface* object = new Interface("Object", 0, true); object->setRank(2); getCurrent()->add(object); } if (Node::getFlatNamespace()) { Module* module = new Module(Node::getFlatNamespace()); getCurrent()->add(module); setCurrent(module); } // Load every IDL file at once int result = EXIT_SUCCESS; int cppStream[2]; pipe(cppStream); pid_t id = fork(); if (id == 0) { // Child process int catStream[2]; pipe(catStream); pid_t id = fork(); if (id == 0) { // cat every IDL file close(catStream[0]); FILE* out = fdopen(catStream[1], "w"); for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-I") == 0 || strcmp(argv[i], "-include") == 0 || strcmp(argv[i], "-isystem") == 0 || strcmp(argv[i], "-namespace") == 0 || strcmp(argv[i], "-object") == 0 || strcmp(argv[i], "-string") == 0 || strcmp(argv[i], "-indent") == 0) { ++i; } continue; } FILE* in = fopen(argv[i], "r"); if (!in) { return EXIT_FAILURE; } fprintf(out, "#pragma source \"%s\"\n", argv[i]); int ch; while ((ch = fgetc(in)) != EOF) { putc(ch, out); } fclose(in); } fclose(out); return EXIT_SUCCESS; } else if (0 < id) { // execute cpp close(0); dup(catStream[0]); close(catStream[0]); close(catStream[1]); close(1); dup(cppStream[1]); close(cppStream[0]); close(cppStream[1]); execvp(argCpp[0], const_cast<char**>(argCpp)); return EXIT_FAILURE; } else { return EXIT_FAILURE; } } else if (0 < id) { // Parent process - process an IDL file close(cppStream[1]); if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS) { return EXIT_FAILURE; } close(cppStream[0]); int status; while (wait(&status) != id) { } if (result == EXIT_SUCCESS) { if (!WIFEXITED(status)) { result = EXIT_FAILURE; } else { result = WEXITSTATUS(status); } } } else { return EXIT_FAILURE; } setBaseFilename(""); ProcessExtendedAttributes processExtendedAttributes; getSpecification()->accept(&processExtendedAttributes); AdjustMethodCount adjustMethodCount; getSpecification()->accept(&adjustMethodCount); for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-I") == 0 || strcmp(argv[i], "-include") == 0 || strcmp(argv[i], "-isystem") == 0 || strcmp(argv[i], "-namespace") == 0 || strcmp(argv[i], "-object") == 0 || strcmp(argv[i], "-string") == 0) { ++i; } continue; } result = output(argv[i], isystem, useExceptions, stringTypeName, indent, skeleton, generic); } return result; } <commit_msg>(main) : Fix bugs.<commit_after>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 "esidl.h" #include <sys/types.h> #include <sys/wait.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <string> namespace { std::string baseFilename; std::string filename; } const std::string getBaseFilename() { return baseFilename; } void setBaseFilename(const char* name) { baseFilename = name; if (baseFilename[0] == '"') { baseFilename = baseFilename.substr(1, baseFilename.length() - 2); } setFilename(name); } const std::string getFilename() { return filename; } void setFilename(const char* name) { filename = name; if (filename == "\"<stdin>\"") { filename = getBaseFilename(); } else if (filename[0] == '"') { filename = filename.substr(1, filename.length() - 2); } } int main(int argc, char* argv[]) { if (argc < 2) { return EXIT_FAILURE; } // Construct cpp options const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2))); if (!argCpp) { return EXIT_FAILURE; } int optCpp = 0; argCpp[optCpp++] = "cpp"; argCpp[optCpp++] = "-C"; // Use -C for cpp by default. bool skeleton = false; bool generic = false; bool isystem = false; bool useExceptions = true; const char* stringTypeName = "char*"; // C++ string type name to be used const char* indent = "es"; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (argv[i][1] == 'I') { argCpp[optCpp++] = argv[i]; if (argv[i][2] == '\0') { ++i; argCpp[optCpp++] = argv[i]; setIncludePath(argv[i]); } else { setIncludePath(&argv[i][2]); } } else if (strcmp(argv[i], "-fexceptions") == 0) { useExceptions = true; } else if (strcmp(argv[i], "-fno-exceptions") == 0) { useExceptions = false; } else if (strcmp(argv[i], "-include") == 0) { argCpp[optCpp++] = argv[i]; ++i; argCpp[optCpp++] = argv[i]; } else if (strcmp(argv[i], "-indent") == 0) { ++i; indent = argv[i]; } else if (strcmp(argv[i], "-isystem") == 0) { argCpp[optCpp++] = argv[i]; ++i; argCpp[optCpp++] = argv[i]; setIncludePath(argv[i]); isystem = true; } else if (strcmp(argv[i], "-namespace") == 0) { ++i; Node::setFlatNamespace(argv[i]); } else if (strcmp(argv[i], "-object") == 0) { ++i; Node::setBaseObjectName(argv[i]); } else if (strcmp(argv[i], "-template") == 0) { generic = true; } else if (strcmp(argv[i], "-skeleton") == 0) { skeleton = true; } else if (strcmp(argv[i], "-string") == 0) { ++i; stringTypeName = argv[i]; } } } argCpp[optCpp] = 0; // Set up the global module Module* node = new Module(""); setSpecification(node); setCurrent(node); if (strcmp(Node::getBaseObjectName(), "::Object") == 0) { // Manually install 'Object' interface forward declaration. Interface* object = new Interface("Object", 0, true); object->setRank(2); getCurrent()->add(object); } if (Node::getFlatNamespace()) { Module* module = new Module(Node::getFlatNamespace()); getCurrent()->add(module); setCurrent(module); } // Load every IDL file at once int result = EXIT_SUCCESS; int cppStream[2]; pipe(cppStream); pid_t id = fork(); if (id == 0) { // Child process int catStream[2]; pipe(catStream); pid_t id = fork(); if (id == 0) { // cat every IDL file close(catStream[0]); FILE* out = fdopen(catStream[1], "w"); for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-I") == 0 || strcmp(argv[i], "-include") == 0 || strcmp(argv[i], "-indent") == 0 || strcmp(argv[i], "-isystem") == 0 || strcmp(argv[i], "-namespace") == 0 || strcmp(argv[i], "-object") == 0 || strcmp(argv[i], "-string") == 0) { ++i; } continue; } FILE* in = fopen(argv[i], "r"); if (!in) { return EXIT_FAILURE; } fprintf(out, "#pragma source \"%s\"\n", argv[i]); int ch; while ((ch = fgetc(in)) != EOF) { putc(ch, out); } fclose(in); } fclose(out); return EXIT_SUCCESS; } else if (0 < id) { // execute cpp close(0); dup(catStream[0]); close(catStream[0]); close(catStream[1]); close(1); dup(cppStream[1]); close(cppStream[0]); close(cppStream[1]); execvp(argCpp[0], const_cast<char**>(argCpp)); return EXIT_FAILURE; } else { return EXIT_FAILURE; } } else if (0 < id) { // Parent process - process an IDL file close(cppStream[1]); if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS) { return EXIT_FAILURE; } close(cppStream[0]); int status; while (wait(&status) != id) { } if (result == EXIT_SUCCESS) { if (!WIFEXITED(status)) { result = EXIT_FAILURE; } else { result = WEXITSTATUS(status); } } } else { return EXIT_FAILURE; } setBaseFilename(""); ProcessExtendedAttributes processExtendedAttributes; getSpecification()->accept(&processExtendedAttributes); AdjustMethodCount adjustMethodCount; getSpecification()->accept(&adjustMethodCount); for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-I") == 0 || strcmp(argv[i], "-include") == 0 || strcmp(argv[i], "-indent") == 0 || strcmp(argv[i], "-isystem") == 0 || strcmp(argv[i], "-namespace") == 0 || strcmp(argv[i], "-object") == 0 || strcmp(argv[i], "-string") == 0) { ++i; } continue; } result = output(argv[i], isystem, useExceptions, stringTypeName, indent, skeleton, generic); } return result; } <|endoftext|>
<commit_before>// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netbase.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; // // "Never go to sea with two chronometers; take one or three." // Our three time sources are: // - System clock // - Median of other nodes clocks // - The user (asking the user to fix the system clock if the first two disagree) // // int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } void AddTimeData(const CNetAddr& ip, int64_t nTime) { int64_t nOffsetSample = nTime - GetTime(); LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(200,0); vTimeOffsets.input(nOffsetSample); LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64_t n, vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } } <commit_msg>Add comment about never updating nTimeOffset past 199 samples<commit_after>// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netbase.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; // // "Never go to sea with two chronometers; take one or three." // Our three time sources are: // - System clock // - Median of other nodes clocks // - The user (asking the user to fix the system clock if the first two disagree) // // int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } void AddTimeData(const CNetAddr& ip, int64_t nTime) { int64_t nOffsetSample = nTime - GetTime(); LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(200,0); vTimeOffsets.input(nOffsetSample); LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64_t n, vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } } <|endoftext|>
<commit_before>#include "Scheduler.h" #include "ProblemStatement.h" #include <mpi.h> #include <stdexcept> Scheduler::Scheduler() : nodesHaveRatings(false), rank(MPI::COMM_WORLD.Get_rank()), elf(nullptr) { } Scheduler::Scheduler(const BenchmarkResult& benchmarkResult) : nodesHaveRatings(true), nodeSet(benchmarkResult), rank(MPI::COMM_WORLD.Get_rank()), elf(nullptr) { } void Scheduler::setNodeset(const BenchmarkResult& benchmarkResult) { nodeSet = benchmarkResult; } void Scheduler::setNodeset(NodeId singleNode) { nodeSet = {{singleNode, 0}}; } void Scheduler::dispatch(ProblemStatement& statement) { if (elf == nullptr) { throw std::runtime_error("Scheduler::dispatch(): No elf configured!"); } doDispatch(statement); } <commit_msg>Scheduler base class checks for non-empty node set<commit_after>#include "Scheduler.h" #include "ProblemStatement.h" #include <mpi.h> #include <stdexcept> Scheduler::Scheduler() : nodesHaveRatings(false), rank(MPI::COMM_WORLD.Get_rank()), elf(nullptr) { } Scheduler::Scheduler(const BenchmarkResult& benchmarkResult) : nodesHaveRatings(true), nodeSet(benchmarkResult), rank(MPI::COMM_WORLD.Get_rank()), elf(nullptr) { } void Scheduler::setNodeset(const BenchmarkResult& benchmarkResult) { nodeSet = benchmarkResult; } void Scheduler::setNodeset(NodeId singleNode) { nodeSet = {{singleNode, 0}}; } void Scheduler::dispatch(ProblemStatement& statement) { if (elf == nullptr) { throw std::runtime_error("Scheduler::dispatch(): No elf configured!"); } if (nodeSet.empty()) { throw std::runtime_error("Scheduler::dispatch(): Nodeset is empty!"); } doDispatch(statement); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Game NET - A Simple Network Tutorial for OpenGL Games // // (C) by Sven Forstmann in 2015 // // License : MIT // http://opensource.org/licenses/MIT //////////////////////////////////////////////////////////////////////////////// #include "core.h" #include "net_rpc.h" #include "net_client.h" #include "net_server.h" //////////////////////////////////////////////////////////////////////////////// // Simple Hello World //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Server Part NetServer server(12345,0); // RPC void hello_server(uint clientid, string s) { //cout << "Client " << clientid << " sends " << s << endl; server.call(clientid, "hello_client", "Greetings from Server"); static uint t = core_time() % 1000; uint t_now = core_time()%1000; static uint bench = 0; bench=bench+1; //cout << t_now - t << endl; if (t_now<t) { cout << bench << " RPCs/s " << endl; bench = 0; } t = t_now; } // Main void start_server() { Rpc &r = server.get_rpc(); rpc_register_remote(r, hello_client); rpc_register_local (r, hello_server); server.start(); //server.stop(); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Client Part NetClient client; // Client RPCs void hello_client(string s) { //cout << "Server sends " << s << endl; }; // Main void start_client() { Rpc &r = client.get_rpc(); rpc_register_local (r, hello_client); rpc_register_remote(r, hello_server); client.connect("localhost", 12345); uint c; while (client.connected()) { loopi(0, 20) client.call("hello_server", "Greetings"); client.process(); } //client.disconnect(); core_sleep(1000); server.stop(); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Main int main() { start_server(); start_client(); return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>minor update<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Game NET - A Simple Network Tutorial for OpenGL Games // // (C) by Sven Forstmann in 2015 // // License : MIT // http://opensource.org/licenses/MIT //////////////////////////////////////////////////////////////////////////////// #include "core.h" #include "net_rpc.h" #include "net_client.h" #include "net_server.h" //////////////////////////////////////////////////////////////////////////////// // Simple Hello World //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Server Part NetServer server(12345,0); // RPC void hello_server(uint clientid, string s) { //cout << "Client " << clientid << " sends " << s << endl; //server.call(clientid, "hello_client", "Greetings from Server"); static uint t = core_time() % 1000; uint t_now = core_time()%1000; static uint bench = 0; bench=bench+1; if (t_now<t) { cout << bench << " RPCs/s " << endl; bench = 0; } t = t_now; } // Main void start_server() { Rpc &r = server.get_rpc(); rpc_register_remote(r, hello_client); rpc_register_local (r, hello_server); server.start(); //server.stop(); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Client Part NetClient client; // Client RPCs void hello_client(string s) { //cout << "Server sends " << s << endl; }; // Main void start_client() { Rpc &r = client.get_rpc(); rpc_register_local (r, hello_client); rpc_register_remote(r, hello_server); client.connect("localhost", 12345); uint c; while (client.connected()) { loopi(0, 20) client.call("hello_server", "Greetings"); client.process(); } //client.disconnect(); core_sleep(1000); server.stop(); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Main int main() { start_server(); start_client(); return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <set> #include <chrono> #include <thread> #include <xmmintrin.h> #include "engine.hpp" #include "util.hpp" namespace rack { float gSampleRate; static bool running = false; static std::mutex mutex; static std::thread thread; static VIPMutex vipMutex; static std::set<Module*> modules; // Merely used for keeping track of which module inputs point to which module outputs, to prevent pointer mistakes and make the rack API more rigorous static std::set<Wire*> wires; // Parameter interpolation static Module *smoothModule = NULL; static int smoothParamId; static float smoothValue; void engineInit() { gSampleRate = 44100.0; } void engineDestroy() { // Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the GUI was destroyed. assert(wires.empty()); assert(modules.empty()); } static void engineStep() { // Param interpolation if (smoothModule) { float value = smoothModule->params[smoothParamId]; const float lambda = 60.0; // decay rate is 1 graphics frame const float snap = 0.0001; float delta = smoothValue - value; if (fabsf(delta) < snap) { smoothModule->params[smoothParamId] = smoothValue; smoothModule = NULL; } else { value += delta * lambda / gSampleRate; smoothModule->params[smoothParamId] = value; } } // Step all modules // std::chrono::time_point<std::chrono::high_resolution_clock> start, end; for (Module *module : modules) { // Start clock for CPU usage // start = std::chrono::high_resolution_clock::now(); // Step module by one frame module->step(); // Stop clock and smooth step time value // end = std::chrono::high_resolution_clock::now(); // std::chrono::duration<float> diff = end - start; // float elapsed = diff.count() * gSampleRate; // const float lambda = 1.0; // module->cpuTime += (elapsed - module->cpuTime) * lambda / gSampleRate; } // Step cables by moving their output values to inputs for (Wire *wire : wires) { wire->inputValue = wire->outputValue; wire->outputValue = 0.0; } } static void engineRun() { // Set CPU to denormals-are-zero mode // http://carlh.net/plugins/denormals.php _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); // Every time the engine waits and locks a mutex, it steps this many frames const int mutexSteps = 64; // Time in seconds that the engine is rushing ahead of the estimated clock time float ahead = 0.0; auto lastTime = std::chrono::high_resolution_clock::now(); while (running) { vipMutex.wait(); { std::lock_guard<std::mutex> lock(mutex); for (int i = 0; i < mutexSteps; i++) { engineStep(); } } float stepTime = mutexSteps / gSampleRate; ahead += stepTime; auto currTime = std::chrono::high_resolution_clock::now(); const float aheadFactor = 2.0; ahead -= aheadFactor * std::chrono::duration<float>(currTime - lastTime).count(); lastTime = currTime; ahead = fmaxf(ahead, 0.0); // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate // The number of steps to wait before possibly sleeping const float aheadMax = 1.0; // seconds if (ahead > aheadMax) { std::this_thread::sleep_for(std::chrono::duration<float>(stepTime)); } } } void engineStart() { running = true; thread = std::thread(engineRun); } void engineStop() { running = false; thread.join(); } void engineAddModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the module is not already added assert(modules.find(module) == modules.end()); modules.insert(module); } void engineRemoveModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // If a param is being smoothed on this module, remove it immediately if (module == smoothModule) { smoothModule = NULL; } // Check that all wires are disconnected for (Wire *wire : wires) { assert(wire->outputModule != module); assert(wire->inputModule != module); } auto it = modules.find(module); if (it != modules.end()) { modules.erase(it); } } void engineAddWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the wire is not already added assert(wires.find(wire) == wires.end()); assert(wire->outputModule); assert(wire->inputModule); // Check that the inputs/outputs are not already used by another cable for (Wire *wire2 : wires) { assert(wire2 != wire); assert(!(wire2->outputModule == wire->outputModule && wire2->outputId == wire->outputId)); assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId)); } // Add the wire wires.insert(wire); // Connect the wire to inputModule wire->inputModule->inputs[wire->inputId] = &wire->inputValue; wire->outputModule->outputs[wire->outputId] = &wire->outputValue; } void engineRemoveWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Disconnect wire from inputModule wire->inputModule->inputs[wire->inputId] = NULL; wire->outputModule->outputs[wire->outputId] = NULL; // Remove the wire auto it = wires.find(wire); assert(it != wires.end()); wires.erase(it); } void engineSetParamSmooth(Module *module, int paramId, float value) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) { smoothModule->params[smoothParamId] = smoothValue; } smoothModule = module; smoothParamId = paramId; smoothValue = value; } } // namespace rack <commit_msg>Use vector as data structure for Modules and Wires<commit_after>#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <vector> #include <algorithm> #include <chrono> #include <thread> #include <xmmintrin.h> #include "engine.hpp" #include "util.hpp" namespace rack { float gSampleRate; static bool running = false; static std::mutex mutex; static std::thread thread; static VIPMutex vipMutex; static std::vector<Module*> modules; // Merely used for keeping track of which module inputs point to which module outputs, to prevent pointer mistakes and make the rack API more rigorous static std::vector<Wire*> wires; // Parameter interpolation static Module *smoothModule = NULL; static int smoothParamId; static float smoothValue; void engineInit() { gSampleRate = 44100.0; } void engineDestroy() { // Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the GUI was destroyed. assert(wires.empty()); assert(modules.empty()); } static void engineStep() { // Param interpolation if (smoothModule) { float value = smoothModule->params[smoothParamId]; const float lambda = 60.0; // decay rate is 1 graphics frame const float snap = 0.0001; float delta = smoothValue - value; if (fabsf(delta) < snap) { smoothModule->params[smoothParamId] = smoothValue; smoothModule = NULL; } else { value += delta * lambda / gSampleRate; smoothModule->params[smoothParamId] = value; } } // Step modules for (size_t i = 0; i < modules.size(); i++) { Module *module = modules[i]; module->step(); } // Step cables by moving their output values to inputs for (Wire *wire : wires) { wire->inputValue = wire->outputValue; wire->outputValue = 0.0; } } static void engineRun() { // Set CPU to denormals-are-zero mode // http://carlh.net/plugins/denormals.php _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); // Every time the engine waits and locks a mutex, it steps this many frames const int mutexSteps = 64; // Time in seconds that the engine is rushing ahead of the estimated clock time float ahead = 0.0; auto lastTime = std::chrono::high_resolution_clock::now(); while (running) { vipMutex.wait(); { std::lock_guard<std::mutex> lock(mutex); for (int i = 0; i < mutexSteps; i++) { engineStep(); } } float stepTime = mutexSteps / gSampleRate; ahead += stepTime; auto currTime = std::chrono::high_resolution_clock::now(); const float aheadFactor = 2.0; ahead -= aheadFactor * std::chrono::duration<float>(currTime - lastTime).count(); lastTime = currTime; ahead = fmaxf(ahead, 0.0); // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate // The number of steps to wait before possibly sleeping const float aheadMax = 1.0; // seconds if (ahead > aheadMax) { std::this_thread::sleep_for(std::chrono::duration<float>(stepTime)); } } } void engineStart() { running = true; thread = std::thread(engineRun); } void engineStop() { running = false; thread.join(); } void engineAddModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the module is not already added auto it = std::find(modules.begin(), modules.end(), module); assert(it == modules.end()); modules.push_back(module); } void engineRemoveModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // If a param is being smoothed on this module, remove it immediately if (module == smoothModule) { smoothModule = NULL; } // Check that all wires are disconnected for (Wire *wire : wires) { assert(wire->outputModule != module); assert(wire->inputModule != module); } auto it = std::find(modules.begin(), modules.end(), module); assert(it != modules.end()); modules.erase(it); } void engineAddWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the wire is not already added auto it = std::find(wires.begin(), wires.end(), wire); assert(it == wires.end()); assert(wire->outputModule); assert(wire->inputModule); // Check that the inputs/outputs are not already used by another cable for (Wire *wire2 : wires) { assert(wire2 != wire); assert(!(wire2->outputModule == wire->outputModule && wire2->outputId == wire->outputId)); assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId)); } // Add the wire wires.push_back(wire); // Connect the wire to inputModule wire->inputModule->inputs[wire->inputId] = &wire->inputValue; wire->outputModule->outputs[wire->outputId] = &wire->outputValue; } void engineRemoveWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Disconnect wire from inputModule wire->inputModule->inputs[wire->inputId] = NULL; wire->outputModule->outputs[wire->outputId] = NULL; // Remove the wire auto it = std::find(wires.begin(), wires.end(), wire); assert(it != wires.end()); wires.erase(it); } void engineSetParamSmooth(Module *module, int paramId, float value) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) { smoothModule->params[smoothParamId] = smoothValue; } smoothModule = module; smoothParamId = paramId; smoothValue = value; } } // namespace rack <|endoftext|>
<commit_before>#include "Session.hpp" #include <stdexcept> #include <QtNetwork> #include <QTimer> #include <QUrl> #include <QDataStream> #include "utils.hpp" #include "Matrix.hpp" #include "parse.hpp" namespace matrix { constexpr uint64_t CACHE_FORMAT_VERSION = 1; // Bumped every time a backwards-incompatible format change is made, a // corruption bug is fixed, or a previously ignored class of state is // persisted static constexpr char POLL_TIMEOUT_MS[] = "50000"; static const lmdb::val next_batch_key("next_batch"); static const lmdb::val transaction_id_key("transaction_id"); static const lmdb::val cache_format_version_key("cache_format_version"); template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr T from_little_endian(const uint8_t *x) { T result{0}; for(size_t i = 0; i < sizeof(T); ++i) { result |= static_cast<T>(x[i]) << (8*i); } return result; } template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr void to_little_endian(T v, uint8_t *x) { for(size_t i = 0; i < sizeof(T); ++i) { x[i] = (v >> (8*i)) & 0xFF; } } std::unique_ptr<Session> Session::create(Matrix& universe, QUrl homeserver, QString user_id, QString access_token) { auto env = lmdb::env::create(); env.set_mapsize(128UL * 1024UL * 1024UL); // 128MB should be enough for anyone! env.set_max_dbs(1024UL); // maximum rooms plus two QString state_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) % "/" % QString::fromUtf8(user_id.toUtf8().toHex() % "/state"); bool fresh = !QFile::exists(state_path); if(!QDir().mkpath(state_path)) { throw std::runtime_error(("unable to create state directory at " + state_path).toStdString().c_str()); } env.open(state_path.toStdString().c_str()); auto txn = lmdb::txn::begin(env); auto state_db = lmdb::dbi::open(txn, "state", MDB_CREATE); auto room_db = lmdb::dbi::open(txn, "rooms", MDB_CREATE); if(!fresh) { bool compatible = false; lmdb::val x; if(lmdb::dbi_get(txn, state_db, cache_format_version_key, x)) { compatible = CACHE_FORMAT_VERSION == from_little_endian<uint64_t>(x.data<const uint8_t>()); } if(!compatible) { qDebug() << "incompatible cache, resetting it"; lmdb::dbi_drop(txn, state_db, false); lmdb::dbi_drop(txn, room_db, false); fresh = true; } } if(fresh) { uint8_t data[8]; to_little_endian(CACHE_FORMAT_VERSION, data); lmdb::val val(data, sizeof(data)); lmdb::dbi_put(txn, state_db, cache_format_version_key, val); } txn.commit(); return std::make_unique<Session>(universe, std::move(homeserver), std::move(user_id), std::move(access_token), std::move(env), std::move(state_db), std::move(room_db)); } static std::string room_dbname(const QString &room_id) { return ("r." + room_id).toStdString(); } Session::Session(Matrix& universe, QUrl homeserver, QString user_id, QString access_token, lmdb::env &&env, lmdb::dbi &&state_db, lmdb::dbi &&room_db) : universe_(universe), homeserver_(homeserver), user_id_(user_id), access_token_(access_token), env_(std::move(env)), state_db_(std::move(state_db)), room_db_(std::move(room_db)), buffer_size_(50), synced_(false) { { auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY); lmdb::val stored_batch; if(lmdb::dbi_get(txn, state_db_, next_batch_key, stored_batch)) { next_batch_ = QString::fromUtf8(stored_batch.data(), stored_batch.size()); qDebug() << "resuming from" << next_batch_; lmdb::val room; lmdb::val state; auto cursor = lmdb::cursor::open(txn, room_db_); while(cursor.get(room, state, MDB_NEXT)) { auto id = QString::fromUtf8(room.data(), room.size()); rooms_.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(universe_, *this, id, QJsonDocument::fromBinaryData(QByteArray(state.data(), state.size())).object(), env_, txn, lmdb::dbi::open(txn, room_dbname(id).c_str()))); } } else { qDebug() << "starting from scratch"; } txn.commit(); } sync_retry_timer_.setSingleShot(true); connect(&sync_retry_timer_, &QTimer::timeout, this, static_cast<void (Session::*)()>(&Session::sync)); QUrlQuery query; query.addQueryItem("filter", encode({ {"room", QJsonObject{ {"timeline", QJsonObject{ {"limit", static_cast<int>(buffer_size_)} }}, }} })); sync(query); } void Session::sync() { // This method exists so that we can hook Qt signals to it without worrying about default arguments. sync(QUrlQuery()); } void Session::sync(QUrlQuery query) { if(next_batch_.isNull()) { query.addQueryItem("full_state", "true"); } else { query.addQueryItem("since", next_batch_); query.addQueryItem("timeout", POLL_TIMEOUT_MS); } sync_reply_ = get("client/r0/sync", query); connect(sync_reply_, &QNetworkReply::finished, this, &Session::handle_sync_reply); connect(sync_reply_, &QNetworkReply::downloadProgress, this, &Session::sync_progress); } void Session::handle_sync_reply() { sync_progress(0, 0); if(sync_reply_->size() > (1 << 12)) { qDebug() << "sync is" << sync_reply_->size() << "bytes"; } using namespace std::chrono_literals; auto r = decode(sync_reply_); bool was_synced = synced_; if(r.error) { synced_ = false; error(*r.error); } else { QString current_batch = next_batch_; try { auto s = parse_sync(r.object); auto txn = lmdb::txn::begin(env_); active_txn_ = &txn; try { auto batch_utf8 = s.next_batch.toUtf8(); lmdb::dbi_put(txn, state_db_, next_batch_key, lmdb::val(batch_utf8.data(), batch_utf8.size())); next_batch_ = s.next_batch; dispatch(txn, std::move(s)); txn.commit(); } catch(...) { active_txn_ = nullptr; throw; } active_txn_ = nullptr; synced_ = true; } catch(lmdb::runtime_error &e) { synced_ = false; next_batch_ = current_batch; error(e.what()); } } if(was_synced != synced_) synced_changed(); auto now = std::chrono::steady_clock::now(); constexpr std::chrono::steady_clock::duration RETRY_INTERVAL = 10s; auto since_last_error = now - last_sync_error_; if(!synced_ && (since_last_error < RETRY_INTERVAL)) { sync_retry_timer_.start(std::chrono::duration_cast<std::chrono::milliseconds>(RETRY_INTERVAL - since_last_error).count()); } else { sync(); } if(!synced_) { last_sync_error_ = now; } } void Session::dispatch(lmdb::txn &txn, proto::Sync sync) { // TODO: Exception-safety: copy all room states, update and them and db, commit, swap copy/orig, emit signals for(auto &joined_room : sync.rooms.join) { auto it = rooms_.find(joined_room.id); bool new_room = false; if(it == rooms_.end()) { auto db = lmdb::dbi::open(txn, room_dbname(joined_room.id).c_str(), MDB_CREATE); it = rooms_.emplace(std::piecewise_construct, std::forward_as_tuple(joined_room.id), std::forward_as_tuple(universe_, *this, joined_room.id, QJsonObject(), env_, txn, std::move(db))).first; new_room = true; } auto &room = it->second; room.load_state(txn, joined_room.state.events); room.dispatch(txn, joined_room); // Mandatory write, since either the buffer or state has almost certainly changed cache_state(txn, room); if(new_room) joined(room); } sync_complete(); } void Session::cache_state(lmdb::txn &txn, const Room &room) { auto data = QJsonDocument(room.to_json()).toBinaryData(); auto utf8 = room.id().toUtf8(); lmdb::dbi_put(txn, room_db_, lmdb::val(utf8.data(), utf8.size()), lmdb::val(data.data(), data.size())); } void Session::log_out() { auto reply = post("client/r0/logout", {}); connect(reply, &QNetworkReply::finished, [this, reply](){ auto r = decode(reply); if(!r.error || r.code == 404) { // 404 = already logged out logged_out(); } else { error(*r.error); } }); } std::vector<Room *> Session::rooms() { std::vector<Room *> result; result.reserve(rooms_.size()); std::transform(rooms_.begin(), rooms_.end(), std::back_inserter(result), [](auto &x) { return &x.second; }); return result; } QNetworkRequest Session::request(const QString &path, QUrlQuery query, const QString &content_type) { QUrl url(homeserver_); url.setPath("/_matrix/" + path, QUrl::StrictMode); query.addQueryItem("access_token", access_token_); url.setQuery(query); QNetworkRequest req(url); req.setHeader(QNetworkRequest::ContentTypeHeader, content_type); return req; } QNetworkReply *Session::get(const QString &path, QUrlQuery query) { auto reply = universe_.net.get(request(path, query)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::post(const QString &path, QJsonObject body, QUrlQuery query) { auto reply = universe_.net.post(request(path, query), encode(body)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::post(const QString &path, QIODevice *data, const QString &content_type, const QString &filename) { QUrlQuery query; query.addQueryItem("filename", filename); auto reply = universe_.net.post(request(path, query, content_type), data); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::put(const QString &path, QJsonObject body) { auto reply = universe_.net.put(request(path), encode(body)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } ContentFetch *Session::get(const Content &content) { auto reply = get("media/r0/download/" % content.host() % "/" % content.id()); auto result = new ContentFetch(reply); connect(reply, &QNetworkReply::finished, [content, reply, result]() { if(reply->error()) { result->error(reply->errorString()); } else { result->finished(content, reply->header(QNetworkRequest::ContentTypeHeader).toString(), reply->header(QNetworkRequest::ContentDispositionHeader).toString(), reply->readAll()); } }); return result; } ContentFetch *Session::get_thumbnail(const Content &content, const QSize &size, ThumbnailMethod method) { QUrlQuery query; query.addQueryItem("access_token", access_token_); query.addQueryItem("width", QString::number(size.width())); query.addQueryItem("height", QString::number(size.height())); query.addQueryItem("method", method == ThumbnailMethod::SCALE ? "scale" : "crop"); auto reply = get("media/r0/thumbnail/" % content.host() % "/" % content.id(), query); auto result = new ContentFetch(reply); connect(reply, &QNetworkReply::finished, [content, reply, result]() { if(reply->error()) { result->error(reply->errorString()); } else { result->finished(content, reply->header(QNetworkRequest::ContentTypeHeader).toString(), reply->header(QNetworkRequest::ContentDispositionHeader).toString(), reply->readAll()); } }); return result; } QString Session::get_transaction_id() { auto txn = lmdb::txn::begin(env_); uint64_t value; lmdb::val x; if(lmdb::dbi_get(txn, state_db_, transaction_id_key, x)) { value = from_little_endian<uint64_t>(x.data<const uint8_t>()); } else { value = 0; } uint8_t data[8]; to_little_endian(value + 1, data); lmdb::val y(data, sizeof(data)); lmdb::dbi_put(txn, state_db_, transaction_id_key, y); txn.commit(); return QString::number(value, 36); } JoinRequest *Session::join(const QString &id_or_alias) { auto reply = post("client/r0/join/" + QUrl::toPercentEncoding(id_or_alias), {}); auto req = new JoinRequest(reply); connect(reply, &QNetworkReply::finished, [reply, req]() { auto r = decode(reply); if(r.error) { req->error(*r.error); } else { req->success(r.object["room_id"].toString()); } }); return req; } QUrl Session::ensure_http(const QUrl &url) const { if(url.scheme() == "mxc") { return matrix::Content(url).url_on(homeserver()); } return url; } void Session::cache_state(const Room &room) { if(active_txn_) return; // State will be cached after sync processing completes auto txn = lmdb::txn::begin(env_); cache_state(txn, room); txn.commit(); } } <commit_msg>Try to safely handle LMDB version changes<commit_after>#include "Session.hpp" #include <stdexcept> #include <QtNetwork> #include <QTimer> #include <QUrl> #include <QDataStream> #include "utils.hpp" #include "Matrix.hpp" #include "parse.hpp" namespace matrix { constexpr uint64_t CACHE_FORMAT_VERSION = 1; // Bumped every time a backwards-incompatible format change is made, a // corruption bug is fixed, or a previously ignored class of state is // persisted static constexpr char POLL_TIMEOUT_MS[] = "50000"; static const lmdb::val next_batch_key("next_batch"); static const lmdb::val transaction_id_key("transaction_id"); static const lmdb::val cache_format_version_key("cache_format_version"); template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr T from_little_endian(const uint8_t *x) { T result{0}; for(size_t i = 0; i < sizeof(T); ++i) { result |= static_cast<T>(x[i]) << (8*i); } return result; } template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> constexpr void to_little_endian(T v, uint8_t *x) { for(size_t i = 0; i < sizeof(T); ++i) { x[i] = (v >> (8*i)) & 0xFF; } } std::unique_ptr<Session> Session::create(Matrix& universe, QUrl homeserver, QString user_id, QString access_token) { auto env = lmdb::env::create(); env.set_mapsize(128UL * 1024UL * 1024UL); // 128MB should be enough for anyone! env.set_max_dbs(1024UL); // maximum rooms plus two QString state_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) % "/" % QString::fromUtf8(user_id.toUtf8().toHex() % "/state"); bool fresh = !QFile::exists(state_path); if(!QDir().mkpath(state_path)) { throw std::runtime_error(("unable to create state directory at " + state_path).toStdString().c_str()); } try { env.open(state_path.toStdString().c_str()); } catch(const lmdb::version_mismatch_error &e) { qDebug() << "resetting cache due to LMDB version mismatch:" << e.what(); QDir state_dir(state_path); for(const auto &file : state_dir.entryList(QDir::NoDotAndDotDot)) { if(!state_dir.remove(file)) { throw std::runtime_error(("unable to delete state file " + state_path + file).toStdString().c_str()); } } env.open(state_path.toStdString().c_str()); } auto txn = lmdb::txn::begin(env); auto state_db = lmdb::dbi::open(txn, "state", MDB_CREATE); auto room_db = lmdb::dbi::open(txn, "rooms", MDB_CREATE); if(!fresh) { bool compatible = false; lmdb::val x; if(lmdb::dbi_get(txn, state_db, cache_format_version_key, x)) { compatible = CACHE_FORMAT_VERSION == from_little_endian<uint64_t>(x.data<const uint8_t>()); } if(!compatible) { qDebug() << "resetting cache due to breaking changes or fixes"; lmdb::dbi_drop(txn, state_db, false); lmdb::dbi_drop(txn, room_db, false); fresh = true; } } if(fresh) { uint8_t data[8]; to_little_endian(CACHE_FORMAT_VERSION, data); lmdb::val val(data, sizeof(data)); lmdb::dbi_put(txn, state_db, cache_format_version_key, val); } txn.commit(); return std::make_unique<Session>(universe, std::move(homeserver), std::move(user_id), std::move(access_token), std::move(env), std::move(state_db), std::move(room_db)); } static std::string room_dbname(const QString &room_id) { return ("r." + room_id).toStdString(); } Session::Session(Matrix& universe, QUrl homeserver, QString user_id, QString access_token, lmdb::env &&env, lmdb::dbi &&state_db, lmdb::dbi &&room_db) : universe_(universe), homeserver_(homeserver), user_id_(user_id), access_token_(access_token), env_(std::move(env)), state_db_(std::move(state_db)), room_db_(std::move(room_db)), buffer_size_(50), synced_(false) { { auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY); lmdb::val stored_batch; if(lmdb::dbi_get(txn, state_db_, next_batch_key, stored_batch)) { next_batch_ = QString::fromUtf8(stored_batch.data(), stored_batch.size()); qDebug() << "resuming from" << next_batch_; lmdb::val room; lmdb::val state; auto cursor = lmdb::cursor::open(txn, room_db_); while(cursor.get(room, state, MDB_NEXT)) { auto id = QString::fromUtf8(room.data(), room.size()); rooms_.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(universe_, *this, id, QJsonDocument::fromBinaryData(QByteArray(state.data(), state.size())).object(), env_, txn, lmdb::dbi::open(txn, room_dbname(id).c_str()))); } } else { qDebug() << "starting from scratch"; } txn.commit(); } sync_retry_timer_.setSingleShot(true); connect(&sync_retry_timer_, &QTimer::timeout, this, static_cast<void (Session::*)()>(&Session::sync)); QUrlQuery query; query.addQueryItem("filter", encode({ {"room", QJsonObject{ {"timeline", QJsonObject{ {"limit", static_cast<int>(buffer_size_)} }}, }} })); sync(query); } void Session::sync() { // This method exists so that we can hook Qt signals to it without worrying about default arguments. sync(QUrlQuery()); } void Session::sync(QUrlQuery query) { if(next_batch_.isNull()) { query.addQueryItem("full_state", "true"); } else { query.addQueryItem("since", next_batch_); query.addQueryItem("timeout", POLL_TIMEOUT_MS); } sync_reply_ = get("client/r0/sync", query); connect(sync_reply_, &QNetworkReply::finished, this, &Session::handle_sync_reply); connect(sync_reply_, &QNetworkReply::downloadProgress, this, &Session::sync_progress); } void Session::handle_sync_reply() { sync_progress(0, 0); if(sync_reply_->size() > (1 << 12)) { qDebug() << "sync is" << sync_reply_->size() << "bytes"; } using namespace std::chrono_literals; auto r = decode(sync_reply_); bool was_synced = synced_; if(r.error) { synced_ = false; error(*r.error); } else { QString current_batch = next_batch_; try { auto s = parse_sync(r.object); auto txn = lmdb::txn::begin(env_); active_txn_ = &txn; try { auto batch_utf8 = s.next_batch.toUtf8(); lmdb::dbi_put(txn, state_db_, next_batch_key, lmdb::val(batch_utf8.data(), batch_utf8.size())); next_batch_ = s.next_batch; dispatch(txn, std::move(s)); txn.commit(); } catch(...) { active_txn_ = nullptr; throw; } active_txn_ = nullptr; synced_ = true; } catch(lmdb::runtime_error &e) { synced_ = false; next_batch_ = current_batch; error(e.what()); } } if(was_synced != synced_) synced_changed(); auto now = std::chrono::steady_clock::now(); constexpr std::chrono::steady_clock::duration RETRY_INTERVAL = 10s; auto since_last_error = now - last_sync_error_; if(!synced_ && (since_last_error < RETRY_INTERVAL)) { sync_retry_timer_.start(std::chrono::duration_cast<std::chrono::milliseconds>(RETRY_INTERVAL - since_last_error).count()); } else { sync(); } if(!synced_) { last_sync_error_ = now; } } void Session::dispatch(lmdb::txn &txn, proto::Sync sync) { // TODO: Exception-safety: copy all room states, update and them and db, commit, swap copy/orig, emit signals for(auto &joined_room : sync.rooms.join) { auto it = rooms_.find(joined_room.id); bool new_room = false; if(it == rooms_.end()) { auto db = lmdb::dbi::open(txn, room_dbname(joined_room.id).c_str(), MDB_CREATE); it = rooms_.emplace(std::piecewise_construct, std::forward_as_tuple(joined_room.id), std::forward_as_tuple(universe_, *this, joined_room.id, QJsonObject(), env_, txn, std::move(db))).first; new_room = true; } auto &room = it->second; room.load_state(txn, joined_room.state.events); room.dispatch(txn, joined_room); // Mandatory write, since either the buffer or state has almost certainly changed cache_state(txn, room); if(new_room) joined(room); } sync_complete(); } void Session::cache_state(lmdb::txn &txn, const Room &room) { auto data = QJsonDocument(room.to_json()).toBinaryData(); auto utf8 = room.id().toUtf8(); lmdb::dbi_put(txn, room_db_, lmdb::val(utf8.data(), utf8.size()), lmdb::val(data.data(), data.size())); } void Session::log_out() { auto reply = post("client/r0/logout", {}); connect(reply, &QNetworkReply::finished, [this, reply](){ auto r = decode(reply); if(!r.error || r.code == 404) { // 404 = already logged out logged_out(); } else { error(*r.error); } }); } std::vector<Room *> Session::rooms() { std::vector<Room *> result; result.reserve(rooms_.size()); std::transform(rooms_.begin(), rooms_.end(), std::back_inserter(result), [](auto &x) { return &x.second; }); return result; } QNetworkRequest Session::request(const QString &path, QUrlQuery query, const QString &content_type) { QUrl url(homeserver_); url.setPath("/_matrix/" + path, QUrl::StrictMode); query.addQueryItem("access_token", access_token_); url.setQuery(query); QNetworkRequest req(url); req.setHeader(QNetworkRequest::ContentTypeHeader, content_type); return req; } QNetworkReply *Session::get(const QString &path, QUrlQuery query) { auto reply = universe_.net.get(request(path, query)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::post(const QString &path, QJsonObject body, QUrlQuery query) { auto reply = universe_.net.post(request(path, query), encode(body)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::post(const QString &path, QIODevice *data, const QString &content_type, const QString &filename) { QUrlQuery query; query.addQueryItem("filename", filename); auto reply = universe_.net.post(request(path, query, content_type), data); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } QNetworkReply *Session::put(const QString &path, QJsonObject body) { auto reply = universe_.net.put(request(path), encode(body)); connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater); return reply; } ContentFetch *Session::get(const Content &content) { auto reply = get("media/r0/download/" % content.host() % "/" % content.id()); auto result = new ContentFetch(reply); connect(reply, &QNetworkReply::finished, [content, reply, result]() { if(reply->error()) { result->error(reply->errorString()); } else { result->finished(content, reply->header(QNetworkRequest::ContentTypeHeader).toString(), reply->header(QNetworkRequest::ContentDispositionHeader).toString(), reply->readAll()); } }); return result; } ContentFetch *Session::get_thumbnail(const Content &content, const QSize &size, ThumbnailMethod method) { QUrlQuery query; query.addQueryItem("access_token", access_token_); query.addQueryItem("width", QString::number(size.width())); query.addQueryItem("height", QString::number(size.height())); query.addQueryItem("method", method == ThumbnailMethod::SCALE ? "scale" : "crop"); auto reply = get("media/r0/thumbnail/" % content.host() % "/" % content.id(), query); auto result = new ContentFetch(reply); connect(reply, &QNetworkReply::finished, [content, reply, result]() { if(reply->error()) { result->error(reply->errorString()); } else { result->finished(content, reply->header(QNetworkRequest::ContentTypeHeader).toString(), reply->header(QNetworkRequest::ContentDispositionHeader).toString(), reply->readAll()); } }); return result; } QString Session::get_transaction_id() { auto txn = lmdb::txn::begin(env_); uint64_t value; lmdb::val x; if(lmdb::dbi_get(txn, state_db_, transaction_id_key, x)) { value = from_little_endian<uint64_t>(x.data<const uint8_t>()); } else { value = 0; } uint8_t data[8]; to_little_endian(value + 1, data); lmdb::val y(data, sizeof(data)); lmdb::dbi_put(txn, state_db_, transaction_id_key, y); txn.commit(); return QString::number(value, 36); } JoinRequest *Session::join(const QString &id_or_alias) { auto reply = post("client/r0/join/" + QUrl::toPercentEncoding(id_or_alias), {}); auto req = new JoinRequest(reply); connect(reply, &QNetworkReply::finished, [reply, req]() { auto r = decode(reply); if(r.error) { req->error(*r.error); } else { req->success(r.object["room_id"].toString()); } }); return req; } QUrl Session::ensure_http(const QUrl &url) const { if(url.scheme() == "mxc") { return matrix::Content(url).url_on(homeserver()); } return url; } void Session::cache_state(const Room &room) { if(active_txn_) return; // State will be cached after sync processing completes auto txn = lmdb::txn::begin(env_); cache_state(txn, room); txn.commit(); } } <|endoftext|>
<commit_before>#include <stdlib.h> #include<string.h> #ifdef __APPLE__ #include <unistd.h> #else #include <argp.h> #endif #include <stdio.h> #include <string> #include <iostream> #include <FatUtils.h> #include <core/FatSystem.h> #include <core/FatPath.h> #include <table/FatBackup.h> #include <table/FatDiff.h> #include <analysis/FatChains.h> #include <analysis/FatExtract.h> #include <analysis/FatFix.h> #include <analysis/FatSearch.h> #define ATOU(i) ((unsigned int)atoi(i)) using namespace std; void usage() { cout << "fatcat v1.0.6, Gregwar <g.passault@gmail.com>" << endl; cout << endl; cout << "Usage: fatcat disk.img [options]" << endl; cout << " -i: display information about disk" << endl; cout << " -O [offset]: global offset (may be partition place)" << endl; cout << " -F [format]: output format (default, json)" << endl; cout << endl; cout << "Browsing & extracting:" << endl; cout << " -l [dir]: list files and directories in the given path" << endl; cout << " -L [cluster]: list files and directories in the given cluster" << endl; cout << " -r [path]: reads the file given by the path" << endl; cout << " -R [cluster]: reads the data from given cluster" << endl; cout << " -s [size]: specify the size of data to read from the cluster" << endl; cout << " -d: enable listing of deleted files" << endl; cout << " -x [directory]: extract all files to a directory, deleted files included if -d" << endl; cout << " will start with rootDirectory, unless -c is provided" << endl; cout << "* -S: write scamble data in unallocated sectors" << endl; cout << "* -z: write scamble data in unallocated sectors" << endl; cout << endl; cout << "FAT Hacking" << endl; cout << " -@ [cluster]: Get the cluster address and information" << endl; cout << " -2: analysis & compare the 2 FATs" << endl; cout << " -b [file]: backup the FATs (see -t)" << endl; cout << "* -p [file]: restore (patch) the FATs (see -t)" << endl; cout << "* -w [cluster] -v [value]: write next cluster (see -t)" << endl; cout << " -t [table]: specify which table to write (0:both, 1:first, 2:second)" << endl; cout << "* -m: merge the FATs" << endl; cout << " -o: search for orphan files and directories" << endl; cout << "* -f: try to fix reachable directories" << endl; cout << endl; cout << "Entries hacking" << endl; cout << " -e [path]: sets the entry to hack, combined with:" << endl; cout << "* -c [cluster]: sets the entry cluster" << endl; cout << "* -s [size]: sets the entry size" << endl; cout << "* -a [attributes]: sets the entry attributes" << endl; cout << " -k [cluster]: try to find an entry that point to that cluster" << endl; cout << endl; cout << "*: These flags writes on the disk, and may damage it, be careful" << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { vector<string> arguments; char *image = NULL; int index; // -O offset unsigned long long globalOffset = 0; // -s, specify the size to be read unsigned int size = -1; // -i, display information about the disk bool infoFlag = false; // -l, list directories in the given path bool listFlag = false; string listPath; // -c, listing for a direct cluster bool listClusterFlag = false; unsigned int listCluster; // -r, reads a file bool readFlag = false; string readPath; // -R, reads from cluster file bool clusterRead = false; unsigned int cluster = 0; // -d, lists deleted bool listDeleted = false; // -x: extract bool extract = false; string extractDirectory; // -2: compare two fats bool compare = false; // -@: get the cluster address bool address = false; // -k: analysis the chains bool chains = false; // -b: backup the fats bool backup = false; bool patch = false; string backupFile; // -w: write next cluster bool writeNext = false; // -m: merge the FATs bool merge = false; // -v: value bool hasValue = false; unsigned int value; // -t: FAT table to write or read unsigned int table = 0; // -S: write random data in unallocated sectors bool scramble = false; bool zero = false; // -f: fix reachable bool fixReachable = false; // -e: entry hacking bool entry = false; string entryPath; bool clusterProvided = false; bool sizeProvided = false; int attributes = 0; bool attributesProvided = false; // -k: entry finder bool findEntry = false; OutputType output = Default; // Parsing command line while ((index = getopt(argc, argv, "il:L:r:R:s:dc:hx:2@:ob:p:w:v:mt:Sze:O:fk:a:F:")) != -1) { switch (index) { case 'a': attributesProvided = true; attributes = atoi(optarg); break; case 'k': findEntry = true; cluster = atoi(optarg); break; case 'f': fixReachable = true; break; case 'O': globalOffset = atoll(optarg); break; case 'e': entry = true; entryPath = string(optarg); break; case 'z': zero = true; break; case 'S': scramble = true; break; case 't': table = ATOU(optarg); break; case 'm': merge = true; break; case 'v': hasValue = true; value = ATOU(optarg); break; case 'w': writeNext = true; cluster = ATOU(optarg); break; case '@': address = true; cluster = ATOU(optarg); break; case 'o': chains = true; break; case 'i': infoFlag = true; break; case 'l': listFlag = true; listPath = string(optarg); break; case 'L': listClusterFlag = true; listCluster = ATOU(optarg); break; case 'r': readFlag = true; readPath = string(optarg); break; case 'R': clusterRead = true; cluster = ATOU(optarg); break; case 's': size = ATOU(optarg); sizeProvided = true; break; case 'd': listDeleted = true; break; case 'c': cluster = ATOU(optarg); clusterProvided = true; break; case 'x': extract = true; extractDirectory = string(optarg); break; case '2': compare = true; break; case 'b': backup = true; backupFile = string(optarg); break; case 'p': patch = true; backupFile = string(optarg); break; case 'h': usage(); break; case 'F': if (strcmp(optarg, "json") == 0) output = Json; else if (strcmp(optarg, "default") == 0) output = Default; else { usage(); } break; } } // Trying to get the FAT file or device if (optind != argc) { image = argv[optind]; } if (!image) { usage(); } // Getting extra arguments for (index=optind+1; index<argc; index++) { arguments.push_back(argv[index]); } // If the user did not required any actions if (!(infoFlag || listFlag || listClusterFlag || readFlag || clusterRead || extract || compare || address || chains || backup || patch || writeNext || merge || scramble || zero || entry || fixReachable || findEntry)) { usage(); } try { // Openning the image FatSystem fat(image, globalOffset); fat.setListDeleted(listDeleted); if (fat.init()) { if (infoFlag) { fat.infos(); } else if (listFlag) { cout << "Listing path " << listPath << endl; FatPath path(listPath); fat.list(path); } else if (listClusterFlag) { cout << "Listing cluster " << listCluster << endl; fat.list(listCluster); } else if (readFlag) { FatPath path(readPath); fat.readFile(path); } else if (clusterRead) { fat.readFile(cluster, size); } else if (extract) { FatExtract extract(fat); extract.extract(cluster, extractDirectory, listDeleted); } else if (compare) { FatDiff diff(fat); diff.compare(); } else if (address) { cout << "Cluster " << cluster << " address:" << endl; long long addr = fat.clusterAddress(cluster); printf("%llu (%016llx)\n", addr, addr); cout << "Next cluster:" << endl; int next1 = fat.nextCluster(cluster, 0); int next2 = fat.nextCluster(cluster, 1); printf("FAT1: %u (%08x)\n", next1, next1); printf("FAT2: %u (%08x)\n", next2, next2); bool isContiguous = false; FatChains chains(fat); unsigned long long size = chains.chainSize(cluster, &isContiguous); printf("Chain size: %llu (%llu / %s)\n", size, size*fat.bytesPerCluster, prettySize(size*fat.bytesPerCluster).c_str()); if (isContiguous) { printf("Chain is contiguous\n"); } else { printf("Chain is not contiguous\n"); } } else if (chains) { FatChains chains(fat); chains.chainsAnalysis(); } else if (fixReachable) { FatFix fix(fat); fix.fix(); } else if (findEntry) { FatSearch search(fat); search.search(cluster); } else if (backup || patch) { FatBackup backupSystem(fat); if (backup) { backupSystem.backup(backupFile, table); } else { backupSystem.patch(backupFile, table); } } else if (writeNext) { if (!hasValue) { throw string("You should provide a value with -v"); } int prev = fat.nextCluster(cluster); printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value); fat.enableWrite(); if (table == 0 || table == 1) { printf("Writing on FAT1\n"); fat.writeNextCluster(cluster, value, 0); } if (table == 0 || table == 2) { printf("Writing on FAT2\n"); fat.writeNextCluster(cluster, value, 1); } } else if (merge) { FatDiff diff(fat); diff.merge(); } else if (scramble) { fat.enableWrite(); fat.rewriteUnallocated(1); } else if (zero) { fat.enableWrite(); fat.rewriteUnallocated(); } else if (entry) { cout << "Searching entry for " << entryPath << endl; FatPath path(entryPath); FatEntry entry; if (fat.findFile(path, entry)) { printf("Entry address %016llx\n", entry.address); printf("Attributes %02X\n", entry.attributes); cout << "Found entry, cluster=" << entry.cluster; if (entry.isDirectory()) { cout << ", directory"; } else { cout << ", file with size=" << entry.size << " (" << prettySize(entry.size) << ")"; } cout << endl; if (clusterProvided) { cout << "Setting the cluster to " << cluster << endl; entry.cluster = cluster; } if (sizeProvided) { cout << "Setting the size to " << size << endl; entry.size = size&0xffffffff; } if (attributesProvided) { cout << "Setting attributes to " << attributes << endl; entry.attributes = attributes; } if (clusterProvided || sizeProvided || attributesProvided) { entry.updateData(); fat.enableWrite(); string data = entry.data; fat.writeData(entry.address, data.c_str(), entry.data.size()); } } else { cout << "Entry not found." << endl; } } } else { cout << "! Failed to init the FAT filesystem" << endl; } } catch (string error) { cerr << "Error: " << error << endl; } exit(EXIT_SUCCESS); } <commit_msg>Passing the output format to the constructor<commit_after>#include <stdlib.h> #include<string.h> #ifdef __APPLE__ #include <unistd.h> #else #include <argp.h> #endif #include <stdio.h> #include <string> #include <iostream> #include <FatUtils.h> #include <core/FatSystem.h> #include <core/FatPath.h> #include <table/FatBackup.h> #include <table/FatDiff.h> #include <analysis/FatChains.h> #include <analysis/FatExtract.h> #include <analysis/FatFix.h> #include <analysis/FatSearch.h> #define ATOU(i) ((unsigned int)atoi(i)) using namespace std; void usage() { cout << "fatcat v1.0.6, Gregwar <g.passault@gmail.com>" << endl; cout << endl; cout << "Usage: fatcat disk.img [options]" << endl; cout << " -i: display information about disk" << endl; cout << " -O [offset]: global offset (may be partition place)" << endl; cout << " -F [format]: output format (default, json)" << endl; cout << endl; cout << "Browsing & extracting:" << endl; cout << " -l [dir]: list files and directories in the given path" << endl; cout << " -L [cluster]: list files and directories in the given cluster" << endl; cout << " -r [path]: reads the file given by the path" << endl; cout << " -R [cluster]: reads the data from given cluster" << endl; cout << " -s [size]: specify the size of data to read from the cluster" << endl; cout << " -d: enable listing of deleted files" << endl; cout << " -x [directory]: extract all files to a directory, deleted files included if -d" << endl; cout << " will start with rootDirectory, unless -c is provided" << endl; cout << "* -S: write scamble data in unallocated sectors" << endl; cout << "* -z: write scamble data in unallocated sectors" << endl; cout << endl; cout << "FAT Hacking" << endl; cout << " -@ [cluster]: Get the cluster address and information" << endl; cout << " -2: analysis & compare the 2 FATs" << endl; cout << " -b [file]: backup the FATs (see -t)" << endl; cout << "* -p [file]: restore (patch) the FATs (see -t)" << endl; cout << "* -w [cluster] -v [value]: write next cluster (see -t)" << endl; cout << " -t [table]: specify which table to write (0:both, 1:first, 2:second)" << endl; cout << "* -m: merge the FATs" << endl; cout << " -o: search for orphan files and directories" << endl; cout << "* -f: try to fix reachable directories" << endl; cout << endl; cout << "Entries hacking" << endl; cout << " -e [path]: sets the entry to hack, combined with:" << endl; cout << "* -c [cluster]: sets the entry cluster" << endl; cout << "* -s [size]: sets the entry size" << endl; cout << "* -a [attributes]: sets the entry attributes" << endl; cout << " -k [cluster]: try to find an entry that point to that cluster" << endl; cout << endl; cout << "*: These flags writes on the disk, and may damage it, be careful" << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { vector<string> arguments; char *image = NULL; int index; // -O offset unsigned long long globalOffset = 0; // -s, specify the size to be read unsigned int size = -1; // -i, display information about the disk bool infoFlag = false; // -l, list directories in the given path bool listFlag = false; string listPath; // -c, listing for a direct cluster bool listClusterFlag = false; unsigned int listCluster; // -r, reads a file bool readFlag = false; string readPath; // -R, reads from cluster file bool clusterRead = false; unsigned int cluster = 0; // -d, lists deleted bool listDeleted = false; // -x: extract bool extract = false; string extractDirectory; // -2: compare two fats bool compare = false; // -@: get the cluster address bool address = false; // -k: analysis the chains bool chains = false; // -b: backup the fats bool backup = false; bool patch = false; string backupFile; // -w: write next cluster bool writeNext = false; // -m: merge the FATs bool merge = false; // -v: value bool hasValue = false; unsigned int value; // -t: FAT table to write or read unsigned int table = 0; // -S: write random data in unallocated sectors bool scramble = false; bool zero = false; // -f: fix reachable bool fixReachable = false; // -e: entry hacking bool entry = false; string entryPath; bool clusterProvided = false; bool sizeProvided = false; int attributes = 0; bool attributesProvided = false; // -k: entry finder bool findEntry = false; OutputType output = Default; // Parsing command line while ((index = getopt(argc, argv, "il:L:r:R:s:dc:hx:2@:ob:p:w:v:mt:Sze:O:fk:a:F:")) != -1) { switch (index) { case 'a': attributesProvided = true; attributes = atoi(optarg); break; case 'k': findEntry = true; cluster = atoi(optarg); break; case 'f': fixReachable = true; break; case 'O': globalOffset = atoll(optarg); break; case 'e': entry = true; entryPath = string(optarg); break; case 'z': zero = true; break; case 'S': scramble = true; break; case 't': table = ATOU(optarg); break; case 'm': merge = true; break; case 'v': hasValue = true; value = ATOU(optarg); break; case 'w': writeNext = true; cluster = ATOU(optarg); break; case '@': address = true; cluster = ATOU(optarg); break; case 'o': chains = true; break; case 'i': infoFlag = true; break; case 'l': listFlag = true; listPath = string(optarg); break; case 'L': listClusterFlag = true; listCluster = ATOU(optarg); break; case 'r': readFlag = true; readPath = string(optarg); break; case 'R': clusterRead = true; cluster = ATOU(optarg); break; case 's': size = ATOU(optarg); sizeProvided = true; break; case 'd': listDeleted = true; break; case 'c': cluster = ATOU(optarg); clusterProvided = true; break; case 'x': extract = true; extractDirectory = string(optarg); break; case '2': compare = true; break; case 'b': backup = true; backupFile = string(optarg); break; case 'p': patch = true; backupFile = string(optarg); break; case 'h': usage(); break; case 'F': if (strcmp(optarg, "json") == 0) output = Json; else if (strcmp(optarg, "default") == 0) output = Default; else { usage(); } break; } } // Trying to get the FAT file or device if (optind != argc) { image = argv[optind]; } if (!image) { usage(); } // Getting extra arguments for (index=optind+1; index<argc; index++) { arguments.push_back(argv[index]); } // If the user did not required any actions if (!(infoFlag || listFlag || listClusterFlag || readFlag || clusterRead || extract || compare || address || chains || backup || patch || writeNext || merge || scramble || zero || entry || fixReachable || findEntry)) { usage(); } try { // Openning the image FatSystem fat(image, globalOffset, output); fat.setListDeleted(listDeleted); if (fat.init()) { if (infoFlag) { fat.infos(); } else if (listFlag) { cout << "Listing path " << listPath << endl; FatPath path(listPath); fat.list(path); } else if (listClusterFlag) { cout << "Listing cluster " << listCluster << endl; fat.list(listCluster); } else if (readFlag) { FatPath path(readPath); fat.readFile(path); } else if (clusterRead) { fat.readFile(cluster, size); } else if (extract) { FatExtract extract(fat); extract.extract(cluster, extractDirectory, listDeleted); } else if (compare) { FatDiff diff(fat); diff.compare(); } else if (address) { cout << "Cluster " << cluster << " address:" << endl; long long addr = fat.clusterAddress(cluster); printf("%llu (%016llx)\n", addr, addr); cout << "Next cluster:" << endl; int next1 = fat.nextCluster(cluster, 0); int next2 = fat.nextCluster(cluster, 1); printf("FAT1: %u (%08x)\n", next1, next1); printf("FAT2: %u (%08x)\n", next2, next2); bool isContiguous = false; FatChains chains(fat); unsigned long long size = chains.chainSize(cluster, &isContiguous); printf("Chain size: %llu (%llu / %s)\n", size, size*fat.bytesPerCluster, prettySize(size*fat.bytesPerCluster).c_str()); if (isContiguous) { printf("Chain is contiguous\n"); } else { printf("Chain is not contiguous\n"); } } else if (chains) { FatChains chains(fat); chains.chainsAnalysis(); } else if (fixReachable) { FatFix fix(fat); fix.fix(); } else if (findEntry) { FatSearch search(fat); search.search(cluster); } else if (backup || patch) { FatBackup backupSystem(fat); if (backup) { backupSystem.backup(backupFile, table); } else { backupSystem.patch(backupFile, table); } } else if (writeNext) { if (!hasValue) { throw string("You should provide a value with -v"); } int prev = fat.nextCluster(cluster); printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value); fat.enableWrite(); if (table == 0 || table == 1) { printf("Writing on FAT1\n"); fat.writeNextCluster(cluster, value, 0); } if (table == 0 || table == 2) { printf("Writing on FAT2\n"); fat.writeNextCluster(cluster, value, 1); } } else if (merge) { FatDiff diff(fat); diff.merge(); } else if (scramble) { fat.enableWrite(); fat.rewriteUnallocated(1); } else if (zero) { fat.enableWrite(); fat.rewriteUnallocated(); } else if (entry) { cout << "Searching entry for " << entryPath << endl; FatPath path(entryPath); FatEntry entry; if (fat.findFile(path, entry)) { printf("Entry address %016llx\n", entry.address); printf("Attributes %02X\n", entry.attributes); cout << "Found entry, cluster=" << entry.cluster; if (entry.isDirectory()) { cout << ", directory"; } else { cout << ", file with size=" << entry.size << " (" << prettySize(entry.size) << ")"; } cout << endl; if (clusterProvided) { cout << "Setting the cluster to " << cluster << endl; entry.cluster = cluster; } if (sizeProvided) { cout << "Setting the size to " << size << endl; entry.size = size&0xffffffff; } if (attributesProvided) { cout << "Setting attributes to " << attributes << endl; entry.attributes = attributes; } if (clusterProvided || sizeProvided || attributesProvided) { entry.updateData(); fat.enableWrite(); string data = entry.data; fat.writeData(entry.address, data.c_str(), entry.data.size()); } } else { cout << "Entry not found." << endl; } } } else { cout << "! Failed to init the FAT filesystem" << endl; } } catch (string error) { cerr << "Error: " << error << endl; } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include "chunk.h" #include <stdexcept> #include <fstream> #include <sstream> #include <curl/curl.h> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "dxjson/dxjson.h" #include "dxcpp/dxcpp.h" extern "C" { #include "compress.h" } #include "log.h" using namespace std; void Chunk::read() { const int64_t len = end - start; data.clear(); data.resize(len); ifstream in(localFile.c_str(), ifstream::in | ifstream::binary); in.seekg(start); in.read(&(data[0]), len); if (in) { } else { ostringstream msg; msg << "readData failed on chunk " << (*this); throw runtime_error(msg.str()); } } void Chunk::compress() { int64_t sourceLen = data.size(); int64_t destLen = gzCompressBound(sourceLen); vector<char> dest(destLen); int compressStatus = gzCompress((Bytef *) (&(dest[0])), (uLongf *) &destLen, (const Bytef *) (&(data[0])), (uLong) sourceLen, 3); // 3 is the compression level -- fast, not good if (compressStatus == Z_MEM_ERROR) { throw runtime_error("compression failed: not enough memory"); } else if (compressStatus == Z_BUF_ERROR) { throw runtime_error("compression failed: output buffer too small"); } else if (compressStatus != Z_OK) { throw runtime_error("compression failed: " + boost::lexical_cast<string>(compressStatus)); } if (destLen < (int64_t) dest.size()) { dest.resize(destLen); } data.swap(dest); } void checkConfigCURLcode(CURLcode code) { if (code != 0) { ostringstream msg; msg << "An error occurred while configuring the HTTP request (" << curl_easy_strerror(code) << ")" << endl; throw runtime_error(msg.str()); } } void checkPerformCURLcode(CURLcode code) { if (code != 0) { ostringstream msg; msg << "An error occurred while performing the HTTP request (" << curl_easy_strerror(code) << ")" << endl; throw runtime_error(msg.str()); } } /* * This function is the callback invoked by libcurl when it needs more data * to send to the server (CURLOPT_READFUNCTION). userdata is a pointer to * the chunk; we copy at most size * nmemb bytes of its data into ptr and * return the amount of data copied. */ size_t curlReadFunction(void * ptr, size_t size, size_t nmemb, void * userdata) { Chunk * chunk = (Chunk *) userdata; int64_t bytesLeft = chunk->data.size() - chunk->uploadOffset; size_t bytesToCopy = min<size_t>(bytesLeft, size * nmemb); if (bytesToCopy > 0) { memcpy(ptr, &((chunk->data)[chunk->uploadOffset]), bytesToCopy); chunk->uploadOffset += bytesToCopy; } return bytesToCopy; } void Chunk::upload() { string url = uploadURL(); LOG << "Upload URL: " << url << endl; CURL * curl = curl_easy_init(); if (curl == NULL) { throw runtime_error("An error occurred when initializing the HTTP connection"); } checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_POST, 1)); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_URL, url.c_str())); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_READFUNCTION, curlReadFunction)); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_READDATA, this)); /* * Set the Content-Type header. Default to something generic for now, and * do something sophisticated (i.e., detect it) later. */ struct curl_slist * slist = NULL; slist = curl_slist_append(slist, "Content-Type: application/octet-stream"); /* * Set the Content-Length header. */ { ostringstream clen; clen << "Content-Length: " << data.size(); slist = curl_slist_append(slist, clen.str().c_str()); } checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist)); log("Starting curl_easy_perform..."); checkPerformCURLcode(curl_easy_perform(curl)); long responseCode; checkPerformCURLcode(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode)); log("Returned from curl_easy_perform; responseCode is " + boost::lexical_cast<string>(responseCode)); if ((responseCode < 200) && (responseCode >= 300)) { ostringstream msg; msg << "Request failed with HTTP status code " << responseCode; throw runtime_error(msg.str()); } curl_slist_free_all(slist); curl_easy_cleanup(curl); } void Chunk::clear() { // A trick for forcing a vector's contents to be deallocated: swap the // memory from data into v; v will be destroyed when this function exits. vector<char> v; data.swap(v); } string Chunk::uploadURL() const { dx::JSON params(dx::JSON_OBJECT); params["index"] = index + 1; // minimum part index is 1 dx::JSON result = fileUpload(fileID, params); return result["url"].get<string>(); } /* * Logs a message about this chunk. */ void Chunk::log(const string &message) const { LOG << "Thread " << boost::this_thread::get_id() << ": " << "Chunk " << (*this) << ": " << message << endl; } ostream &operator<<(ostream &out, const Chunk &chunk) { out << "[" << chunk.localFile << ":" << chunk.start << "-" << chunk.end << " -> " << chunk.fileID << "[" << chunk.index << "]" << ", tries=" << chunk.triesLeft << ", data.size=" << chunk.data.size() << "]"; return out; } <commit_msg>Fixes to error handling / chunk retry logic.<commit_after>#include "chunk.h" #include <stdexcept> #include <fstream> #include <sstream> #include <curl/curl.h> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "dxjson/dxjson.h" #include "dxcpp/dxcpp.h" extern "C" { #include "compress.h" } #include "log.h" using namespace std; void Chunk::read() { const int64_t len = end - start; data.clear(); data.resize(len); ifstream in(localFile.c_str(), ifstream::in | ifstream::binary); in.seekg(start); in.read(&(data[0]), len); if (in) { } else { ostringstream msg; msg << "readData failed on chunk " << (*this); throw runtime_error(msg.str()); } } void Chunk::compress() { int64_t sourceLen = data.size(); int64_t destLen = gzCompressBound(sourceLen); vector<char> dest(destLen); int compressStatus = gzCompress((Bytef *) (&(dest[0])), (uLongf *) &destLen, (const Bytef *) (&(data[0])), (uLong) sourceLen, 3); // 3 is the compression level -- fast, not good if (compressStatus == Z_MEM_ERROR) { throw runtime_error("compression failed: not enough memory"); } else if (compressStatus == Z_BUF_ERROR) { throw runtime_error("compression failed: output buffer too small"); } else if (compressStatus != Z_OK) { throw runtime_error("compression failed: " + boost::lexical_cast<string>(compressStatus)); } if (destLen < (int64_t) dest.size()) { dest.resize(destLen); } data.swap(dest); } void checkConfigCURLcode(CURLcode code) { if (code != 0) { ostringstream msg; msg << "An error occurred while configuring the HTTP request (" << curl_easy_strerror(code) << ")" << endl; throw runtime_error(msg.str()); } } void checkPerformCURLcode(CURLcode code) { if (code != 0) { ostringstream msg; msg << "An error occurred while performing the HTTP request (" << curl_easy_strerror(code) << ")" << endl; throw runtime_error(msg.str()); } } /* * This function is the callback invoked by libcurl when it needs more data * to send to the server (CURLOPT_READFUNCTION). userdata is a pointer to * the chunk; we copy at most size * nmemb bytes of its data into ptr and * return the amount of data copied. */ size_t curlReadFunction(void * ptr, size_t size, size_t nmemb, void * userdata) { Chunk * chunk = (Chunk *) userdata; int64_t bytesLeft = chunk->data.size() - chunk->uploadOffset; size_t bytesToCopy = min<size_t>(bytesLeft, size * nmemb); if (bytesToCopy > 0) { memcpy(ptr, &((chunk->data)[chunk->uploadOffset]), bytesToCopy); chunk->uploadOffset += bytesToCopy; } return bytesToCopy; } void Chunk::upload() { string url = uploadURL(); log("Upload URL: " + url); uploadOffset = 0; CURL * curl = curl_easy_init(); if (curl == NULL) { throw runtime_error("An error occurred when initializing the HTTP connection"); } checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_POST, 1)); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_URL, url.c_str())); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_READFUNCTION, curlReadFunction)); checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_READDATA, this)); /* * Set the Content-Type header. Default to something generic for now, and * do something sophisticated (i.e., detect it) later. */ struct curl_slist * slist = NULL; slist = curl_slist_append(slist, "Content-Type: application/octet-stream"); /* * Set the Content-Length header. */ { ostringstream clen; clen << "Content-Length: " << data.size(); slist = curl_slist_append(slist, clen.str().c_str()); } checkConfigCURLcode(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist)); log("Starting curl_easy_perform..."); checkPerformCURLcode(curl_easy_perform(curl)); long responseCode; checkPerformCURLcode(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode)); log("Returned from curl_easy_perform; responseCode is " + boost::lexical_cast<string>(responseCode)); log("Performing curl cleanup"); curl_slist_free_all(slist); curl_easy_cleanup(curl); if ((responseCode < 200) || (responseCode >= 300)) { log("Throwing runtime_error"); ostringstream msg; msg << "Request failed with HTTP status code " << responseCode; throw runtime_error(msg.str()); } } void Chunk::clear() { // A trick for forcing a vector's contents to be deallocated: swap the // memory from data into v; v will be destroyed when this function exits. vector<char> v; data.swap(v); } string Chunk::uploadURL() const { dx::JSON params(dx::JSON_OBJECT); params["index"] = index + 1; // minimum part index is 1 dx::JSON result = fileUpload(fileID, params); return result["url"].get<string>(); } /* * Logs a message about this chunk. */ void Chunk::log(const string &message) const { LOG << "Thread " << boost::this_thread::get_id() << ": " << "Chunk " << (*this) << ": " << message << endl; } ostream &operator<<(ostream &out, const Chunk &chunk) { out << "[" << chunk.localFile << ":" << chunk.start << "-" << chunk.end << " -> " << chunk.fileID << "[" << chunk.index << "]" << ", tries=" << chunk.triesLeft << ", data.size=" << chunk.data.size() << "]"; return out; } <|endoftext|>
<commit_before>/** * @file status.cc * @author Krzysztof Trzepla * @copyright (C) 2015 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "messages/status.h" #include "messages.pb.h" #include <boost/bimap.hpp> #include <boost/optional/optional_io.hpp> #include <cassert> #include <sstream> #include <system_error> #include <vector> namespace { using Translation = boost::bimap<one::clproto::Status::Code, std::errc>; Translation createTranslation() { using namespace one::clproto; const std::vector<Translation::value_type> pairs{ {Status_Code_ok, static_cast<std::errc>(0)}, {Status_Code_eafnosupport, std::errc::address_family_not_supported}, {Status_Code_eaddrinuse, std::errc::address_in_use}, {Status_Code_eaddrnotavail, std::errc::address_not_available}, {Status_Code_eisconn, std::errc::already_connected}, {Status_Code_e2big, std::errc::argument_list_too_long}, {Status_Code_edom, std::errc::argument_out_of_domain}, {Status_Code_efault, std::errc::bad_address}, {Status_Code_ebadf, std::errc::bad_file_descriptor}, {Status_Code_ebadmsg, std::errc::bad_message}, {Status_Code_epipe, std::errc::broken_pipe}, {Status_Code_econnaborted, std::errc::connection_aborted}, {Status_Code_ealready, std::errc::connection_already_in_progress}, {Status_Code_econnrefused, std::errc::connection_refused}, {Status_Code_econnreset, std::errc::connection_reset}, {Status_Code_exdev, std::errc::cross_device_link}, {Status_Code_edestaddrreq, std::errc::destination_address_required}, {Status_Code_ebusy, std::errc::device_or_resource_busy}, {Status_Code_enotempty, std::errc::directory_not_empty}, {Status_Code_enoexec, std::errc::executable_format_error}, {Status_Code_eexist, std::errc::file_exists}, {Status_Code_efbig, std::errc::file_too_large}, {Status_Code_enametoolong, std::errc::filename_too_long}, {Status_Code_enosys, std::errc::function_not_supported}, {Status_Code_ehostunreach, std::errc::host_unreachable}, {Status_Code_eidrm, std::errc::identifier_removed}, {Status_Code_eilseq, std::errc::illegal_byte_sequence}, {Status_Code_enotty, std::errc::inappropriate_io_control_operation}, {Status_Code_eintr, std::errc::interrupted}, {Status_Code_einval, std::errc::invalid_argument}, {Status_Code_espipe, std::errc::invalid_seek}, {Status_Code_eio, std::errc::io_error}, {Status_Code_eisdir, std::errc::is_a_directory}, {Status_Code_emsgsize, std::errc::message_size}, {Status_Code_enetdown, std::errc::network_down}, {Status_Code_enetreset, std::errc::network_reset}, {Status_Code_enetunreach, std::errc::network_unreachable}, {Status_Code_enobufs, std::errc::no_buffer_space}, {Status_Code_echild, std::errc::no_child_process}, {Status_Code_enolink, std::errc::no_link}, {Status_Code_enolck, std::errc::no_lock_available}, {Status_Code_enodata, std::errc::no_message_available}, {Status_Code_enomsg, std::errc::no_message}, {Status_Code_enoprotoopt, std::errc::no_protocol_option}, {Status_Code_enospc, std::errc::no_space_on_device}, {Status_Code_enosr, std::errc::no_stream_resources}, {Status_Code_enxio, std::errc::no_such_device_or_address}, {Status_Code_enodev, std::errc::no_such_device}, {Status_Code_enoent, std::errc::no_such_file_or_directory}, {Status_Code_esrch, std::errc::no_such_process}, {Status_Code_enotdir, std::errc::not_a_directory}, {Status_Code_enotsock, std::errc::not_a_socket}, {Status_Code_enostr, std::errc::not_a_stream}, {Status_Code_enotconn, std::errc::not_connected}, {Status_Code_enomem, std::errc::not_enough_memory}, {Status_Code_enotsup, std::errc::not_supported}, {Status_Code_ecanceled, std::errc::operation_canceled}, {Status_Code_einprogress, std::errc::operation_in_progress}, {Status_Code_eperm, std::errc::operation_not_permitted}, {Status_Code_eopnotsupp, std::errc::operation_not_supported}, {Status_Code_ewouldblock, std::errc::operation_would_block}, {Status_Code_eownerdead, std::errc::owner_dead}, {Status_Code_eacces, std::errc::permission_denied}, {Status_Code_eproto, std::errc::protocol_error}, {Status_Code_eprotonosupport, std::errc::protocol_not_supported}, {Status_Code_erofs, std::errc::read_only_file_system}, {Status_Code_edeadlk, std::errc::resource_deadlock_would_occur}, {Status_Code_eagain, std::errc::resource_unavailable_try_again}, {Status_Code_erange, std::errc::result_out_of_range}, {Status_Code_enotrecoverable, std::errc::state_not_recoverable}, {Status_Code_etime, std::errc::stream_timeout}, {Status_Code_etxtbsy, std::errc::text_file_busy}, {Status_Code_etimedout, std::errc::timed_out}, {Status_Code_enfile, std::errc::too_many_files_open_in_system}, {Status_Code_emfile, std::errc::too_many_files_open}, {Status_Code_emlink, std::errc::too_many_links}, {Status_Code_eloop, std::errc::too_many_symbolic_link_levels}, {Status_Code_eoverflow, std::errc::value_too_large}, {Status_Code_eprototype, std::errc::wrong_protocol_type}}; return {pairs.begin(), pairs.end()}; } const Translation translation = createTranslation(); } namespace one { namespace messages { Status::Status(std::error_code ec) : m_code{ec} { } Status::Status(std::error_code ec, std::string desc) : m_code{ec} , m_description{std::move(desc)} { } Status::Status(std::unique_ptr<ProtocolServerMessage> serverMessage) : Status{*serverMessage->mutable_status()} { } Status::Status(clproto::Status &status) { auto searchResult = translation.left.find(status.code()); auto errc = searchResult == translation.left.end() ? std::errc::protocol_error : searchResult->second; m_code = std::make_error_code(errc); if (status.has_description()) m_description = std::move(*status.mutable_description()); } std::error_code Status::code() const { return m_code; } void Status::throwOnError() const { if (!m_code) return; if (m_description) throw std::system_error{m_code, m_description.get()}; throw std::system_error{m_code}; } const boost::optional<std::string> &Status::description() const { return m_description; } std::string Status::toString() const { std::stringstream stream; stream << "type: 'Status', code: " << m_code << ", description: " << m_description; return stream.str(); } std::unique_ptr<ProtocolClientMessage> Status::serializeAndDestroy() { auto clientMsg = std::make_unique<ProtocolClientMessage>(); auto statusMsg = clientMsg->mutable_status(); auto searchResult = translation.right.find(static_cast<std::errc>(m_code.value())); assert(searchResult != translation.right.end()); statusMsg->set_code(searchResult->second); if (m_description) statusMsg->mutable_description()->swap(m_description.get()); return clientMsg; } } // namespace messages } // namespace one <commit_msg>VFS-2058 Add special handling for non-default error messages<commit_after>/** * @file status.cc * @author Krzysztof Trzepla * @copyright (C) 2015 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "messages/status.h" #include "messages.pb.h" #include <boost/bimap.hpp> #include <boost/bimap/multiset_of.hpp> #include <boost/optional/optional_io.hpp> #include <cassert> #include <logging.h> #include <sstream> #include <system_error> #include <vector> namespace { using Translation = boost::bimap<one::clproto::Status::Code, boost::bimaps::multiset_of<std::errc>>; Translation createTranslation() { using namespace one::clproto; const std::vector<Translation::value_type> pairs{ {Status_Code_ok, static_cast<std::errc>(0)}, {Status_Code_eafnosupport, std::errc::address_family_not_supported}, {Status_Code_eaddrinuse, std::errc::address_in_use}, {Status_Code_eaddrnotavail, std::errc::address_not_available}, {Status_Code_eisconn, std::errc::already_connected}, {Status_Code_e2big, std::errc::argument_list_too_long}, {Status_Code_edom, std::errc::argument_out_of_domain}, {Status_Code_efault, std::errc::bad_address}, {Status_Code_ebadf, std::errc::bad_file_descriptor}, {Status_Code_ebadmsg, std::errc::bad_message}, {Status_Code_epipe, std::errc::broken_pipe}, {Status_Code_econnaborted, std::errc::connection_aborted}, {Status_Code_ealready, std::errc::connection_already_in_progress}, {Status_Code_econnrefused, std::errc::connection_refused}, {Status_Code_econnreset, std::errc::connection_reset}, {Status_Code_exdev, std::errc::cross_device_link}, {Status_Code_edestaddrreq, std::errc::destination_address_required}, {Status_Code_ebusy, std::errc::device_or_resource_busy}, {Status_Code_enotempty, std::errc::directory_not_empty}, {Status_Code_enoexec, std::errc::executable_format_error}, {Status_Code_eexist, std::errc::file_exists}, {Status_Code_efbig, std::errc::file_too_large}, {Status_Code_enametoolong, std::errc::filename_too_long}, {Status_Code_enosys, std::errc::function_not_supported}, {Status_Code_ehostunreach, std::errc::host_unreachable}, {Status_Code_eidrm, std::errc::identifier_removed}, {Status_Code_eilseq, std::errc::illegal_byte_sequence}, {Status_Code_enotty, std::errc::inappropriate_io_control_operation}, {Status_Code_eintr, std::errc::interrupted}, {Status_Code_einval, std::errc::invalid_argument}, {Status_Code_espipe, std::errc::invalid_seek}, {Status_Code_eio, std::errc::io_error}, {Status_Code_eisdir, std::errc::is_a_directory}, {Status_Code_emsgsize, std::errc::message_size}, {Status_Code_enetdown, std::errc::network_down}, {Status_Code_enetreset, std::errc::network_reset}, {Status_Code_enetunreach, std::errc::network_unreachable}, {Status_Code_enobufs, std::errc::no_buffer_space}, {Status_Code_echild, std::errc::no_child_process}, {Status_Code_enolink, std::errc::no_link}, {Status_Code_enolck, std::errc::no_lock_available}, {Status_Code_enodata, std::errc::no_message_available}, {Status_Code_enomsg, std::errc::no_message}, {Status_Code_enoprotoopt, std::errc::no_protocol_option}, {Status_Code_enospc, std::errc::no_space_on_device}, {Status_Code_enosr, std::errc::no_stream_resources}, {Status_Code_enxio, std::errc::no_such_device_or_address}, {Status_Code_enodev, std::errc::no_such_device}, {Status_Code_enoent, std::errc::no_such_file_or_directory}, {Status_Code_esrch, std::errc::no_such_process}, {Status_Code_enotdir, std::errc::not_a_directory}, {Status_Code_enotsock, std::errc::not_a_socket}, {Status_Code_enostr, std::errc::not_a_stream}, {Status_Code_enotconn, std::errc::not_connected}, {Status_Code_enomem, std::errc::not_enough_memory}, {Status_Code_enotsup, std::errc::not_supported}, {Status_Code_ecanceled, std::errc::operation_canceled}, {Status_Code_einprogress, std::errc::operation_in_progress}, {Status_Code_eperm, std::errc::operation_not_permitted}, {Status_Code_eopnotsupp, std::errc::operation_not_supported}, {Status_Code_ewouldblock, std::errc::operation_would_block}, {Status_Code_eownerdead, std::errc::owner_dead}, {Status_Code_eacces, std::errc::permission_denied}, {Status_Code_eproto, std::errc::protocol_error}, {Status_Code_eprotonosupport, std::errc::protocol_not_supported}, {Status_Code_erofs, std::errc::read_only_file_system}, {Status_Code_edeadlk, std::errc::resource_deadlock_would_occur}, {Status_Code_eagain, std::errc::resource_unavailable_try_again}, {Status_Code_erange, std::errc::result_out_of_range}, {Status_Code_enotrecoverable, std::errc::state_not_recoverable}, {Status_Code_etime, std::errc::stream_timeout}, {Status_Code_etxtbsy, std::errc::text_file_busy}, {Status_Code_etimedout, std::errc::timed_out}, {Status_Code_enfile, std::errc::too_many_files_open_in_system}, {Status_Code_emfile, std::errc::too_many_files_open}, {Status_Code_emlink, std::errc::too_many_links}, {Status_Code_eloop, std::errc::too_many_symbolic_link_levels}, {Status_Code_eoverflow, std::errc::value_too_large}, {Status_Code_eprototype, std::errc::wrong_protocol_type}}; return {pairs.begin(), pairs.end()}; } const Translation translation = createTranslation(); } namespace one { namespace messages { Status::Status(std::error_code ec) : m_code{ec} { } Status::Status(std::error_code ec, std::string desc) : m_code{ec} , m_description{std::move(desc)} { } Status::Status(std::unique_ptr<ProtocolServerMessage> serverMessage) : Status{*serverMessage->mutable_status()} { } Status::Status(clproto::Status &status) { auto searchResult = translation.left.find(status.code()); std::errc errc = std::errc::protocol_error; if (searchResult == translation.left.end()) { LOG(ERROR) << "Unknown error code received: " << status.code(); } else { errc = searchResult->second; } m_code = std::make_error_code(errc); if (status.has_description()) { m_description = std::move(*status.mutable_description()); LOG(INFO) << "Received status with description: " << m_code.message() << ": " << m_description.get(); } } std::error_code Status::code() const { return m_code; } void Status::throwOnError() const { if (!m_code) return; if (m_description) throw std::system_error{m_code, m_description.get()}; throw std::system_error{m_code}; } const boost::optional<std::string> &Status::description() const { return m_description; } std::string Status::toString() const { std::stringstream stream; stream << "type: 'Status', code: " << m_code << ", description: " << m_description; return stream.str(); } std::unique_ptr<ProtocolClientMessage> Status::serializeAndDestroy() { auto clientMsg = std::make_unique<ProtocolClientMessage>(); auto statusMsg = clientMsg->mutable_status(); auto searchResult = translation.right.find(static_cast<std::errc>(m_code.value())); assert(searchResult != translation.right.end()); statusMsg->set_code(searchResult->second); if (m_description) statusMsg->mutable_description()->swap(m_description.get()); return clientMsg; } } // namespace messages } // namespace one <|endoftext|>
<commit_before>#include "Mask.h" #include "Image.h" #include "Utility.h" #include "Features.h" #include "pRandomForest.h" #include "dlib/cmd_line_parser.h" #include "dlib/image_io.h" #include <vector> #include <string> #include <iostream> using namespace std; struct Options { int fft_width = 512; int fft_step = 256; int hi_pass_hz = 300; double theta = 1; string input_path; string model_path; string output_path; string label_path; string out_label_path; bool good() { return (model_path.size() || label_path.size()) && input_path.size() && output_path.size() && fft_width > 0 && fft_step > 0 && hi_pass_hz >= 0; } }; Options learn_parse_args(int argc, char *argv[]) { dlib::cmd_line_parser<char>::check_1a_c parser; parser.add_option("h", "Display this help message"); parser.add_option("i", "An input .wav audio file", 1); parser.add_option("o", "Output noise-reduced .wav audio file",1); parser.add_option("w", "Integer FFT width (2x the output spectrogram image height). Default 512", 1); parser.add_option("s", "FFT Step (smaller step sizes result in a wider image). Default 256", 1); parser.add_option("p", "High-Pass cutoff in Hz. Default 300", 1); parser.add_option("m", "Model file, generated by 'learn'", 1); parser.add_option("a", "If using -m, output filename for BMP of the label (this label can then be re-used with -l)", 1); parser.add_option("l", "Label file, can be used as a replacement for -m. Must be a monochrome BMP the same shape as the spectrogram. White areas will be included in the output, and black deleted.", 1); parser.add_option("t", "Theta: Lower means less noise reduction, higher eliminates more sound. Default 1", 1); parser.parse(argc, argv); Options opts; if (parser.number_of_arguments() > 0) opts.input_path = parser[0]; if (parser.number_of_arguments() > 1) opts.output_path = parser[1]; if (parser.option("i") && parser.option("i").count() > 0) opts.input_path = parser.option("i").argument(); if (parser.option("o") && parser.option("o").count() > 0) opts.output_path = parser.option("o").argument(); if (parser.option("m") && parser.option("m").count() > 0) opts.model_path = parser.option("m").argument(); if (parser.option("l") && parser.option("l").count() > 0) opts.label_path = parser.option("l").argument(); if (parser.option("a") && parser.option("a").count() > 0) opts.out_label_path = parser.option("a").argument(); if (parser.option("w") && parser.option("w").count() > 0) opts.fft_width = dlib::sa = parser.option("w").argument(); if (parser.option("s") && parser.option("s").count() > 0) opts.fft_step = dlib::sa = parser.option("s").argument(); if (parser.option("p") && parser.option("p").count() > 0) opts.hi_pass_hz = dlib::sa = parser.option("p").argument(); if (parser.option("t") && parser.option("t").count() > 0) opts.theta = dlib::sa = parser.option("t").argument(); if (!opts.good()) { cout << "\tfilter -m model.rf noisy.wav filtered.wav" << endl; parser.print_options(); exit(1); } return opts; } int main(int argc, char *argv[]) { Options opt = learn_parse_args(argc, argv); cout << "Generating spectrogram" << endl; Mask spec(opt.input_path, opt.fft_width, opt.fft_step); cout << "Processing spectrogram" << endl; spec = preprocess_spec_icassp(spec, opt.hi_pass_hz); if (opt.label_path.size()) { Mask label(opt.label_path); cout << "Loaded label mask " << label.toString(); label.attenuate_wav(opt.input_path, opt.output_path); cout << "Finished applying label" << endl; } else { cout << "Loading Random Forest from " << opt.model_path << endl; pRandomForest rf; rf.load(opt.model_path); cout << "Applying RF scoring to spectrogram: " << spec.toString() << endl; Mask scores(spec.width(), spec.height(), [&](int x, int y) { vector<float> feature(extract_feature_perpixel_icassp(spec, x, y)); float score = rf.estimateClassProbabilities(feature)[0]; return score; }); scores = scores.gaussian_blur(4).norm_to_mean(1.0).raise_to(opt.theta); if (opt.out_label_path.size()) Image(scores).save(opt.out_label_path); cout << "Attenuate wav" << endl; scores.attenuate_wav(opt.input_path, opt.output_path); cout << "Finished attenuate wav" << endl; } return 0; } <commit_msg>Make output from -l and -m style filters match up<commit_after>#include "Mask.h" #include "Image.h" #include "Utility.h" #include "Features.h" #include "pRandomForest.h" #include "dlib/cmd_line_parser.h" #include "dlib/image_io.h" #include <vector> #include <string> #include <iostream> using namespace std; struct Options { int fft_width = 512; int fft_step = 256; int hi_pass_hz = 300; double theta = 1; string input_path; string model_path; string output_path; string label_path; string out_label_path; bool good() { return (model_path.size() || label_path.size()) && input_path.size() && output_path.size() && fft_width > 0 && fft_step > 0 && hi_pass_hz >= 0; } }; Options learn_parse_args(int argc, char *argv[]) { dlib::cmd_line_parser<char>::check_1a_c parser; parser.add_option("h", "Display this help message"); parser.add_option("i", "An input .wav audio file", 1); parser.add_option("o", "Output noise-reduced .wav audio file",1); parser.add_option("w", "Integer FFT width (2x the output spectrogram image height). Default 512", 1); parser.add_option("s", "FFT Step (smaller step sizes result in a wider image). Default 256", 1); parser.add_option("p", "High-Pass cutoff in Hz. Default 300", 1); parser.add_option("m", "Model file, generated by 'learn'", 1); parser.add_option("a", "If using -m, output filename for BMP of the label (this label can then be re-used with -l)", 1); parser.add_option("l", "Label file, can be used as a replacement for -m. Must be a monochrome BMP the same shape as the spectrogram. White areas will be included in the output, and black deleted.", 1); parser.add_option("t", "Theta: Lower means less noise reduction, higher eliminates more sound. Default 1", 1); parser.parse(argc, argv); Options opts; if (parser.number_of_arguments() > 0) opts.input_path = parser[0]; if (parser.number_of_arguments() > 1) opts.output_path = parser[1]; if (parser.option("i") && parser.option("i").count() > 0) opts.input_path = parser.option("i").argument(); if (parser.option("o") && parser.option("o").count() > 0) opts.output_path = parser.option("o").argument(); if (parser.option("m") && parser.option("m").count() > 0) opts.model_path = parser.option("m").argument(); if (parser.option("l") && parser.option("l").count() > 0) opts.label_path = parser.option("l").argument(); if (parser.option("a") && parser.option("a").count() > 0) opts.out_label_path = parser.option("a").argument(); if (parser.option("w") && parser.option("w").count() > 0) opts.fft_width = dlib::sa = parser.option("w").argument(); if (parser.option("s") && parser.option("s").count() > 0) opts.fft_step = dlib::sa = parser.option("s").argument(); if (parser.option("p") && parser.option("p").count() > 0) opts.hi_pass_hz = dlib::sa = parser.option("p").argument(); if (parser.option("t") && parser.option("t").count() > 0) opts.theta = dlib::sa = parser.option("t").argument(); if (!opts.good()) { cout << "\tfilter -m model.rf noisy.wav filtered.wav" << endl; parser.print_options(); exit(1); } return opts; } int main(int argc, char *argv[]) { Options opt = learn_parse_args(argc, argv); cout << "Generating spectrogram" << endl; Mask spec(opt.input_path, opt.fft_width, opt.fft_step); cout << "Processing spectrogram" << endl; spec = preprocess_spec_icassp(spec, opt.hi_pass_hz); if (opt.label_path.size()) { Mask label(opt.label_path); cout << "Loaded label mask " << label.toString(); if (opt.out_label_path.size()) Image(label).save(opt.out_label_path); label.attenuate_wav(opt.input_path, opt.output_path); cout << "Finished applying label" << endl; } else { cout << "Loading Random Forest from " << opt.model_path << endl; pRandomForest rf; rf.load(opt.model_path); cout << "Applying RF scoring to spectrogram: " << spec.toString() << endl; Mask scores(spec.width(), spec.height(), [&](int x, int y) { vector<float> feature(extract_feature_perpixel_icassp(spec, x, y)); float score = rf.estimateClassProbabilities(feature)[1]; return score; }); scores = scores.gaussian_blur(4).norm_to_mean(1.0).raise_to(opt.theta); if (opt.out_label_path.size()) Image(scores).save(opt.out_label_path); cout << "Attenuate wav" << endl; scores.attenuate_wav(opt.input_path, opt.output_path); cout << "Finished attenuate wav" << endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Zubax, zubax.com * Please refer to the file LICENSE for terms and conditions. * Author: Pavel Kirienko <pavel.kirienko@zubax.com> */ #pragma once #include <ros/ros.h> #include <ros/console.h> #include <eigen3/Eigen/Eigen> #include <cmath> #include "mathematica.hpp" #include "debug_publisher.hpp" #include "linear_algebra.hpp" #include "exception.hpp" #include "state_vector_autogenerated.hpp" namespace zubax_posekf { /** * Filter output - twist; compatible with geometry_msgs/TwistWithCovariance. * - Velocity of IMU in the world frame, transformed into the IMU frame * - Angular velocity of IMU in the IMU frame * - Covariance: x, y, z, rotation about X axis, rotation about Y axis, rotation about Z axis */ struct Twist { Vector3 linear; Vector3 angular; Matrix<6, 6> linear_angular_cov; Twist() { linear.setZero(); angular.setZero(); linear_angular_cov.setZero(); } }; /** * Filter output - pose; compatible with geometry_msgs/PoseWithCovariance. * - Position of IMU in the world frame * - Orientation of IMU in the world frame * - Covariance: x, y, z, rotation about X axis, rotation about Y axis, rotation about Z axis */ struct Pose { Vector3 position; Quaternion orientation; Matrix<6, 6> position_orientation_cov; Pose() { position.setZero(); orientation.setIdentity(); position_orientation_cov.setZero(); } }; /** * The business end. */ class Filter { DebugPublisher debug_pub_; StateVector state_; Matrix<StateVector::Size, StateVector::Size> P_; Matrix<StateVector::Size, StateVector::Size> Q_; const Scalar MaxGyroDrift = 0.1; const Scalar MaxAccelDrift = 2.0; const Scalar MaxCovariance = 1e9; const Scalar MinVariance = 1e-9; Scalar state_timestamp_ = 0.0; bool initialized_ = false; static Vector3 constrainDrift(Vector3 vec, const Scalar limit, const char* name) { for (int i = 0; i < 3; i++) { if (!checkRangeAndConstrainSymmetric(vec[i], limit)) { ROS_WARN_THROTTLE(1, "Drift is too high [%s]", name); } } return vec; } void normalizeAndCheck() { state_.normalize(); state_.bw(constrainDrift(state_.bw(), MaxGyroDrift, "gyro")); state_.ba(constrainDrift(state_.ba(), MaxAccelDrift, "accel")); // P validation if (!validateAndFixCovarianceMatrix(P_, MaxCovariance, MinVariance)) { ROS_ERROR_STREAM_THROTTLE(1, "Matrix P has been fixed\n" << P_.format(Eigen::IOFormat(2))); } debug_pub_.publish("x", state_.x); debug_pub_.publish("P", P_); debug_pub_.publish("Q", Q_); enforce("Non-finite states", std::isfinite(state_.x.sum()) && std::isfinite(P_.sum()) && std::isfinite(Q_.sum())); enforce("Invalid timestamp", std::isfinite(state_timestamp_) && (state_timestamp_ > 0.0)); } template <int NumDims> void performMeasurementUpdate(const Vector<NumDims>& y, const Matrix<NumDims, NumDims>& R, const Matrix<NumDims, StateVector::Size>& H, const char* const source_name) { ROS_ASSERT(initialized_); /* * Ensure that R is symmetric, then validate */ const Matrix<NumDims, NumDims> R_sym = 0.5 * (R + R.transpose()); { bool R_sym_ok = true; for (int i = 0; i < NumDims; i++) { if (R_sym(i, i) <= 0) { R_sym_ok = false; break; } } if (!R_sym_ok || !std::isfinite(R_sym.sum())) { std::ostringstream os; os << "Measurement R_sym [" << source_name << "]:\n" << R_sym; throw Exception(os.str()); } } /* * Compute S inverse with validation */ Matrix<NumDims, NumDims> S_inv; { const Matrix<NumDims, NumDims> S = H * P_ * H.transpose() + R_sym; bool s_is_invertible = false; S.computeInverseWithCheck(S_inv, s_is_invertible); if (!s_is_invertible) { std::ostringstream os; os << "S is not invertible (numerical failure?) [" << source_name << "]:\n" << S << "\nR_sym:\n" << R_sym; throw Exception(os.str()); } } /* * Kalman update equations * Joseph form is used instead of the simplified form to improve numerical stability */ const auto K = static_cast<Matrix<StateVector::Size, NumDims> >(P_ * H.transpose() * S_inv); state_.x = state_.x + K * y; const Matrix<StateVector::Size, StateVector::Size> IKH = decltype(P_)::Identity() - K * H; P_ = IKH * P_ * IKH.transpose() + K * R_sym * K.transpose(); normalizeAndCheck(); // std::cout << "P:\n" << P_.format(Eigen::IOFormat(2)) << "\n" << std::endl; // std::cout << "x:\n" << state_.x.transpose().format(Eigen::IOFormat(2)) << "\n" << std::endl; } public: Filter() { // Initial state - zero everything, null rotations state_.qwi(Quaternion(1, 0, 0, 0)); state_.qvw(Quaternion(1, 0, 0, 0)); // Initial P P_.setZero(); P_ = StateVector::Pinitdiag().asDiagonal(); // Initial Q // TODO: runtime Q estimation Q_ = StateVector::Qmindiag().asDiagonal(); } bool isInitialized() const { return initialized_; } void initialize(Scalar timestamp, const Quaternion& orientation) { ROS_ASSERT(!initialized_); initialized_ = true; state_timestamp_ = timestamp; state_.qwi(orientation); normalizeAndCheck(); ROS_INFO_STREAM("Initial P:\n" << P_.format(Eigen::IOFormat(2))); ROS_INFO_STREAM("Initial Q:\n" << Q_.format(Eigen::IOFormat(2))); ROS_INFO_STREAM("Initial x:\n" << state_.x.transpose().format(Eigen::IOFormat(2))); } void performTimeUpdate(Scalar timestamp) { ROS_ASSERT(initialized_); ROS_ASSERT(timestamp > 0); /* * Compute and check dt */ const Scalar dt = timestamp - state_timestamp_; debug_pub_.publish("dt", dt); if (dt <= 0) { ROS_ERROR("Time update: Nonpositive dt [%f]", dt); return; } state_timestamp_ = timestamp; /* * Update the state vector and process covariance matrix */ const auto F = state_.F(dt); state_.x = state_.f(dt); P_ = F * P_ * F.transpose() + Q_ * dt; normalizeAndCheck(); // TODO: Commit point - add new X to the state history } void performAccelUpdate(const Vector3& accel, const Matrix3& cov) { const Vector3 y = accel - state_.hacc(); performMeasurementUpdate(y, cov, state_.Hacc(), "acc"); } void performGyroUpdate(const Vector3& angvel, const Matrix3& cov) { const Vector3 y = angvel - state_.hgyro(); performMeasurementUpdate(y, cov, state_.Hgyro(), "gyro"); } void performGNSSPosUpdate(const Vector3& pos, const Matrix3& cov) { const Vector3 y = pos - state_.hgnsspos(); performMeasurementUpdate(y, cov, state_.Hgnsspos(), "gnsspos"); } void performGNSSVelUpdate(const Vector3& vel, const Matrix3& cov) { const Vector3 y = vel - state_.hgnssvel(); performMeasurementUpdate(y, cov, state_.Hgnssvel(), "gnssvel"); } void performVisPosUpdate(const Vector3& pos, const Matrix3& cov) { const Vector3 y = pos - state_.hvispos(); performMeasurementUpdate(y, cov, state_.Hvispos(), "vispos"); } void performVisAttUpdate(const Quaternion& z, const Matrix3& cov) { /* * Residual computation */ const Quaternion h = state_.hvisatt(); const Quaternion yq = z * h.inverse(); // Weiss 2012, eq. 3.45 ~ 3.46 Vector<4> y; y[0] = yq.w(); y[1] = yq.x(); y[2] = yq.y(); y[3] = yq.z(); /* * Covariance transformation */ const Matrix<4, 3> G = quaternionFromEulerJacobian(quaternionToEuler(z)); const auto R = static_cast<Matrix<4, 4> >(G * cov * G.transpose()); performMeasurementUpdate(y, R, state_.Hvisatt(), "visatt"); debug_pub_.publish("visatt_R", R); } Scalar getTimestamp() const { return state_timestamp_; } /** * Pose, compatible with geometry_msgs/PoseWithCovariance */ Pose getOutputPose() const { Pose out; out.position = state_.pwi(); out.orientation = state_.qwi(); const Matrix<3, 4> G = quaternionToEulerJacobian(out.orientation); const Matrix4 C = P_.block<4, 4>(StateVector::Idx::qwiw, StateVector::Idx::qwiw); out.position_orientation_cov.block<3, 3>(0, 0) = P_.block<3, 3>(StateVector::Idx::pwix, StateVector::Idx::pwix); out.position_orientation_cov.block<3, 3>(3, 3) = G * C * G.transpose(); return out; } /** * Twist, compatible with geometry_msgs/TwistWithCovariance */ Twist getOutputTwistInIMUFrame() const { Twist out; out.linear = rotateVectorByQuaternion(state_.vwi(), state_.qwi()); // World --> IMU out.angular = state_.w(); const Matrix3 G = rotateVectorByQuaternionJacobian(state_.qwi()); const Matrix3 C = P_.block<3, 3>(StateVector::Idx::vwix, StateVector::Idx::vwix); out.linear_angular_cov.block<3, 3>(0, 0) = G * C * G.transpose(); out.linear_angular_cov.block<3, 3>(3, 3) = P_.block<3, 3>(StateVector::Idx::wx, StateVector::Idx::wx); return out; } /** * Gravity compensated acceleration in IMU frame with covariance */ std::pair<Vector3, Matrix3> getOutputAcceleration() const { return { state_.a(), P_.block<3, 3>(StateVector::Idx::ax, StateVector::Idx::ax) }; } }; } <commit_msg>De-escalated error message<commit_after>/* * Copyright (c) 2014 Zubax, zubax.com * Please refer to the file LICENSE for terms and conditions. * Author: Pavel Kirienko <pavel.kirienko@zubax.com> */ #pragma once #include <ros/ros.h> #include <ros/console.h> #include <eigen3/Eigen/Eigen> #include <cmath> #include "mathematica.hpp" #include "debug_publisher.hpp" #include "linear_algebra.hpp" #include "exception.hpp" #include "state_vector_autogenerated.hpp" namespace zubax_posekf { /** * Filter output - twist; compatible with geometry_msgs/TwistWithCovariance. * - Velocity of IMU in the world frame, transformed into the IMU frame * - Angular velocity of IMU in the IMU frame * - Covariance: x, y, z, rotation about X axis, rotation about Y axis, rotation about Z axis */ struct Twist { Vector3 linear; Vector3 angular; Matrix<6, 6> linear_angular_cov; Twist() { linear.setZero(); angular.setZero(); linear_angular_cov.setZero(); } }; /** * Filter output - pose; compatible with geometry_msgs/PoseWithCovariance. * - Position of IMU in the world frame * - Orientation of IMU in the world frame * - Covariance: x, y, z, rotation about X axis, rotation about Y axis, rotation about Z axis */ struct Pose { Vector3 position; Quaternion orientation; Matrix<6, 6> position_orientation_cov; Pose() { position.setZero(); orientation.setIdentity(); position_orientation_cov.setZero(); } }; /** * The business end. */ class Filter { DebugPublisher debug_pub_; StateVector state_; Matrix<StateVector::Size, StateVector::Size> P_; Matrix<StateVector::Size, StateVector::Size> Q_; const Scalar MaxGyroDrift = 0.1; const Scalar MaxAccelDrift = 2.0; const Scalar MaxCovariance = 1e9; const Scalar MinVariance = 1e-9; Scalar state_timestamp_ = 0.0; bool initialized_ = false; static Vector3 constrainDrift(Vector3 vec, const Scalar limit, const char* name) { for (int i = 0; i < 3; i++) { if (!checkRangeAndConstrainSymmetric(vec[i], limit)) { ROS_WARN_THROTTLE(1, "Drift is too high [%s]", name); } } return vec; } void normalizeAndCheck() { state_.normalize(); state_.bw(constrainDrift(state_.bw(), MaxGyroDrift, "gyro")); state_.ba(constrainDrift(state_.ba(), MaxAccelDrift, "accel")); // P validation if (!validateAndFixCovarianceMatrix(P_, MaxCovariance, MinVariance)) { ROS_ERROR_STREAM_THROTTLE(1, "Matrix P has been fixed\n" << P_.format(Eigen::IOFormat(2))); } debug_pub_.publish("x", state_.x); debug_pub_.publish("P", P_); debug_pub_.publish("Q", Q_); enforce("Non-finite states", std::isfinite(state_.x.sum()) && std::isfinite(P_.sum()) && std::isfinite(Q_.sum())); enforce("Invalid timestamp", std::isfinite(state_timestamp_) && (state_timestamp_ > 0.0)); } template <int NumDims> void performMeasurementUpdate(const Vector<NumDims>& y, const Matrix<NumDims, NumDims>& R, const Matrix<NumDims, StateVector::Size>& H, const char* const source_name) { ROS_ASSERT(initialized_); /* * Ensure that R is symmetric, then validate */ const Matrix<NumDims, NumDims> R_sym = 0.5 * (R + R.transpose()); { bool R_sym_ok = true; for (int i = 0; i < NumDims; i++) { if (R_sym(i, i) <= 0) { R_sym_ok = false; break; } } if (!R_sym_ok || !std::isfinite(R_sym.sum())) { std::ostringstream os; os << "Measurement R_sym [" << source_name << "]:\n" << R_sym; throw Exception(os.str()); } } /* * Compute S inverse with validation */ Matrix<NumDims, NumDims> S_inv; { const Matrix<NumDims, NumDims> S = H * P_ * H.transpose() + R_sym; bool s_is_invertible = false; S.computeInverseWithCheck(S_inv, s_is_invertible); if (!s_is_invertible) { std::ostringstream os; os << "S is not invertible (numerical failure?) [" << source_name << "]:\n" << S << "\nR_sym:\n" << R_sym; throw Exception(os.str()); } } /* * Kalman update equations * Joseph form is used instead of the simplified form to improve numerical stability */ const auto K = static_cast<Matrix<StateVector::Size, NumDims> >(P_ * H.transpose() * S_inv); state_.x = state_.x + K * y; const Matrix<StateVector::Size, StateVector::Size> IKH = decltype(P_)::Identity() - K * H; P_ = IKH * P_ * IKH.transpose() + K * R_sym * K.transpose(); normalizeAndCheck(); // std::cout << "P:\n" << P_.format(Eigen::IOFormat(2)) << "\n" << std::endl; // std::cout << "x:\n" << state_.x.transpose().format(Eigen::IOFormat(2)) << "\n" << std::endl; } public: Filter() { // Initial state - zero everything, null rotations state_.qwi(Quaternion(1, 0, 0, 0)); state_.qvw(Quaternion(1, 0, 0, 0)); // Initial P P_.setZero(); P_ = StateVector::Pinitdiag().asDiagonal(); // Initial Q // TODO: runtime Q estimation Q_ = StateVector::Qmindiag().asDiagonal(); } bool isInitialized() const { return initialized_; } void initialize(Scalar timestamp, const Quaternion& orientation) { ROS_ASSERT(!initialized_); initialized_ = true; state_timestamp_ = timestamp; state_.qwi(orientation); normalizeAndCheck(); ROS_INFO_STREAM("Initial P:\n" << P_.format(Eigen::IOFormat(2))); ROS_INFO_STREAM("Initial Q:\n" << Q_.format(Eigen::IOFormat(2))); ROS_INFO_STREAM("Initial x:\n" << state_.x.transpose().format(Eigen::IOFormat(2))); } void performTimeUpdate(Scalar timestamp) { ROS_ASSERT(initialized_); ROS_ASSERT(timestamp > 0); /* * Compute and check dt */ const Scalar dt = timestamp - state_timestamp_; debug_pub_.publish("dt", dt); if (dt <= 0) { ROS_WARN_THROTTLE(1, "Time update: Nonpositive dt [%f]", dt); return; } state_timestamp_ = timestamp; /* * Update the state vector and process covariance matrix */ const auto F = state_.F(dt); state_.x = state_.f(dt); P_ = F * P_ * F.transpose() + Q_ * dt; normalizeAndCheck(); // TODO: Commit point - add new X to the state history } void performAccelUpdate(const Vector3& accel, const Matrix3& cov) { const Vector3 y = accel - state_.hacc(); performMeasurementUpdate(y, cov, state_.Hacc(), "acc"); } void performGyroUpdate(const Vector3& angvel, const Matrix3& cov) { const Vector3 y = angvel - state_.hgyro(); performMeasurementUpdate(y, cov, state_.Hgyro(), "gyro"); } void performGNSSPosUpdate(const Vector3& pos, const Matrix3& cov) { const Vector3 y = pos - state_.hgnsspos(); performMeasurementUpdate(y, cov, state_.Hgnsspos(), "gnsspos"); } void performGNSSVelUpdate(const Vector3& vel, const Matrix3& cov) { const Vector3 y = vel - state_.hgnssvel(); performMeasurementUpdate(y, cov, state_.Hgnssvel(), "gnssvel"); } void performVisPosUpdate(const Vector3& pos, const Matrix3& cov) { const Vector3 y = pos - state_.hvispos(); performMeasurementUpdate(y, cov, state_.Hvispos(), "vispos"); } void performVisAttUpdate(const Quaternion& z, const Matrix3& cov) { /* * Residual computation */ const Quaternion h = state_.hvisatt(); const Quaternion yq = z * h.inverse(); // Weiss 2012, eq. 3.45 ~ 3.46 Vector<4> y; y[0] = yq.w(); y[1] = yq.x(); y[2] = yq.y(); y[3] = yq.z(); /* * Covariance transformation */ const Matrix<4, 3> G = quaternionFromEulerJacobian(quaternionToEuler(z)); const auto R = static_cast<Matrix<4, 4> >(G * cov * G.transpose()); performMeasurementUpdate(y, R, state_.Hvisatt(), "visatt"); debug_pub_.publish("visatt_R", R); } Scalar getTimestamp() const { return state_timestamp_; } /** * Pose, compatible with geometry_msgs/PoseWithCovariance */ Pose getOutputPose() const { Pose out; out.position = state_.pwi(); out.orientation = state_.qwi(); const Matrix<3, 4> G = quaternionToEulerJacobian(out.orientation); const Matrix4 C = P_.block<4, 4>(StateVector::Idx::qwiw, StateVector::Idx::qwiw); out.position_orientation_cov.block<3, 3>(0, 0) = P_.block<3, 3>(StateVector::Idx::pwix, StateVector::Idx::pwix); out.position_orientation_cov.block<3, 3>(3, 3) = G * C * G.transpose(); return out; } /** * Twist, compatible with geometry_msgs/TwistWithCovariance */ Twist getOutputTwistInIMUFrame() const { Twist out; out.linear = rotateVectorByQuaternion(state_.vwi(), state_.qwi()); // World --> IMU out.angular = state_.w(); const Matrix3 G = rotateVectorByQuaternionJacobian(state_.qwi()); const Matrix3 C = P_.block<3, 3>(StateVector::Idx::vwix, StateVector::Idx::vwix); out.linear_angular_cov.block<3, 3>(0, 0) = G * C * G.transpose(); out.linear_angular_cov.block<3, 3>(3, 3) = P_.block<3, 3>(StateVector::Idx::wx, StateVector::Idx::wx); return out; } /** * Gravity compensated acceleration in IMU frame with covariance */ std::pair<Vector3, Matrix3> getOutputAcceleration() const { return { state_.a(), P_.block<3, 3>(StateVector::Idx::ax, StateVector::Idx::ax) }; } }; } <|endoftext|>
<commit_before>#include "Dragoon.h" #include "../Action.h" #include "../Actor.h" #include "../Aura.h" namespace models { Dragoon::Dragoon() : Base("dragoon") { { struct Skill : Action { struct Buff : Aura { Buff() : Aura("internal-release") {} virtual std::chrono::microseconds duration() const override { return 15_s; } virtual double additionalCriticalHitChance() const override { return 0.10; } }; Skill() : Action("internal-release") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("life-surge") {} virtual std::chrono::microseconds duration() const override { return 10_s; } virtual double additionalCriticalHitChance() const override { return 1.0; } }; Skill() : Action("life-surge") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("blood-for-blood") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual double increasedDamage() const override { return 0.30; } }; Skill() : Action("blood-for-blood") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 80_s; } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("invigorate") {} virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 120_s; } virtual int tpRestoration() const override { return 500; } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("fracture-dot") {} virtual std::chrono::microseconds duration() const override { return 18_s; } virtual int tickDamage() const override { return 20; } }; Skill() : Action("fracture") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 100; } virtual int tpCost() const override { return 80; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("true-thrust") {} virtual int damage() const override { return 150; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("vorpal-thrust-combo") {} virtual int damage() const override { return 200; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "true-thrust"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("full-thrust-combo") {} virtual int damage() const override { return 300; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "vorpal-thrust-combo"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("impulse-drive-rear") {} virtual int damage() const override { return 180; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct Debuff : Aura { Debuff() : Aura("disembowel-combo") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual void transformIncomingDamage(Damage* damage) const override { if (damage->type == DamageTypePiercing) { damage->amount *= 1.0 / 0.9; } } }; Skill() : Action("disembowel-combo") { _targetAuras.push_back(new Debuff()); } virtual int damage() const override { return 220; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "impulse-drive-rear"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("chaos-thrust-dot") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual int tickDamage() const override { return 30; } }; Skill() : Action("chaos-thrust-combo") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 200; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "disembowel-combo"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("heavy-thrust") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual double increasedDamage() const override { return 0.15; } }; Skill() : Action("heavy-thrust-flank") { _sourceAuras.push_back(new Buff()); } virtual int damage() const override { return 170; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("phlebotomize-dot") {} virtual std::chrono::microseconds duration() const override { return 18_s; } virtual int tickDamage() const override { return 25; } }; Skill() : Action("phlebotomize") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 170; } virtual int tpCost() const override { return 90; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("jump") {} virtual int damage(const Actor* source, const Actor* target) const override { return source->auraCount("power-surge", source) ? 300 : 200; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); source->dispelAura("power-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("power-surge") {} virtual std::chrono::microseconds duration() const override { return 10_s; } }; Skill() : Action("power-surge") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("dragonfire-dive") {} virtual int damage() const override { return 250; } virtual std::chrono::microseconds cooldown() const override { return 180_s; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } } int Dragoon::maximumMP(const Actor* actor) const { return 0; } DamageType Dragoon::_defaultDamageType() const { return DamageTypePiercing; } std::chrono::microseconds Dragoon::_baseGlobalCooldown(const Actor* actor) const { auto& stats = actor->stats(); auto gcd = std::chrono::duration<double>(2.5 - (stats.skillSpeed - 341) * (0.01 / 10.5)); return std::chrono::duration_cast<std::chrono::microseconds>(gcd); } // http://valk.dancing-mad.com/ double Dragoon::_basePotencyMultiplier(const Actor* actor) const { auto& stats = actor->stats(); return 0.01 * (stats.weaponPhysicalDamage * (stats.strength * 0.00389 + stats.determination * 0.0008 + 0.01035) + (stats.strength * 0.08034) + (stats.determination * 0.02622)); } double Dragoon::_baseAutoAttackDamage(const Actor* actor) const { auto& stats = actor->stats(); return stats.weaponDelay / 3.0 * (stats.weaponPhysicalDamage * (stats.strength * 0.00408 + stats.determination * 0.00208 - 0.30991) + (stats.strength * 0.07149) + (stats.determination * 0.03443)); } }<commit_msg>Jump and Dragonfire Dive are off the GCD<commit_after>#include "Dragoon.h" #include "../Action.h" #include "../Actor.h" #include "../Aura.h" namespace models { Dragoon::Dragoon() : Base("dragoon") { { struct Skill : Action { struct Buff : Aura { Buff() : Aura("internal-release") {} virtual std::chrono::microseconds duration() const override { return 15_s; } virtual double additionalCriticalHitChance() const override { return 0.10; } }; Skill() : Action("internal-release") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("life-surge") {} virtual std::chrono::microseconds duration() const override { return 10_s; } virtual double additionalCriticalHitChance() const override { return 1.0; } }; Skill() : Action("life-surge") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("blood-for-blood") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual double increasedDamage() const override { return 0.30; } }; Skill() : Action("blood-for-blood") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 80_s; } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("invigorate") {} virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 120_s; } virtual int tpRestoration() const override { return 500; } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("fracture-dot") {} virtual std::chrono::microseconds duration() const override { return 18_s; } virtual int tickDamage() const override { return 20; } }; Skill() : Action("fracture") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 100; } virtual int tpCost() const override { return 80; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("true-thrust") {} virtual int damage() const override { return 150; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("vorpal-thrust-combo") {} virtual int damage() const override { return 200; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "true-thrust"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("full-thrust-combo") {} virtual int damage() const override { return 300; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "vorpal-thrust-combo"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("impulse-drive-rear") {} virtual int damage() const override { return 180; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct Debuff : Aura { Debuff() : Aura("disembowel-combo") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual void transformIncomingDamage(Damage* damage) const override { if (damage->type == DamageTypePiercing) { damage->amount *= 1.0 / 0.9; } } }; Skill() : Action("disembowel-combo") { _targetAuras.push_back(new Debuff()); } virtual int damage() const override { return 220; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "impulse-drive-rear"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("chaos-thrust-dot") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual int tickDamage() const override { return 30; } }; Skill() : Action("chaos-thrust-combo") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 200; } virtual int tpCost() const override { return 60; } virtual bool requirements(const Actor* source) const override { return source->comboAction() && source->comboAction()->identifier() == "disembowel-combo"; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("heavy-thrust") {} virtual std::chrono::microseconds duration() const override { return 20_s; } virtual double increasedDamage() const override { return 0.15; } }; Skill() : Action("heavy-thrust-flank") { _sourceAuras.push_back(new Buff()); } virtual int damage() const override { return 170; } virtual int tpCost() const override { return 70; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { struct DoT : Aura { DoT() : Aura("phlebotomize-dot") {} virtual std::chrono::microseconds duration() const override { return 18_s; } virtual int tickDamage() const override { return 25; } }; Skill() : Action("phlebotomize") { _targetAuras.push_back(new DoT()); } virtual int damage() const override { return 170; } virtual int tpCost() const override { return 90; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("jump") {} virtual int damage(const Actor* source, const Actor* target) const override { return source->auraCount("power-surge", source) ? 300 : 200; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); source->dispelAura("power-surge", source); } virtual bool isOffGlobalCooldown() const override { return true; } }; _registerAction<Skill>(); } { struct Skill : Action { struct Buff : Aura { Buff() : Aura("power-surge") {} virtual std::chrono::microseconds duration() const override { return 10_s; } }; Skill() : Action("power-surge") { _sourceAuras.push_back(new Buff()); } virtual bool isOffGlobalCooldown() const override { return true; } virtual std::chrono::microseconds cooldown() const override { return 60_s; } }; _registerAction<Skill>(); } { struct Skill : Action { Skill() : Action("dragonfire-dive") {} virtual int damage() const override { return 250; } virtual std::chrono::microseconds cooldown() const override { return 180_s; } virtual void resolution(Actor* source, Actor* target) const override { source->dispelAura("life-surge", source); } virtual bool isOffGlobalCooldown() const override { return true; } }; _registerAction<Skill>(); } } int Dragoon::maximumMP(const Actor* actor) const { return 0; } DamageType Dragoon::_defaultDamageType() const { return DamageTypePiercing; } std::chrono::microseconds Dragoon::_baseGlobalCooldown(const Actor* actor) const { auto& stats = actor->stats(); auto gcd = std::chrono::duration<double>(2.5 - (stats.skillSpeed - 341) * (0.01 / 10.5)); return std::chrono::duration_cast<std::chrono::microseconds>(gcd); } // http://valk.dancing-mad.com/ double Dragoon::_basePotencyMultiplier(const Actor* actor) const { auto& stats = actor->stats(); return 0.01 * (stats.weaponPhysicalDamage * (stats.strength * 0.00389 + stats.determination * 0.0008 + 0.01035) + (stats.strength * 0.08034) + (stats.determination * 0.02622)); } double Dragoon::_baseAutoAttackDamage(const Actor* actor) const { auto& stats = actor->stats(); return stats.weaponDelay / 3.0 * (stats.weaponPhysicalDamage * (stats.strength * 0.00408 + stats.determination * 0.00208 - 0.30991) + (stats.strength * 0.07149) + (stats.determination * 0.03443)); } } <|endoftext|>
<commit_before>// @(#)root/gpad:$Id$ // Author: Rene Brun 03/07/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TDialogCanvas.h" #include "TGroupButton.h" #include "TText.h" #include "TStyle.h" ClassImp(TDialogCanvas) //______________________________________________________________________________ //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* //*-* A DialogCanvas is a canvas specialized to set attributes. //*-* It contains, in general, TGroupButton objects. //*-* When the APPLY button is executed, the actions corresponding //*-* to the active buttons are executed via the Interpreter. //*-* //*-* See examples in TAttLineCanvas, TAttFillCanvas, TAttTextCanvas, TAttMarkerCanvas //______________________________________________________________________________ TDialogCanvas::TDialogCanvas() : TCanvas() { //*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas default constructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================ } //_____________________________________________________________________________ TDialogCanvas::TDialogCanvas(const char *name, const char *title, Int_t ww, Int_t wh) : TCanvas(name,title,-ww,wh) { //*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== SetFillColor(36); fRefObject = 0; fRefPad = 0; } //_____________________________________________________________________________ TDialogCanvas::TDialogCanvas(const char *name, const char *title, Int_t wtopx, Int_t wtopy, UInt_t ww, UInt_t wh) : TCanvas(name,title,-wtopx,wtopy,ww,wh) { //*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== SetFillColor(36); fRefObject = 0; fRefPad = 0; } //______________________________________________________________________________ TDialogCanvas::~TDialogCanvas() { //*-*-*-*-*-*-*-*-*-*-*DialogCanvas default destructor*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== } //______________________________________________________________________________ void TDialogCanvas::Apply(const char *action) { //*-*-*-*-*-*-*-*-*Called when the APPLY button is executed*-*-*-*-*-*-*-*-*-*-* //*-* ======================================== if (!fRefPad) return; SetCursor(kWatch); TIter next(fPrimitives); TObject *refobj = fRefObject; TObject *obj; TGroupButton *button; if (!strcmp(action,"gStyle")) fRefObject = gStyle; while ((obj = next())) { if (obj->InheritsFrom(TGroupButton::Class())) { button = (TGroupButton*)obj; if (button->GetBorderMode() < 0) button->ExecuteAction(); } } fRefObject = refobj; if (!gROOT->GetSelectedPad()) return; gROOT->GetSelectedPad()->Modified(); gROOT->GetSelectedPad()->Update(); } //______________________________________________________________________________ void TDialogCanvas::BuildStandardButtons() { //*-*-*-*-*-*-*-*-*Create APPLY, gStyle and CLOSE buttons*-*-*-*-*-*-*-*-*-*-* //*-* ====================================== TGroupButton *apply = new TGroupButton("APPLY","Apply","",.05,.01,.3,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); apply = new TGroupButton("APPLY","gStyle","",.375,.01,.625,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); apply = new TGroupButton("APPLY","Close","",.70,.01,.95,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); } //______________________________________________________________________________ void TDialogCanvas::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2) { //*-*-*-*-*-*-*-*-*-*-*Set world coordinate system for the pad*-*-*-*-*-*-* //*-* ======================================= TPad::Range(x1,y1,x2,y2); } //______________________________________________________________________________ void TDialogCanvas::RecursiveRemove(TObject *obj) { //*-*-*-*-*-*-*-*Recursively remove object from a pad and its subpads*-*-*-*-* //*-* ==================================================== TPad::RecursiveRemove(obj); if (fRefObject == obj) fRefObject = 0; if (fRefPad == obj) fRefPad = 0; } <commit_msg>- Fix coverity report UNINIT _CTOR - Reformat the comments according to the ROOT coding conventions.<commit_after>// @(#)root/gpad:$Id$ // Author: Rene Brun 03/07/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TDialogCanvas.h" #include "TGroupButton.h" #include "TText.h" #include "TStyle.h" ClassImp(TDialogCanvas) //______________________________________________________________________________ // A DialogCanvas is a canvas specialized to set attributes. // It contains, in general, TGroupButton objects. // When the APPLY button is executed, the actions corresponding // to the active buttons are executed via the Interpreter. // // See examples in TAttLineCanvas, TAttFillCanvas, TAttTextCanvas, TAttMarkerCanvas //______________________________________________________________________________ TDialogCanvas::TDialogCanvas() : TCanvas() { // DialogCanvas default constructor fRefObject = 0; fRefPad = 0; } //_____________________________________________________________________________ TDialogCanvas::TDialogCanvas(const char *name, const char *title, Int_t ww, Int_t wh) : TCanvas(name,title,-ww,wh) { // DialogCanvas constructor SetFillColor(36); fRefObject = 0; fRefPad = 0; } //_____________________________________________________________________________ TDialogCanvas::TDialogCanvas(const char *name, const char *title, Int_t wtopx, Int_t wtopy, UInt_t ww, UInt_t wh) : TCanvas(name,title,-wtopx,wtopy,ww,wh) { // DialogCanvas constructor SetFillColor(36); fRefObject = 0; fRefPad = 0; } //______________________________________________________________________________ TDialogCanvas::~TDialogCanvas() { // DialogCanvas default destructor } //______________________________________________________________________________ void TDialogCanvas::Apply(const char *action) { // Called when the APPLY button is executed if (!fRefPad) return; SetCursor(kWatch); TIter next(fPrimitives); TObject *refobj = fRefObject; TObject *obj; TGroupButton *button; if (!strcmp(action,"gStyle")) fRefObject = gStyle; while ((obj = next())) { if (obj->InheritsFrom(TGroupButton::Class())) { button = (TGroupButton*)obj; if (button->GetBorderMode() < 0) button->ExecuteAction(); } } fRefObject = refobj; if (!gROOT->GetSelectedPad()) return; gROOT->GetSelectedPad()->Modified(); gROOT->GetSelectedPad()->Update(); } //______________________________________________________________________________ void TDialogCanvas::BuildStandardButtons() { // Create APPLY, gStyle and CLOSE buttons TGroupButton *apply = new TGroupButton("APPLY","Apply","",.05,.01,.3,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); apply = new TGroupButton("APPLY","gStyle","",.375,.01,.625,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); apply = new TGroupButton("APPLY","Close","",.70,.01,.95,.09); apply->SetTextSize(0.55); apply->SetBorderSize(3); apply->SetFillColor(44); apply->Draw(); } //______________________________________________________________________________ void TDialogCanvas::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2) { // Set world coordinate system for the pad TPad::Range(x1,y1,x2,y2); } //______________________________________________________________________________ void TDialogCanvas::RecursiveRemove(TObject *obj) { // Recursively remove object from a pad and its subpads TPad::RecursiveRemove(obj); if (fRefObject == obj) fRefObject = 0; if (fRefPad == obj) fRefPad = 0; } <|endoftext|>
<commit_before>/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "RStringView.h" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); // Returns false if further emission of this Log should be suppressed. virtual bool Emit(const TLogEntry &entry) = 0; }; class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } }; class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define R__LOG_PRETTY_FUNCTION __FUNCSIG__ #elif defined(__GNUC__) || defined(__clang__) #define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #else #define R__LOG_PRETTY_FUNCTION __func__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(R__LOG_PRETTY_FUNCTION) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif <commit_msg>Let '__PRETTY_FUNCTION__' be the default<commit_after>/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "RStringView.h" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); // Returns false if further emission of this Log should be suppressed. virtual bool Emit(const TLogEntry &entry) = 0; }; class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } }; class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define R__LOG_PRETTY_FUNCTION __FUNCSIG__ #else #define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(R__LOG_PRETTY_FUNCTION) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/dash-config.h> #endif #include <tinyformat.h> #include <utiltime.h> #include <atomic> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> static std::atomic<int64_t> nMockTime(0); //!< For unit testing int64_t GetTime() { int64_t mocktime = nMockTime.load(std::memory_order_relaxed); if (mocktime) return mocktime; time_t now = time(nullptr); assert(now > 0); return now; } void SetMockTime(int64_t nMockTimeIn) { nMockTime.store(nMockTimeIn, std::memory_order_relaxed); } int64_t GetMockTime() { return nMockTime.load(std::memory_order_relaxed); } int64_t GetTimeMillis() { int64_t now = (boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); assert(now > 0); return now; } int64_t GetTimeMicros() { int64_t now = (boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); assert(now > 0); return now; } int64_t GetSystemTimeInSeconds() { return GetTimeMicros()/1000000; } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { static std::locale classic(std::locale::classic()); // std::locale takes ownership of the pointer std::locale loc(classic, new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } <commit_msg>Use std::chrono for GetTimeMillis/GetTimeMicros<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/dash-config.h> #endif #include <tinyformat.h> #include <utiltime.h> #include <atomic> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> #include <chrono> static std::atomic<int64_t> nMockTime(0); //!< For unit testing int64_t GetTime() { int64_t mocktime = nMockTime.load(std::memory_order_relaxed); if (mocktime) return mocktime; time_t now = time(nullptr); assert(now > 0); return now; } void SetMockTime(int64_t nMockTimeIn) { nMockTime.store(nMockTimeIn, std::memory_order_relaxed); } int64_t GetMockTime() { return nMockTime.load(std::memory_order_relaxed); } int64_t GetTimeMillis() { int64_t now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count(); assert(now > 0); return now; } int64_t GetTimeMicros() { int64_t now = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::system_clock::now()).time_since_epoch().count(); assert(now > 0); return now; } int64_t GetSystemTimeInSeconds() { return GetTimeMicros()/1000000; } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { static std::locale classic(std::locale::classic()); // std::locale takes ownership of the pointer std::locale loc(classic, new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include <vector> #include <cmath> #include <memory> #include <dune/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/fvector.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Checkerboard : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const RangeType value) : BaseType(ent) , value_(value) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override { return 0; } virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override { assert(this->is_a_valid_point(xx)); ret = value_; } virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: const RangeType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; static const int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".checkerboard"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["lower_left"] = "[0.0 0.0 0.0]"; config["upper_right"] = "[1.0 1.0 1.0]"; config["num_elements"] = "[2 2 2]"; config["values"] = "[1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0]"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // calculate number of values and get values auto num_elements = cfg.get("num_elements", default_cfg.get< Common::FieldVector< size_t, dimDomain > >("num_elements"), dimDomain); size_t num_values = 1; for (size_t ii = 0; ii < num_elements.size(); ++ii) num_values *= num_elements[ii]; std::vector< RangeType > values(num_values); auto values_rf = cfg.get("values", default_cfg.get< std::vector< RangeFieldType > >("values"), num_values); for (size_t ii = 0; ii < values_rf.size(); ++ii) values[ii] = RangeType(values_rf[ii]); // create return Common::make_unique< ThisType >( cfg.get("lower_left", default_cfg.get< Common::FieldVector< DomainFieldType, dimDomain > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< Common::FieldVector< DomainFieldType, dimDomain > >("upper_right"), dimDomain), std::move(num_elements), std::move(values), cfg.get("name", default_cfg.get< std::string > ("name"))); } // ... create(...) Checkerboard(const Common::FieldVector< DomainFieldType, dimDomain >& lowerLeft, const Common::FieldVector< DomainFieldType, dimDomain >& upperRight, const Common::FieldVector< size_t, dimDomain >& numElements, const std::vector< RangeType >& values, const std::string nm = static_id()) : lowerLeft_(new Common::FieldVector< DomainFieldType, dimDomain >(lowerLeft)) , upperRight_(new Common::FieldVector< DomainFieldType, dimDomain >(upperRight)) , numElements_(new Common::FieldVector< size_t, dimDomain >(numElements)) , values_(new std::vector< RangeType >(values)) , name_(nm) { // checks size_t totalSubdomains = 1; for (size_t dd = 0; dd < dimDomain; ++dd) { const auto& ll = (*lowerLeft_)[dd]; const auto& ur = (*upperRight_)[dd]; const auto& ne = (*numElements_)[dd]; if (!(ll < ur)) DUNE_THROW(Dune::RangeError, "lowerLeft has to be elementwise smaller than upperRight!"); totalSubdomains *= ne; } if (values_->size() < totalSubdomains) DUNE_THROW(Dune::RangeError, "values too small (is " << values_->size() << ", should be " << totalSubdomains << ")"); } // Checkerboard(...) Checkerboard(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; ThisType& operator=(ThisType&& source) = delete; virtual ThisType* copy() const override { return new ThisType(*this); } virtual std::string type() const override { return BaseType::static_id() + ".checkerboard"; } virtual std::string name() const override { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override { // decide on the subdomain the center of the entity belongs to const auto center = entity.geometry().center(); std::vector< size_t > whichPartition(dimDomain, 0); const auto& ll = *lowerLeft_; const auto& ur = *upperRight_; const auto& ne = *numElements_; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd]*((center[dd] - ll[dd])/(ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*ne[0]; else subdomain = whichPartition[0] + whichPartition[1]*ne[0] + whichPartition[2]*ne[1]*ne[0]; // return the component that belongs to the subdomain return std::unique_ptr< Localfunction >(new Localfunction(entity, (*values_)[subdomain])); } // ... local_function(...) private: std::shared_ptr< const Common::FieldVector< DomainFieldType, dimDomain > > lowerLeft_; std::shared_ptr< const Common::FieldVector< DomainFieldType, dimDomain > > upperRight_; std::shared_ptr< const Common::FieldVector< size_t, dimDomain > > numElements_; std::shared_ptr< const std::vector< RangeType > > values_; std::string name_; }; // class Checkerboard } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH <commit_msg>[functions.checkerboard] remove unused local typedefs<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH #include <vector> #include <cmath> #include <memory> #include <dune/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/fvector.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Checkerboard : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const RangeType value) : BaseType(ent) , value_(value) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override { return 0; } virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override { assert(this->is_a_valid_point(xx)); ret = value_; } virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: const RangeType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".checkerboard"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["lower_left"] = "[0.0 0.0 0.0]"; config["upper_right"] = "[1.0 1.0 1.0]"; config["num_elements"] = "[2 2 2]"; config["values"] = "[1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0]"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // calculate number of values and get values auto num_elements = cfg.get("num_elements", default_cfg.get< Common::FieldVector< size_t, dimDomain > >("num_elements"), dimDomain); size_t num_values = 1; for (size_t ii = 0; ii < num_elements.size(); ++ii) num_values *= num_elements[ii]; std::vector< RangeType > values(num_values); auto values_rf = cfg.get("values", default_cfg.get< std::vector< RangeFieldType > >("values"), num_values); for (size_t ii = 0; ii < values_rf.size(); ++ii) values[ii] = RangeType(values_rf[ii]); // create return Common::make_unique< ThisType >( cfg.get("lower_left", default_cfg.get< Common::FieldVector< DomainFieldType, dimDomain > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< Common::FieldVector< DomainFieldType, dimDomain > >("upper_right"), dimDomain), std::move(num_elements), std::move(values), cfg.get("name", default_cfg.get< std::string > ("name"))); } // ... create(...) Checkerboard(const Common::FieldVector< DomainFieldType, dimDomain >& lowerLeft, const Common::FieldVector< DomainFieldType, dimDomain >& upperRight, const Common::FieldVector< size_t, dimDomain >& numElements, const std::vector< RangeType >& values, const std::string nm = static_id()) : lowerLeft_(new Common::FieldVector< DomainFieldType, dimDomain >(lowerLeft)) , upperRight_(new Common::FieldVector< DomainFieldType, dimDomain >(upperRight)) , numElements_(new Common::FieldVector< size_t, dimDomain >(numElements)) , values_(new std::vector< RangeType >(values)) , name_(nm) { // checks size_t totalSubdomains = 1; for (size_t dd = 0; dd < dimDomain; ++dd) { const auto& ll = (*lowerLeft_)[dd]; const auto& ur = (*upperRight_)[dd]; const auto& ne = (*numElements_)[dd]; if (!(ll < ur)) DUNE_THROW(Dune::RangeError, "lowerLeft has to be elementwise smaller than upperRight!"); totalSubdomains *= ne; } if (values_->size() < totalSubdomains) DUNE_THROW(Dune::RangeError, "values too small (is " << values_->size() << ", should be " << totalSubdomains << ")"); } // Checkerboard(...) Checkerboard(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; ThisType& operator=(ThisType&& source) = delete; virtual ThisType* copy() const override { return new ThisType(*this); } virtual std::string type() const override { return BaseType::static_id() + ".checkerboard"; } virtual std::string name() const override { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override { // decide on the subdomain the center of the entity belongs to const auto center = entity.geometry().center(); std::vector< size_t > whichPartition(dimDomain, 0); const auto& ll = *lowerLeft_; const auto& ur = *upperRight_; const auto& ne = *numElements_; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd]*((center[dd] - ll[dd])/(ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*ne[0]; else subdomain = whichPartition[0] + whichPartition[1]*ne[0] + whichPartition[2]*ne[1]*ne[0]; // return the component that belongs to the subdomain return std::unique_ptr< Localfunction >(new Localfunction(entity, (*values_)[subdomain])); } // ... local_function(...) private: std::shared_ptr< const Common::FieldVector< DomainFieldType, dimDomain > > lowerLeft_; std::shared_ptr< const Common::FieldVector< DomainFieldType, dimDomain > > upperRight_; std::shared_ptr< const Common::FieldVector< size_t, dimDomain > > numElements_; std::shared_ptr< const std::vector< RangeType > > values_; std::string name_; }; // class Checkerboard } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH #define DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH #ifdef HAVE_EIGEN #include <Eigen/Eigen> #include <dune/common/exceptions.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Stuff { namespace LA { namespace Solver { namespace Eigen { namespace Sparse { template< class ElementType = double > class Interface { public: typedef Dune::Stuff::LA::Container::Eigen::SparseMatrix< ElementType > SparseMatrixType; typedef Dune::Stuff::LA::Container::Eigen::DenseVector< ElementType > DenseVectorType; virtual bool apply(const SparseMatrixType& /*systemMatrix*/, const DenseVectorType& /*rhsVector*/, DenseVectorType& /*solutionVector*/, unsigned int /*maxIter*/, double /*precision*/) const = 0; }; // class Interface template< class ElementType = double > class BicgstabIlut : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int maxIter = 5000, double precision = 1e-12) const { typedef ::Eigen::IncompleteLUT< ElementType > PreconditionerType; typedef ::Eigen::BiCGSTAB< typename SparseMatrixType::BaseType, PreconditionerType > SolverType; SolverType solver; solver.setMaxIterations(maxIter); solver.setTolerance(precision); solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } // virtual bool apply(...) }; // struct BicgstabIlut //struct BicgstabDiagonal //{ //public: // static const std::string id; // template< class MatrixType, class SolutionType, class RhsType > // static void apply(MatrixType& matrix, SolutionType& solution, RhsType& rhs, unsigned int maxIter = 5000, double precision = 1e-12) // { // typedef typename MatrixType::EntryType EntryType; // typedef typename MatrixType::StorageType EigenMatrixType; // typedef ::Eigen::DiagonalPreconditioner< EntryType > PreconditionerType; // typedef ::Eigen::BiCGSTAB< EigenMatrixType, PreconditionerType > SolverType; // SolverType solver; // solver.setMaxIterations(maxIter); // solver.setTolerance(precision); // solver.compute(*(matrix.storage())); // *(solution.storage()) = solver.solve(*(rhs.storage())); // } //}; // struct BicgstabDiagonal //const std::string BicgstabDiagonal::id = "eigen.bicgstab.diagonal"; //struct CgDiagonalUpper //{ //public: // static const std::string id; // template< class MatrixType, class SolutionType, class RhsType > // static void apply(MatrixType& matrix, SolutionType& solution, RhsType& rhs, unsigned int maxIter = 5000, double precision = 1e-12) // { // typedef typename MatrixType::EntryType EntryType; // typedef typename MatrixType::StorageType EigenMatrixType; // typedef ::Eigen::DiagonalPreconditioner< EntryType > PreconditionerType; // typedef ::Eigen::ConjugateGradient< EigenMatrixType, ::Eigen::Upper, PreconditionerType > SolverType; // SolverType solver; // solver.setMaxIterations(maxIter); // solver.setTolerance(precision); // solver.compute(*(matrix.storage())); // *(solution.storage()) = solver.solve(*(rhs.storage())); // } //}; // struct CgDiagonalUpper //const std::string CgDiagonalUpper::id = "eigen.cg.diagonal.upper"; //struct CgDiagonalLower //{ //public: // static const std::string id; // template< class MatrixType, class SolutionType, class RhsType > // static void apply(MatrixType& matrix, SolutionType& solution, RhsType& rhs, unsigned int maxIter = 5000, double precision = 1e-12) // { // typedef typename MatrixType::EntryType EntryType; // typedef typename MatrixType::StorageType EigenMatrixType; // typedef ::Eigen::DiagonalPreconditioner< EntryType > PreconditionerType; // typedef ::Eigen::ConjugateGradient< EigenMatrixType, ::Eigen::Lower, PreconditionerType > SolverType; // SolverType solver; // solver.setMaxIterations(maxIter); // solver.setTolerance(precision); // solver.compute(*(matrix.storage())); // *(solution.storage()) = solver.solve(*(rhs.storage())); // } //}; // struct CgDiagonalLower //const std::string CgDiagonalLower::id = "eigen.cg.diagonal.lower"; //struct SimplicialcholeskyUpper //{ //public: // static const std::string id; // template< class MatrixType, class SolutionType, class RhsType > // static void apply(MatrixType& matrix, SolutionType& solution, RhsType& rhs, unsigned int maxIter = 5000, double precision = 1e-12) // { // typedef typename MatrixType::EntryType EntryType; // typedef typename MatrixType::StorageType EigenMatrixType; // typedef ::Eigen::SimplicialCholesky< EigenMatrixType, ::Eigen::Upper > SolverType; // SolverType solver; // solver.compute(*(matrix.storage())); // *(solution.storage()) = solver.solve(*(rhs.storage())); // } //}; // struct SimplicialcholeskyUpper //const std::string SimplicialcholeskyUpper::id = "eigen.simplicialcholesky.upper"; //struct SimplicialcholeskyLower //{ //public: // static const std::string id; // template< class MatrixType, class SolutionType, class RhsType > // static void apply(MatrixType& matrix, SolutionType& solution, RhsType& rhs, unsigned int maxIter = 5000, double precision = 1e-12) // { // typedef typename MatrixType::EntryType EntryType; // typedef typename MatrixType::StorageType EigenMatrixType; // typedef ::Eigen::SimplicialCholesky< EigenMatrixType, ::Eigen::Lower > SolverType; // SolverType solver; // solver.compute(*(matrix.storage())); // *(solution.storage()) = solver.solve(*(rhs.storage())); // } //}; // struct SimplicialcholeskyLower //const std::string SimplicialcholeskyLower::id = "eigen.simplicialcholesky.lower"; template< class ElementType = double > Interface< ElementType >* create(const std::string type = "eigen.bicgstab.incompletelut") { if (type == "eigen.bicgstab.incompletelut") { typedef BicgstabIlut< ElementType > BicgstabIlutType; BicgstabIlutType* bicgstabIlut = new BicgstabIlutType; return bicgstabIlut; } else DUNE_THROW(Dune::RangeError, "\nERROR: unknown solver '" << type << "' requested!"); } // Interface< ElementType >* create(const std::string type = "eigen.bicgstab.incompletelut") } // namespace Sparse } // namespace Eigen } // namespace Solver } // namespace LA } // namespace Stuff } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH <commit_msg>[la.solver.eigen.sparse] added 5 linear solvers<commit_after>#ifndef DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH #define DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH //#ifdef HAVE_EIGEN #include <Eigen/Eigen> #include <dune/common/exceptions.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Stuff { namespace LA { namespace Solver { namespace Eigen { namespace Sparse { template< class ElementType = double > class Interface { public: typedef Dune::Stuff::LA::Container::Eigen::SparseMatrix< ElementType > SparseMatrixType; typedef Dune::Stuff::LA::Container::Eigen::DenseVector< ElementType > DenseVectorType; virtual bool apply(const SparseMatrixType& /*systemMatrix*/, const DenseVectorType& /*rhsVector*/, DenseVectorType& /*solutionVector*/, unsigned int /*maxIter*/, double /*precision*/) const = 0; }; // class Interface template< class ElementType = double > class BicgstabIlut : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int maxIter = 5000, double precision = 1e-12) const { typedef ::Eigen::IncompleteLUT< ElementType > PreconditionerType; typedef ::Eigen::BiCGSTAB< typename SparseMatrixType::BaseType, PreconditionerType > SolverType; SolverType solver; solver.setMaxIterations(maxIter); solver.setTolerance(precision); solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } // virtual bool apply(...) }; // class BicgstabIlut template< class ElementType = double > class BicgstabDiagonal : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int maxIter = 5000, double precision = 1e-12) const { typedef ::Eigen::DiagonalPreconditioner< ElementType > PreconditionerType; typedef ::Eigen::BiCGSTAB< SparseMatrixType, PreconditionerType > SolverType; SolverType solver; solver.setMaxIterations(maxIter); solver.setTolerance(precision); solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } }; // class BicgstabDiagonal template< class ElementType = double > class CgDiagonalUpper : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int maxIter = 5000, double precision = 1e-12) const { typedef ::Eigen::DiagonalPreconditioner< ElementType > PreconditionerType; typedef ::Eigen::ConjugateGradient< SparseMatrixType, ::Eigen::Upper, PreconditionerType > SolverType; SolverType solver; solver.setMaxIterations(maxIter); solver.setTolerance(precision); solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } }; // class CgDiagonalUpper template< class ElementType = double > class CgDiagonalLower : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int maxIter = 5000, double precision = 1e-12) const { typedef ::Eigen::DiagonalPreconditioner< ElementType > PreconditionerType; typedef ::Eigen::ConjugateGradient< SparseMatrixType, ::Eigen::Lower, PreconditionerType > SolverType; SolverType solver; solver.setMaxIterations(maxIter); solver.setTolerance(precision); solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } }; // class CgDiagonalLower template< class ElementType = double > class SimplicialcholeskyUpper : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int DUNE_UNUSED(maxIter) = 5000, double DUNE_UNUSED(precision) = 1e-12) const { typedef ::Eigen::SimplicialCholesky< SparseMatrixType, ::Eigen::Upper > SolverType; SolverType solver; solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } }; // class SimplicialcholeskyUpper template< class ElementType = double > class SimplicialcholeskyLower : public Interface< ElementType > { public: typedef Interface< ElementType > BaseType; typedef typename BaseType::SparseMatrixType SparseMatrixType; typedef typename BaseType::DenseVectorType DenseVectorType; virtual bool apply(const SparseMatrixType& systemMatrix, const DenseVectorType& rhsVector, DenseVectorType& solutionVector, unsigned int DUNE_UNUSED(maxIter) = 5000, double DUNE_UNUSED(precision) = 1e-12) const { typedef ::Eigen::SimplicialCholesky< SparseMatrixType, ::Eigen::Lower > SolverType; SolverType solver; solver.compute(systemMatrix.base()); solutionVector.base() = solver.solve(rhsVector.base()); const ::Eigen::ComputationInfo info = solver.info(); return (info == ::Eigen::Success); } }; // class SimplicialcholeskyLower template< class ElementType = double > Interface< ElementType >* create(const std::string type = "eigen.bicgstab.incompletelut") { if (type == "eigen.bicgstab.incompletelut") { typedef BicgstabIlut< ElementType > BicgstabIlutType; BicgstabIlutType* bicgstabIlut = new BicgstabIlutType; return bicgstabIlut; } else if (type == "eigen.bicgstab.diagonal") { typedef BicgstabDiagonal< ElementType > BicgstabDiagonalType; BicgstabDiagonalType* bicgstabDiagonal = new BicgstabDiagonalType; return bicgstabDiagonal; } else if (type == "eigen.cg.diagonal.upper") { typedef CgDiagonalUpper< ElementType > CgDiagonalUpperType; CgDiagonalUpperType* cgDiagonalUpper = new CgDiagonalUpperType; return cgDiagonalUpper; } else if (type == "eigen.cg.diagonal.lower") { typedef CgDiagonalLower< ElementType > CgDiagonalLowerType; CgDiagonalLowerType* cgDiagonalLower = new CgDiagonalLowerType; return cgDiagonalLower; } else if (type == "eigen.simplicialcholesky.upper") { typedef SimplicialcholeskyUpper< ElementType > SimplicialcholeskyUpperType; SimplicialcholeskyUpperType* simplicialcholeskyUpper = new SimplicialcholeskyUpperType; return simplicialcholeskyUpper; } else if (type == "eigen.simplicialcholesky.lower") { typedef SimplicialcholeskyLower< ElementType > SimplicialcholeskyLowerType; SimplicialcholeskyLowerType* simplicialcholeskyLower = new SimplicialcholeskyLowerType; return simplicialcholeskyLower; } else DUNE_THROW(Dune::RangeError, "\nERROR: unknown linear solver '" << type << "' requested!"); } // Interface< ElementType >* create(const std::string type = "eigen.bicgstab.incompletelut") } // namespace Sparse } // namespace Eigen } // namespace Solver } // namespace LA } // namespace Stuff } // namespace Dune //#endif // HAVE_EIGEN #endif // DUNE_STUFF_LA_SOLVER_SPARSE_EIGEN_HH <|endoftext|>
<commit_before>/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "sdkconfig.h" void signal_generator_task(void *pvParameter) { while(1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } } void signal_generator_app_main() { nvs_flash_init(); xTaskCreate(&signal_generator_task, "signal_generator_task", 512, NULL, 5, NULL); } <commit_msg>Update signal.generator.cpp<commit_after>/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "sdkconfig.h" void signal_generator_task(void *pvParameter) { while(1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } } void signal_generator_app_main() { xTaskCreate(&signal_generator_task, "signal_generator_task", 512, NULL, 5, NULL); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include "VisitorUtils.hpp" #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Printer.hpp" #include "mtac/TemporaryAllocator.hpp" //The custom optimizations #include "mtac/VariableOptimizations.hpp" #include "mtac/FunctionOptimizations.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/BasicBlockOptimizations.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/ConcatReduction.hpp" #include "mtac/inlining.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" using namespace eddic; namespace { static const unsigned int MAX_THREADS = 2; template<typename Visitor> bool apply_to_all(std::shared_ptr<mtac::Function> function){ Visitor visitor; mtac::visit_all_statements(visitor, function); return visitor.optimized; } template<typename Visitor> bool apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Function> function){ bool optimized = false; for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Problem> bool data_flow_optimization(std::shared_ptr<mtac::Function> function){ bool optimized = false; Problem problem; auto results = mtac::data_flow(function, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } return optimized; } bool debug(const std::string& name, bool b, std::shared_ptr<mtac::Function> function){ if(option_defined("dev")){ if(b){ std::cout << "optimization " << name << " returned true" << std::endl; //Print the function print(function); } else { std::cout << "optimization " << name << " returned false" << std::endl; } } return b; } template<typename Functor> bool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function){ bool b; { PerfsTimer timer(name); b = functor(function); } return debug(name, b, function); } template<typename Functor, typename Arg2> bool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function, Arg2& arg2){ bool b; { PerfsTimer timer(name); b = functor(function, arg2); } return debug(name, b, function); } void remove_nop(std::shared_ptr<mtac::Function> function){ for(auto& block : function->getBasicBlocks()){ auto it = iterate(block->statements); while(it.has_next()){ if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){ it.erase(); continue; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){ if((*ptr)->op == mtac::Operator::NOP){ it.erase(); continue; } } ++it; } } } void optimize_function(std::shared_ptr<mtac::Function> function, std::shared_ptr<StringPool> pool){ if(option_defined("dev")){ std::cout << "Start optimizations on " << function->getName() << std::endl; print(function); } bool optimized; do { optimized = false; optimized |= debug("Aritmetic Identities", &apply_to_all<mtac::ArithmeticIdentities>, function); optimized |= debug("Reduce in Strength", &apply_to_all<mtac::ReduceInStrength>, function); optimized |= debug("Constant folding", &apply_to_all<mtac::ConstantFolding>, function); optimized |= debug("Constant propagation", &data_flow_optimization<mtac::ConstantPropagationProblem>, function); optimized |= debug("Offset Constant Propagation", &data_flow_optimization<mtac::OffsetConstantPropagationProblem>, function); //If there was optimizations here, better to try again before perfoming common subexpression if(optimized){ continue; } optimized |= debug("Common Subexpression Elimination", &data_flow_optimization<mtac::CommonSubexpressionElimination>, function); optimized |= debug("Math Propagation", &apply_to_basic_blocks_two_pass<mtac::MathPropagation>, function); optimized |= debug("Optimize Branches", &mtac::optimize_branches, function); optimized |= debug("Optimize Concat", &mtac::optimize_concat, function, pool); optimized |= debug("Remove dead basic block", &mtac::remove_dead_basic_blocks, function); optimized |= debug("Merge basic block", &mtac::merge_basic_blocks, function); remove_nop(function); optimized |= debug("Dead-Code Elimination", &mtac::dead_code_elimination, function); optimized |= debug("Remove aliases", &mtac::remove_aliases, function); } while (optimized); //Remove variables that are not used after optimizations clean_variables(function); } void basic_optimize_function(std::shared_ptr<mtac::Function> function){ if(option_defined("dev")){ std::cout << "Start basic optimizations on " << function->getName() << std::endl; print(function); } debug("Constant folding", apply_to_all<mtac::ConstantFolding>(function), function); /*//Liveness debugging mtac::LiveVariableAnalysisProblem problem; auto results = mtac::data_flow(function, problem); for(auto& block : function->getBasicBlocks()){ auto it = block->statements.begin(); auto end = block->statements.end(); while(it != end){ auto statement = *it; mtac::Printer printer; printer.printStatement(statement); std::cout << "OUT{"; for(auto& var : results->OUT_S[statement].values()){ std::cout << var->name() << ", "; } std::cout << "}" << std::endl; std::cout << "IN{"; for(auto& var : results->IN_S[statement].values()){ std::cout << var->name() << ", "; } std::cout << "}" << std::endl; ++it; } }*/ } void optimize_all_functions(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool){ PerfsTimer timer("Whole optimizations"); auto& functions = program->functions; //Find a better heuristic to configure the number of threads std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS)); if(option_defined("dev")){ threads = 1; } std::vector<std::thread> pool; for(std::size_t tid = 0; tid < threads; ++tid){ pool.push_back(std::thread([tid, threads, &string_pool, &functions](){ std::size_t i = tid; while(i < functions.size()){ optimize_function(functions[i], string_pool); i += threads; } })); } //Wait for all the threads to finish std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();}); } } //end of anonymous namespace void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool) const { //Allocate storage for the temporaries that need to be stored allocate_temporary(program); if(option_defined("fglobal-optimization")){ bool optimized = false; do{ mtac::remove_unused_functions(program); optimize_all_functions(program, string_pool); optimized = mtac::remove_empty_functions(program); optimized = mtac::inline_functions(program); } while(optimized); //Allocate storage for the temporaries that need to be stored allocate_temporary(program); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) basic_optimize(program, string_pool); //Allocate storage for the temporaries that need to be stored allocate_temporary(program); } } void mtac::Optimizer::basic_optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> /*string_pool*/) const { PerfsTimer timer("Whole basic optimizations"); auto& functions = program->functions; //Find a better heuristic to configure the number of threads std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS)); if(option_defined("dev")){ threads = 1; } std::vector<std::thread> pool; for(std::size_t tid = 0; tid < threads; ++tid){ pool.push_back(std::thread([tid, threads, &functions](){ std::size_t i = tid; while(i < functions.size()){ basic_optimize_function(functions[i]); i += threads; } })); } //Wait for all the threads to finish std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();}); } <commit_msg>In dev mode, do not create new thread at all<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include "VisitorUtils.hpp" #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Printer.hpp" #include "mtac/TemporaryAllocator.hpp" //The custom optimizations #include "mtac/VariableOptimizations.hpp" #include "mtac/FunctionOptimizations.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/BasicBlockOptimizations.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/ConcatReduction.hpp" #include "mtac/inlining.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" using namespace eddic; namespace { static const unsigned int MAX_THREADS = 2; template<typename Visitor> bool apply_to_all(std::shared_ptr<mtac::Function> function){ Visitor visitor; mtac::visit_all_statements(visitor, function); return visitor.optimized; } template<typename Visitor> bool apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Function> function){ bool optimized = false; for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Problem> bool data_flow_optimization(std::shared_ptr<mtac::Function> function){ bool optimized = false; Problem problem; auto results = mtac::data_flow(function, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } return optimized; } bool debug(const std::string& name, bool b, std::shared_ptr<mtac::Function> function){ if(option_defined("dev")){ if(b){ std::cout << "optimization " << name << " returned true" << std::endl; //Print the function print(function); } else { std::cout << "optimization " << name << " returned false" << std::endl; } } return b; } template<typename Functor> bool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function){ bool b; { PerfsTimer timer(name); b = functor(function); } return debug(name, b, function); } template<typename Functor, typename Arg2> bool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function, Arg2& arg2){ bool b; { PerfsTimer timer(name); b = functor(function, arg2); } return debug(name, b, function); } void remove_nop(std::shared_ptr<mtac::Function> function){ for(auto& block : function->getBasicBlocks()){ auto it = iterate(block->statements); while(it.has_next()){ if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){ it.erase(); continue; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){ if((*ptr)->op == mtac::Operator::NOP){ it.erase(); continue; } } ++it; } } } void optimize_function(std::shared_ptr<mtac::Function> function, std::shared_ptr<StringPool> pool){ if(option_defined("dev")){ std::cout << "Start optimizations on " << function->getName() << std::endl; print(function); } bool optimized; do { optimized = false; optimized |= debug("Aritmetic Identities", &apply_to_all<mtac::ArithmeticIdentities>, function); optimized |= debug("Reduce in Strength", &apply_to_all<mtac::ReduceInStrength>, function); optimized |= debug("Constant folding", &apply_to_all<mtac::ConstantFolding>, function); optimized |= debug("Constant propagation", &data_flow_optimization<mtac::ConstantPropagationProblem>, function); optimized |= debug("Offset Constant Propagation", &data_flow_optimization<mtac::OffsetConstantPropagationProblem>, function); //If there was optimizations here, better to try again before perfoming common subexpression if(optimized){ continue; } optimized |= debug("Common Subexpression Elimination", &data_flow_optimization<mtac::CommonSubexpressionElimination>, function); optimized |= debug("Math Propagation", &apply_to_basic_blocks_two_pass<mtac::MathPropagation>, function); optimized |= debug("Optimize Branches", &mtac::optimize_branches, function); optimized |= debug("Optimize Concat", &mtac::optimize_concat, function, pool); optimized |= debug("Remove dead basic block", &mtac::remove_dead_basic_blocks, function); optimized |= debug("Merge basic block", &mtac::merge_basic_blocks, function); remove_nop(function); optimized |= debug("Dead-Code Elimination", &mtac::dead_code_elimination, function); optimized |= debug("Remove aliases", &mtac::remove_aliases, function); } while (optimized); //Remove variables that are not used after optimizations clean_variables(function); } void basic_optimize_function(std::shared_ptr<mtac::Function> function){ if(option_defined("dev")){ std::cout << "Start basic optimizations on " << function->getName() << std::endl; print(function); } debug("Constant folding", apply_to_all<mtac::ConstantFolding>(function), function); /*//Liveness debugging mtac::LiveVariableAnalysisProblem problem; auto results = mtac::data_flow(function, problem); for(auto& block : function->getBasicBlocks()){ auto it = block->statements.begin(); auto end = block->statements.end(); while(it != end){ auto statement = *it; mtac::Printer printer; printer.printStatement(statement); std::cout << "OUT{"; for(auto& var : results->OUT_S[statement].values()){ std::cout << var->name() << ", "; } std::cout << "}" << std::endl; std::cout << "IN{"; for(auto& var : results->IN_S[statement].values()){ std::cout << var->name() << ", "; } std::cout << "}" << std::endl; ++it; } }*/ } void optimize_all_functions(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool){ PerfsTimer timer("Whole optimizations"); auto& functions = program->functions; if(option_defined("dev")){ for(auto& function : functions){ optimize_function(function, string_pool); } } else { //Find a better heuristic to configure the number of threads std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS)); std::vector<std::thread> pool; for(std::size_t tid = 0; tid < threads; ++tid){ pool.push_back(std::thread([tid, threads, &string_pool, &functions](){ std::size_t i = tid; while(i < functions.size()){ optimize_function(functions[i], string_pool); i += threads; } })); } //Wait for all the threads to finish std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();}); } } } //end of anonymous namespace void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool) const { //Allocate storage for the temporaries that need to be stored allocate_temporary(program); if(option_defined("fglobal-optimization")){ bool optimized = false; do{ mtac::remove_unused_functions(program); optimize_all_functions(program, string_pool); optimized = mtac::remove_empty_functions(program); optimized = mtac::inline_functions(program); } while(optimized); //Allocate storage for the temporaries that need to be stored allocate_temporary(program); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) basic_optimize(program, string_pool); //Allocate storage for the temporaries that need to be stored allocate_temporary(program); } } void mtac::Optimizer::basic_optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> /*string_pool*/) const { PerfsTimer timer("Whole basic optimizations"); auto& functions = program->functions; if(option_defined("dev")){ for(auto& function : functions){ basic_optimize_function(function); } } else { //Find a better heuristic to configure the number of threads std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS)); std::vector<std::thread> pool; for(std::size_t tid = 0; tid < threads; ++tid){ pool.push_back(std::thread([tid, threads, &functions](){ std::size_t i = tid; while(i < functions.size()){ basic_optimize_function(functions[i]); i += threads; } })); } //Wait for all the threads to finish std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();}); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include "boost_cfg.hpp" #include <boost/utility/enable_if.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "VisitorUtils.hpp" #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Printer.hpp" #include "mtac/TemporaryAllocator.hpp" //The custom optimizations #include "mtac/VariableOptimizations.hpp" #include "mtac/FunctionOptimizations.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/BasicBlockOptimizations.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/ConcatReduction.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_optimizations.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::optimize_concat*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(bool, need_pool, false); STATIC_CONSTANT(bool, need_platform, false); STATIC_CONSTANT(bool, need_configuration, false); STATIC_CONSTANT(unsigned int, todo_flags, 0); typedef passes sub_passes; }; } } namespace { //TODO Find a more elegant way than using pointers typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::inline_functions* > ipa_passes; struct pass_runner { bool optimized = false; std::shared_ptr<mtac::Program> program; std::shared_ptr<mtac::Function> function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; pass_runner(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform) : program(program), pool(pool), configuration(configuration), platform(platform) {}; template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::todo_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : function->getBasicBlocks()){ auto it = iterate(block->statements); while(it.has_next()){ if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){ it.erase(); continue; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){ if((*ptr)->op == mtac::Operator::NOP){ it.erase(); continue; } } ++it; } } } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::todo_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_pool, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_pool, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_platform, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_platform, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_configuration, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_configuration, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> Pass make_pass(){ Pass pass; set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(){ auto pass = make_pass<Pass>(); return pass(program); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(){ bool optimized = false; auto& functions = program->functions; for(auto& function : functions){ this->function = function; if(log::enabled<Debug>()){ log::emit<Debug>("Optimizer") << "Start optimizations on " << function->getName() << log::endl; print(function); } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(*this); } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(){ auto pass = make_pass<Pass>(); return pass(function); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(){ auto visitor = make_pass<Pass>(); mtac::visit_all_statements(visitor, function); return visitor.optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(){ bool optimized = false; auto problem = make_pass<Pass>(); auto results = mtac::data_flow(function, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(){ bool optimized = false; auto visitor = make_pass<Pass>(); for(auto& block : function->getBasicBlocks()){ visitor.clear(); visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(){ bool optimized = false; auto visitor = make_pass<Pass>(); for(auto& block : function->getBasicBlocks()){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline void operator()(Pass*){ bool local = false; { PerfsTimer timer(mtac::pass_traits<Pass>::name()); local = apply<Pass>(); } apply_todo<Pass>(); //TODO Do that, only if the pass is local if(log::enabled<Debug>()){ if(local){ log::emit<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function print(function); } else { log::emit<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } optimized |= local; } }; template<typename Passes> void optimize_program(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform){ pass_runner runner(program, pool, configuration, platform); do{ boost::mpl::for_each<Passes>(runner); } while(runner.optimized); } } //end of anonymous namespace void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { PerfsTimer timer("Whole optimizations"); //Allocate storage for the temporaries that need to be stored allocate_temporary(program, platform); if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations optimize_program<ipa_passes>(program, string_pool, configuration, platform); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) optimize_program<basic_passes>(program, string_pool, configuration, platform); } //Allocate storage for the temporaries that need to be stored allocate_temporary(program, platform); } <commit_msg>Improve debug<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include "boost_cfg.hpp" #include <boost/utility/enable_if.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "VisitorUtils.hpp" #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Printer.hpp" #include "mtac/TemporaryAllocator.hpp" //The custom optimizations #include "mtac/VariableOptimizations.hpp" #include "mtac/FunctionOptimizations.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/BasicBlockOptimizations.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/ConcatReduction.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_optimizations.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::optimize_concat*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(bool, need_pool, false); STATIC_CONSTANT(bool, need_platform, false); STATIC_CONSTANT(bool, need_configuration, false); STATIC_CONSTANT(unsigned int, todo_flags, 0); typedef passes sub_passes; }; } } namespace { //TODO Find a more elegant way than using pointers typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::inline_functions* > ipa_passes; struct pass_runner { bool optimized = false; std::shared_ptr<mtac::Program> program; std::shared_ptr<mtac::Function> function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; pass_runner(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform) : program(program), pool(pool), configuration(configuration), platform(platform) {}; template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::todo_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : function->getBasicBlocks()){ auto it = iterate(block->statements); while(it.has_next()){ if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){ it.erase(); continue; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){ if((*ptr)->op == mtac::Operator::NOP){ it.erase(); continue; } } ++it; } } } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::todo_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_pool, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_pool, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_platform, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_platform, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::need_configuration, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename boost::disable_if_c<mtac::pass_traits<Pass>::need_configuration, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> Pass make_pass(){ Pass pass; set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(){ auto pass = make_pass<Pass>(); return pass(program); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(){ bool optimized = false; auto& functions = program->functions; for(auto& function : functions){ this->function = function; if(log::enabled<Debug>()){ log::emit<Debug>("Optimizer") << "Start optimizations on " << function->getName() << log::endl; print(function); } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(*this); } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(){ auto pass = make_pass<Pass>(); return pass(function); } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(){ auto visitor = make_pass<Pass>(); mtac::visit_all_statements(visitor, function); return visitor.optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(){ bool optimized = false; auto problem = make_pass<Pass>(); auto results = mtac::data_flow(function, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(){ bool optimized = false; auto visitor = make_pass<Pass>(); for(auto& block : function->getBasicBlocks()){ visitor.clear(); visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename boost::enable_if_c<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(){ bool optimized = false; auto visitor = make_pass<Pass>(); for(auto& block : function->getBasicBlocks()){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename boost::enable_if_c<boost::type_traits::ice_or<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool){ //NOP } template<typename Pass> inline typename boost::enable_if_c<boost::type_traits::ice_and<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ if(log::enabled<Debug>()){ if(local){ log::emit<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function print(function); } else { log::emit<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } } template<typename Pass> inline void operator()(Pass*){ bool local = false; { PerfsTimer timer(mtac::pass_traits<Pass>::name()); local = apply<Pass>(); } apply_todo<Pass>(); debug_local<Pass>(local); optimized |= local; } }; template<typename Passes> void optimize_program(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform){ pass_runner runner(program, pool, configuration, platform); do{ boost::mpl::for_each<Passes>(runner); } while(runner.optimized); } } //end of anonymous namespace void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { PerfsTimer timer("Whole optimizations"); //Allocate storage for the temporaries that need to be stored allocate_temporary(program, platform); if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations optimize_program<ipa_passes>(program, string_pool, configuration, platform); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) optimize_program<basic_passes>(program, string_pool, configuration, platform); } //Allocate storage for the temporaries that need to be stored allocate_temporary(program, platform); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "ActiveForceComputeGPU.h" #include "ActiveForceComputeGPU.cuh" #include <vector> namespace py = pybind11; using namespace std; /*! \file ActiveForceComputeGPU.cc \brief Contains code for the ActiveForceComputeGPU class */ /*! \param f_list An array of (x,y,z) tuples for the active force vector for each individual particle. \param orientation_link if True then forces and torques are applied in the particle's reference frame. If false, then the box reference fra me is used. Only relevant for non-point-like anisotropic particles. /param orientation_reverse_link When True, the particle's orientation is set to match the active force vector. Useful for for using a particle's orientation to log the active force vector. Not recommended for anisotropic particles \param rotation_diff rotational diffusion constant for all particles. */ ActiveForceComputeGPU::ActiveForceComputeGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, Scalar rotation_diff, Scalar deltaT) : ActiveForceCompute(sysdef, group, rotation_diff, deltaT)(256) { if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a ActiveForceComputeGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing ActiveForceComputeGPU"); } // unsigned int N = m_pdata->getNGlobal(); // unsigned int group_size = m_group->getNumMembersGlobal(); unsigned int type = m_pdata->getNTypes(); GlobalVector<Scalar4> tmp_f_activeVec(type, m_exec_conf); GlobalVector<Scalar4> tmp_t_activeVec(type, m_exec_conf); { ArrayHandle<Scalar4> old_f_activeVec(m_f_activeVec, access_location::host); ArrayHandle<Scalar4> old_t_activeVec(m_t_activeVec, access_location::host); ArrayHandle<Scalar4> f_activeVec(tmp_f_activeVec, access_location::host); ArrayHandle<Scalar4> t_activeVec(tmp_t_activeVec, access_location::host); // for each type of the particles in the group for (unsigned int i = 0; i < type; i++) { f_activeVec.data[i] = old_f_activeVec.data[i]; t_activeVec.data[i] = old_t_activeVec.data[i]; } last_computed = 10; } m_f_activeVec.swap(tmp_f_activeVec); m_t_activeVec.swap(tmp_t_activeVec); } /*! This function sets appropriate active forces and torques on all active particles. */ void ActiveForceComputeGPU::setForces() { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_t_actVec(m_t_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_torque(m_torque, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); // sanity check assert(d_force.data != NULL); assert(d_f_actVec.data != NULL); assert(d_t_actVec.data != NULL); assert(d_pos.data != NULL); assert(d_orientation.data != NULL); assert(d_index_array.data != NULL); unsigned int group_size = m_group->getNumMembers(); unsigned int N = m_pdata->getN(); gpu_compute_active_force_set_forces(group_size, d_index_array.data, d_force.data, d_torque.data, d_pos.data, d_orientation.data, d_f_actVec.data, d_t_actVec.data, N, m_block_size); } /*! This function applies rotational diffusion to all active particles. The angle between the torque vector and * force vector does not change \param timestep Current timestep */ void ActiveForceComputeGPU::rotationalDiffusion(uint64_t timestep) { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::readwrite); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read); assert(d_pos.data != NULL); bool is2D = (m_sysdef->getNDimensions() == 2); unsigned int group_size = m_group->getNumMembers(); gpu_compute_active_force_rotational_diffusion(group_size, d_tag.data, d_index_array.data, d_pos.data, d_orientation.data, d_f_actVec.data, is2D, m_rotationConst, timestep, m_sysdef->getSeed(), m_block_size); } void export_ActiveForceComputeGPU(py::module& m) { py::class_<ActiveForceComputeGPU, ActiveForceCompute, std::shared_ptr<ActiveForceComputeGPU>>( m, "ActiveForceComputeGPU") .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, Scalar, Scalar>()); } <commit_msg>fix initiatisation in ActiveForceComputeGPU.cc<commit_after>// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "ActiveForceComputeGPU.h" #include "ActiveForceComputeGPU.cuh" #include <vector> namespace py = pybind11; using namespace std; /*! \file ActiveForceComputeGPU.cc \brief Contains code for the ActiveForceComputeGPU class */ /*! \param f_list An array of (x,y,z) tuples for the active force vector for each individual particle. \param orientation_link if True then forces and torques are applied in the particle's reference frame. If false, then the box reference fra me is used. Only relevant for non-point-like anisotropic particles. /param orientation_reverse_link When True, the particle's orientation is set to match the active force vector. Useful for for using a particle's orientation to log the active force vector. Not recommended for anisotropic particles \param rotation_diff rotational diffusion constant for all particles. */ ActiveForceComputeGPU::ActiveForceComputeGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, Scalar rotation_diff, Scalar deltaT) : ActiveForceCompute(sysdef, group, rotation_diff, deltaT), m_block_size(256) { if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a ActiveForceComputeGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing ActiveForceComputeGPU"); } // unsigned int N = m_pdata->getNGlobal(); // unsigned int group_size = m_group->getNumMembersGlobal(); unsigned int type = m_pdata->getNTypes(); GlobalVector<Scalar4> tmp_f_activeVec(type, m_exec_conf); GlobalVector<Scalar4> tmp_t_activeVec(type, m_exec_conf); { ArrayHandle<Scalar4> old_f_activeVec(m_f_activeVec, access_location::host); ArrayHandle<Scalar4> old_t_activeVec(m_t_activeVec, access_location::host); ArrayHandle<Scalar4> f_activeVec(tmp_f_activeVec, access_location::host); ArrayHandle<Scalar4> t_activeVec(tmp_t_activeVec, access_location::host); // for each type of the particles in the group for (unsigned int i = 0; i < type; i++) { f_activeVec.data[i] = old_f_activeVec.data[i]; t_activeVec.data[i] = old_t_activeVec.data[i]; } last_computed = 10; } m_f_activeVec.swap(tmp_f_activeVec); m_t_activeVec.swap(tmp_t_activeVec); } /*! This function sets appropriate active forces and torques on all active particles. */ void ActiveForceComputeGPU::setForces() { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_t_actVec(m_t_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_torque(m_torque, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); // sanity check assert(d_force.data != NULL); assert(d_f_actVec.data != NULL); assert(d_t_actVec.data != NULL); assert(d_pos.data != NULL); assert(d_orientation.data != NULL); assert(d_index_array.data != NULL); unsigned int group_size = m_group->getNumMembers(); unsigned int N = m_pdata->getN(); gpu_compute_active_force_set_forces(group_size, d_index_array.data, d_force.data, d_torque.data, d_pos.data, d_orientation.data, d_f_actVec.data, d_t_actVec.data, N, m_block_size); } /*! This function applies rotational diffusion to all active particles. The angle between the torque vector and * force vector does not change \param timestep Current timestep */ void ActiveForceComputeGPU::rotationalDiffusion(uint64_t timestep) { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::readwrite); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read); assert(d_pos.data != NULL); bool is2D = (m_sysdef->getNDimensions() == 2); unsigned int group_size = m_group->getNumMembers(); gpu_compute_active_force_rotational_diffusion(group_size, d_tag.data, d_index_array.data, d_pos.data, d_orientation.data, d_f_actVec.data, is2D, m_rotationConst, timestep, m_sysdef->getSeed(), m_block_size); } void export_ActiveForceComputeGPU(py::module& m) { py::class_<ActiveForceComputeGPU, ActiveForceCompute, std::shared_ptr<ActiveForceComputeGPU>>( m, "ActiveForceComputeGPU") .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, Scalar, Scalar>()); } <|endoftext|>
<commit_before>#include "command.hh" #include "store-api.hh" #include "progress-bar.hh" #include "fs-accessor.hh" #include "shared.hh" #include <queue> using namespace nix; static std::string hilite(const std::string & s, size_t pos, size_t len, const std::string & colour = ANSI_RED) { return std::string(s, 0, pos) + colour + std::string(s, pos, len) + ANSI_NORMAL + std::string(s, pos + len); } static std::string filterPrintable(const std::string & s) { std::string res; for (char c : s) res += isprint(c) ? c : '.'; return res; } struct CmdWhyDepends : SourceExprCommand { std::string _package, _dependency; bool all = false; bool precise = false; CmdWhyDepends() { expectArgs({ .label = "package", .handler = {&_package}, .completer = {[&](size_t, std::string_view prefix) { completeInstallable(prefix); }} }); expectArgs({ .label = "dependency", .handler = {&_dependency}, .completer = {[&](size_t, std::string_view prefix) { completeInstallable(prefix); }} }); addFlag({ .longName = "all", .shortName = 'a', .description = "Show all edges in the dependency graph leading from *package* to *dependency*, rather than just a shortest path.", .handler = {&all, true}, }); addFlag({ .longName = "precise", .description = "For each edge in the dependency graph, show the files in the parent that cause the dependency.", .handler = {&precise, true}, }); } std::string description() override { return "show why a package has another package in its closure"; } std::string doc() override { return #include "why-depends.md" ; } Category category() override { return catSecondary; } void run(ref<Store> store) override { auto package = parseInstallable(store, _package); auto packagePath = Installable::toStorePath(getEvalStore(), store, Realise::Outputs, operateOn, package); auto dependency = parseInstallable(store, _dependency); auto dependencyPath = Installable::toStorePath(getEvalStore(), store, Realise::Derivation, operateOn, dependency); auto dependencyPathHash = dependencyPath.hashPart(); StorePathSet closure; store->computeFSClosure({packagePath}, closure, false, false); if (!closure.count(dependencyPath)) { printError("'%s' does not depend on '%s'", store->printStorePath(packagePath), store->printStorePath(dependencyPath)); return; } stopProgressBar(); // FIXME auto accessor = store->getFSAccessor(); auto const inf = std::numeric_limits<size_t>::max(); struct Node { StorePath path; StorePathSet refs; StorePathSet rrefs; size_t dist = inf; Node * prev = nullptr; bool queued = false; bool visited = false; }; std::map<StorePath, Node> graph; for (auto & path : closure) graph.emplace(path, Node { .path = path, .refs = store->queryPathInfo(path)->references, .dist = path == dependencyPath ? 0 : inf }); // Transpose the graph. for (auto & node : graph) for (auto & ref : node.second.refs) graph.find(ref)->second.rrefs.insert(node.first); /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */ std::priority_queue<Node *> queue; queue.push(&graph.at(dependencyPath)); while (!queue.empty()) { auto & node = *queue.top(); queue.pop(); for (auto & rref : node.rrefs) { auto & node2 = graph.at(rref); auto dist = node.dist + 1; if (dist < node2.dist) { node2.dist = dist; node2.prev = &node; if (!node2.queued) { node2.queued = true; queue.push(&node2); } } } } /* Print the subgraph of nodes that have 'dependency' in their closure (i.e., that have a non-infinite distance to 'dependency'). Print every edge on a path between `package` and `dependency`. */ std::function<void(Node &, const std::string &, const std::string &)> printNode; struct BailOut { }; printNode = [&](Node & node, const std::string & firstPad, const std::string & tailPad) { auto pathS = store->printStorePath(node.path); assert(node.dist != inf); if (precise) { logger->cout("%s%s%s%s" ANSI_NORMAL, firstPad, node.visited ? "\e[38;5;244m" : "", firstPad != "" ? "→ " : "", pathS); } if (node.path == dependencyPath && !all && packagePath != dependencyPath) throw BailOut(); if (node.visited) return; if (precise) node.visited = true; /* Sort the references by distance to `dependency` to ensure that the shortest path is printed first. */ std::multimap<size_t, Node *> refs; std::set<std::string> hashes; for (auto & ref : node.refs) { if (ref == node.path && packagePath != dependencyPath) continue; auto & node2 = graph.at(ref); if (node2.dist == inf) continue; refs.emplace(node2.dist, &node2); hashes.insert(std::string(node2.path.hashPart())); } /* For each reference, find the files and symlinks that contain the reference. */ std::map<std::string, Strings> hits; std::function<void(const Path &)> visitPath; visitPath = [&](const Path & p) { auto st = accessor->stat(p); auto p2 = p == pathS ? "/" : std::string(p, pathS.size() + 1); auto getColour = [&](const std::string & hash) { return hash == dependencyPathHash ? ANSI_GREEN : ANSI_BLUE; }; if (st.type == FSAccessor::Type::tDirectory) { auto names = accessor->readDirectory(p); for (auto & name : names) visitPath(p + "/" + name); } else if (st.type == FSAccessor::Type::tRegular) { auto contents = accessor->readFile(p); for (auto & hash : hashes) { auto pos = contents.find(hash); if (pos != std::string::npos) { size_t margin = 32; auto pos2 = pos >= margin ? pos - margin : 0; hits[hash].emplace_back(fmt("%s: …%s…\n", p2, hilite(filterPrintable( std::string(contents, pos2, pos - pos2 + hash.size() + margin)), pos - pos2, StorePath::HashLen, getColour(hash)))); } } } else if (st.type == FSAccessor::Type::tSymlink) { auto target = accessor->readLink(p); for (auto & hash : hashes) { auto pos = target.find(hash); if (pos != std::string::npos) hits[hash].emplace_back(fmt("%s -> %s\n", p2, hilite(target, pos, StorePath::HashLen, getColour(hash)))); } } }; // FIXME: should use scanForReferences(). if (precise) visitPath(pathS); for (auto & ref : refs) { std::string hash(ref.second->path.hashPart()); bool last = all ? ref == *refs.rbegin() : true; for (auto & hit : hits[hash]) { bool first = hit == *hits[hash].begin(); std::cout << tailPad << (first ? (last ? treeLast : treeConn) : (last ? treeNull : treeLine)) << hit; if (!all) break; } if (!precise) { auto pathS = store->printStorePath(ref.second->path); logger->cout("%s%s%s%s" ANSI_NORMAL, firstPad, ref.second->visited ? "\e[38;5;244m" : "", last ? treeLast : treeConn, pathS); node.visited = true; } printNode(*ref.second, tailPad + (last ? treeNull : treeLine), tailPad + (last ? treeNull : treeLine)); } }; RunPager pager; try { if (!precise) { logger->cout("%s", store->printStorePath(graph.at(packagePath).path)); } printNode(graph.at(packagePath), "", ""); } catch (BailOut & ) { } } }; static auto rCmdWhyDepends = registerCommand<CmdWhyDepends>("why-depends"); <commit_msg>Fix why-depends for CA derivations<commit_after>#include "command.hh" #include "store-api.hh" #include "progress-bar.hh" #include "fs-accessor.hh" #include "shared.hh" #include <queue> using namespace nix; static std::string hilite(const std::string & s, size_t pos, size_t len, const std::string & colour = ANSI_RED) { return std::string(s, 0, pos) + colour + std::string(s, pos, len) + ANSI_NORMAL + std::string(s, pos + len); } static std::string filterPrintable(const std::string & s) { std::string res; for (char c : s) res += isprint(c) ? c : '.'; return res; } struct CmdWhyDepends : SourceExprCommand { std::string _package, _dependency; bool all = false; bool precise = false; CmdWhyDepends() { expectArgs({ .label = "package", .handler = {&_package}, .completer = {[&](size_t, std::string_view prefix) { completeInstallable(prefix); }} }); expectArgs({ .label = "dependency", .handler = {&_dependency}, .completer = {[&](size_t, std::string_view prefix) { completeInstallable(prefix); }} }); addFlag({ .longName = "all", .shortName = 'a', .description = "Show all edges in the dependency graph leading from *package* to *dependency*, rather than just a shortest path.", .handler = {&all, true}, }); addFlag({ .longName = "precise", .description = "For each edge in the dependency graph, show the files in the parent that cause the dependency.", .handler = {&precise, true}, }); } std::string description() override { return "show why a package has another package in its closure"; } std::string doc() override { return #include "why-depends.md" ; } Category category() override { return catSecondary; } void run(ref<Store> store) override { auto package = parseInstallable(store, _package); auto packagePath = Installable::toStorePath(getEvalStore(), store, Realise::Outputs, operateOn, package); auto dependency = parseInstallable(store, _dependency); auto derivedDependency = dependency->toDerivedPath(); auto optDependencyPath = std::visit(overloaded { [](const DerivedPath::Opaque & nodrv) -> std::optional<StorePath> { return { nodrv.path }; }, [&](const DerivedPath::Built & hasdrv) -> std::optional<StorePath> { if (hasdrv.outputs.size() != 1) { throw Error("argument '%s' should evaluate to one store path", dependency->what()); } auto outputMap = store->queryPartialDerivationOutputMap(hasdrv.drvPath); auto maybePath = outputMap.find(*hasdrv.outputs.begin()); if (maybePath == outputMap.end()) { throw Error("unexpected end of iterator"); } return maybePath->second; }, }, derivedDependency.raw()); StorePathSet closure; store->computeFSClosure({packagePath}, closure, false, false); if (!optDependencyPath.has_value() || !closure.count(*optDependencyPath)) { printError("'%s' does not depend on '%s'", package->what(), dependency->what()); return; } auto dependencyPath = *optDependencyPath; auto dependencyPathHash = dependencyPath.hashPart(); stopProgressBar(); // FIXME auto accessor = store->getFSAccessor(); auto const inf = std::numeric_limits<size_t>::max(); struct Node { StorePath path; StorePathSet refs; StorePathSet rrefs; size_t dist = inf; Node * prev = nullptr; bool queued = false; bool visited = false; }; std::map<StorePath, Node> graph; for (auto & path : closure) graph.emplace(path, Node { .path = path, .refs = store->queryPathInfo(path)->references, .dist = path == dependencyPath ? 0 : inf }); // Transpose the graph. for (auto & node : graph) for (auto & ref : node.second.refs) graph.find(ref)->second.rrefs.insert(node.first); /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */ std::priority_queue<Node *> queue; queue.push(&graph.at(dependencyPath)); while (!queue.empty()) { auto & node = *queue.top(); queue.pop(); for (auto & rref : node.rrefs) { auto & node2 = graph.at(rref); auto dist = node.dist + 1; if (dist < node2.dist) { node2.dist = dist; node2.prev = &node; if (!node2.queued) { node2.queued = true; queue.push(&node2); } } } } /* Print the subgraph of nodes that have 'dependency' in their closure (i.e., that have a non-infinite distance to 'dependency'). Print every edge on a path between `package` and `dependency`. */ std::function<void(Node &, const std::string &, const std::string &)> printNode; struct BailOut { }; printNode = [&](Node & node, const std::string & firstPad, const std::string & tailPad) { auto pathS = store->printStorePath(node.path); assert(node.dist != inf); if (precise) { logger->cout("%s%s%s%s" ANSI_NORMAL, firstPad, node.visited ? "\e[38;5;244m" : "", firstPad != "" ? "→ " : "", pathS); } if (node.path == dependencyPath && !all && packagePath != dependencyPath) throw BailOut(); if (node.visited) return; if (precise) node.visited = true; /* Sort the references by distance to `dependency` to ensure that the shortest path is printed first. */ std::multimap<size_t, Node *> refs; std::set<std::string> hashes; for (auto & ref : node.refs) { if (ref == node.path && packagePath != dependencyPath) continue; auto & node2 = graph.at(ref); if (node2.dist == inf) continue; refs.emplace(node2.dist, &node2); hashes.insert(std::string(node2.path.hashPart())); } /* For each reference, find the files and symlinks that contain the reference. */ std::map<std::string, Strings> hits; std::function<void(const Path &)> visitPath; visitPath = [&](const Path & p) { auto st = accessor->stat(p); auto p2 = p == pathS ? "/" : std::string(p, pathS.size() + 1); auto getColour = [&](const std::string & hash) { return hash == dependencyPathHash ? ANSI_GREEN : ANSI_BLUE; }; if (st.type == FSAccessor::Type::tDirectory) { auto names = accessor->readDirectory(p); for (auto & name : names) visitPath(p + "/" + name); } else if (st.type == FSAccessor::Type::tRegular) { auto contents = accessor->readFile(p); for (auto & hash : hashes) { auto pos = contents.find(hash); if (pos != std::string::npos) { size_t margin = 32; auto pos2 = pos >= margin ? pos - margin : 0; hits[hash].emplace_back(fmt("%s: …%s…\n", p2, hilite(filterPrintable( std::string(contents, pos2, pos - pos2 + hash.size() + margin)), pos - pos2, StorePath::HashLen, getColour(hash)))); } } } else if (st.type == FSAccessor::Type::tSymlink) { auto target = accessor->readLink(p); for (auto & hash : hashes) { auto pos = target.find(hash); if (pos != std::string::npos) hits[hash].emplace_back(fmt("%s -> %s\n", p2, hilite(target, pos, StorePath::HashLen, getColour(hash)))); } } }; // FIXME: should use scanForReferences(). if (precise) visitPath(pathS); for (auto & ref : refs) { std::string hash(ref.second->path.hashPart()); bool last = all ? ref == *refs.rbegin() : true; for (auto & hit : hits[hash]) { bool first = hit == *hits[hash].begin(); std::cout << tailPad << (first ? (last ? treeLast : treeConn) : (last ? treeNull : treeLine)) << hit; if (!all) break; } if (!precise) { auto pathS = store->printStorePath(ref.second->path); logger->cout("%s%s%s%s" ANSI_NORMAL, firstPad, ref.second->visited ? "\e[38;5;244m" : "", last ? treeLast : treeConn, pathS); node.visited = true; } printNode(*ref.second, tailPad + (last ? treeNull : treeLine), tailPad + (last ? treeNull : treeLine)); } }; RunPager pager; try { if (!precise) { logger->cout("%s", store->printStorePath(graph.at(packagePath).path)); } printNode(graph.at(packagePath), "", ""); } catch (BailOut & ) { } } }; static auto rCmdWhyDepends = registerCommand<CmdWhyDepends>("why-depends"); <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * 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. * * \file IfImpl.cxx * * Implementation details for the asynchronous NMRAnet interfaces. This file * should only be needed in hardware interface implementations. * * @author Balazs Racz * @date 4 Dec 2013 */ #include "nmranet/IfImpl.hxx" namespace nmranet { StateFlowBase::Action WriteFlowBase::addressed_entry() { if (nmsg()->dst.id) { nmsg()->dstNode = async_if()->lookup_local_node(nmsg()->dst.id); if (nmsg()->dstNode) { async_if()->dispatcher()->send(transfer_message(), priority()); return call_immediately(STATE(send_finished)); } } return send_to_hardware(); } StateFlowBase::Action WriteFlowBase::global_entry() { if (!message()->data()->has_flag_dst( NMRAnetMessage::WAIT_FOR_LOCAL_LOOPBACK)) { // We do not pass on the done notifiable with the loopbacked message. BarrierNotifiable *d = message()->new_child(); if (d) { // This is abuse of the barriernotifiable code, because we assume // that notifying the child twice will cause the parent to be // notified once. d->notify(); d->notify(); message()->set_done(nullptr); } } async_if()->dispatcher()->send(transfer_message()); return release_and_exit(); } #if 0 ///@todo(balazs.racz) move this code to its final location when it is ready. /** Send an ident info reply message. * @param dst destination Node ID to respond to */ void Node::ident_info_reply(NodeHandle dst) { /* macro for condensing the size calculation code */ #define ADD_STRING_SIZE(_str, _max) \ { \ if ((_str)) \ { \ size_t len = strlen((_str)); \ size += len > (_max) ? (_max) : len; \ } \ } /* macro for condensing the string insertion code */ #define INSERT_STRING(_str, _max) \ { \ if ((_str)) \ { \ size_t len = strlen((_str)); \ len = len > (_max) ? (_max) : len; \ memcpy(pos, (_str), len); \ pos[len] = '\0'; \ pos += len + 1; \ } \ else \ { \ pos[0] = '\0'; \ pos++; \ } \ } /* we make this static so that it does not use up stack */ /** @todo (Stuart Baker) if this could ever be accessed from more than one * thread, we will need a lock */ static char ident[8+40+40+20+20+62+63]; char *pos = ident; size_t size = 8; ADD_STRING_SIZE(MANUFACTURER, 40); ADD_STRING_SIZE(model, 40); ADD_STRING_SIZE(HARDWARE_REV, 20); ADD_STRING_SIZE(SOFTWARE_REV, 20); ADD_STRING_SIZE(userName, 62); ADD_STRING_SIZE(userDescription, 63); pos[0] = SIMPLE_NODE_IDENT_VERSION_A; pos++; INSERT_STRING(MANUFACTURER, 40); INSERT_STRING(model, 40); INSERT_STRING(HARDWARE_REV, 20); INSERT_STRING(SOFTWARE_REV, 20); pos[0] = SIMPLE_NODE_IDENT_VERSION_B; pos++; INSERT_STRING(userName, 62); INSERT_STRING(userDescription, 63); for (int index = 0; size; ) { size_t segment_size = size > 6 ? 6 : size; Buffer *buffer = buffer_alloc(6); memcpy(buffer->start(), ident + index, segment_size); buffer->advance(segment_size); write(Defs::MTI_IDENT_INFO_REPLY, dst, buffer); size -= segment_size; index += segment_size; } } /** Send an protocols supported reply message. * @param dst destination Node ID to respond to */ void Node::protocol_support_reply(NodeHandle dst) { /** @todo (Stuart Baker) this needs to be updated as additional protocols * are supported */ uint64_t protocols = PROTOCOL_IDENTIFICATION | DATAGRAM | EVENT_EXCHANGE | SIMPLE_NODE_INFORMATION | MEMORY_CONFIGURATION | CDI; Buffer *buffer = buffer_alloc(6); uint8_t *bytes = (uint8_t*)buffer->start(); bytes[0] = (protocols >> 40) & 0xff; bytes[1] = (protocols >> 32) & 0xff; bytes[2] = (protocols >> 24) & 0xff; bytes[3] = (protocols >> 16) & 0xff; bytes[4] = (protocols >> 8) & 0xff; bytes[5] = (protocols >> 0) & 0xff; buffer->advance(6); write(Defs::MTI_PROTOCOL_SUPPORT_REPLY, dst, buffer); } #endif // if 0 } // namespace nmranet <commit_msg>Recalculates NMRAnet priority of loopback messages.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * 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. * * \file IfImpl.cxx * * Implementation details for the asynchronous NMRAnet interfaces. This file * should only be needed in hardware interface implementations. * * @author Balazs Racz * @date 4 Dec 2013 */ #include "nmranet/IfImpl.hxx" namespace nmranet { StateFlowBase::Action WriteFlowBase::addressed_entry() { if (nmsg()->dst.id) { nmsg()->dstNode = async_if()->lookup_local_node(nmsg()->dst.id); if (nmsg()->dstNode) { unsigned prio = priority(); if (prio >= (1 << 16)) { prio = message()->data()->priority(); } async_if()->dispatcher()->send(transfer_message(), prio); return call_immediately(STATE(send_finished)); } } return send_to_hardware(); } StateFlowBase::Action WriteFlowBase::global_entry() { if (!message()->data()->has_flag_dst( NMRAnetMessage::WAIT_FOR_LOCAL_LOOPBACK)) { // We do not pass on the done notifiable with the loopbacked message. BarrierNotifiable *d = message()->new_child(); if (d) { // This is abuse of the barriernotifiable code, because we assume // that notifying the child twice will cause the parent to be // notified once. d->notify(); d->notify(); message()->set_done(nullptr); } } unsigned loopback_prio = message()->data()->priority(); async_if()->dispatcher()->send(transfer_message(), loopback_prio); return release_and_exit(); } #if 0 ///@todo(balazs.racz) move this code to its final location when it is ready. /** Send an ident info reply message. * @param dst destination Node ID to respond to */ void Node::ident_info_reply(NodeHandle dst) { /* macro for condensing the size calculation code */ #define ADD_STRING_SIZE(_str, _max) \ { \ if ((_str)) \ { \ size_t len = strlen((_str)); \ size += len > (_max) ? (_max) : len; \ } \ } /* macro for condensing the string insertion code */ #define INSERT_STRING(_str, _max) \ { \ if ((_str)) \ { \ size_t len = strlen((_str)); \ len = len > (_max) ? (_max) : len; \ memcpy(pos, (_str), len); \ pos[len] = '\0'; \ pos += len + 1; \ } \ else \ { \ pos[0] = '\0'; \ pos++; \ } \ } /* we make this static so that it does not use up stack */ /** @todo (Stuart Baker) if this could ever be accessed from more than one * thread, we will need a lock */ static char ident[8+40+40+20+20+62+63]; char *pos = ident; size_t size = 8; ADD_STRING_SIZE(MANUFACTURER, 40); ADD_STRING_SIZE(model, 40); ADD_STRING_SIZE(HARDWARE_REV, 20); ADD_STRING_SIZE(SOFTWARE_REV, 20); ADD_STRING_SIZE(userName, 62); ADD_STRING_SIZE(userDescription, 63); pos[0] = SIMPLE_NODE_IDENT_VERSION_A; pos++; INSERT_STRING(MANUFACTURER, 40); INSERT_STRING(model, 40); INSERT_STRING(HARDWARE_REV, 20); INSERT_STRING(SOFTWARE_REV, 20); pos[0] = SIMPLE_NODE_IDENT_VERSION_B; pos++; INSERT_STRING(userName, 62); INSERT_STRING(userDescription, 63); for (int index = 0; size; ) { size_t segment_size = size > 6 ? 6 : size; Buffer *buffer = buffer_alloc(6); memcpy(buffer->start(), ident + index, segment_size); buffer->advance(segment_size); write(Defs::MTI_IDENT_INFO_REPLY, dst, buffer); size -= segment_size; index += segment_size; } } /** Send an protocols supported reply message. * @param dst destination Node ID to respond to */ void Node::protocol_support_reply(NodeHandle dst) { /** @todo (Stuart Baker) this needs to be updated as additional protocols * are supported */ uint64_t protocols = PROTOCOL_IDENTIFICATION | DATAGRAM | EVENT_EXCHANGE | SIMPLE_NODE_INFORMATION | MEMORY_CONFIGURATION | CDI; Buffer *buffer = buffer_alloc(6); uint8_t *bytes = (uint8_t*)buffer->start(); bytes[0] = (protocols >> 40) & 0xff; bytes[1] = (protocols >> 32) & 0xff; bytes[2] = (protocols >> 24) & 0xff; bytes[3] = (protocols >> 16) & 0xff; bytes[4] = (protocols >> 8) & 0xff; bytes[5] = (protocols >> 0) & 0xff; buffer->advance(6); write(Defs::MTI_PROTOCOL_SUPPORT_REPLY, dst, buffer); } #endif // if 0 } // namespace nmranet <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * GdkPixbuf modification code from Walmis * <http://gnome-look.org/content/show.php?content=77783&forumpage=3> * * 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., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygengtkutils.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <iostream> namespace Gtk { //________________________________________________________ bool gtk_widget_has_rgba( GtkWidget* widget ) { if( !widget ) return false; GdkScreen *screen( gtk_widget_get_screen (widget) ); if( gdk_screen_is_composited( screen ) ) { GdkVisual *visual = gtk_widget_get_visual (widget); return visual->depth == 32 && visual->red_mask == 0xff0000 && visual->green_mask == 0x00ff00 && visual->blue_mask == 0x0000ff; } else return false; } //________________________________________________________ GtkWidget* gtk_parent_button( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_BUTTON( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_menu( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_MENU( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_treeview( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_TREE_VIEW( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_combobox( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_COMBO_BOX( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_combobox_entry( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_COMBO_BOX_ENTRY( parent ) ) return parent; } return 0L; } //________________________________________________________ bool gtk_button_is_flat( GtkWidget* widget ) { if( !GTK_IS_BUTTON( widget ) ) return false; GObject* object( G_OBJECT( widget ) ); if( gtk_object_is_a( object, "ccm+Utils+PrettyButton" ) ) return true; GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_TOOLBAR( parent ) || gtk_object_is_a( G_OBJECT( parent ), "GimpToolbox" ) ) { return true; } } return false; } //________________________________________________________ bool gtk_object_is_a( const GObject* object, const gchar * type_name ) { if( object ) { const GType tmp( g_type_from_name( type_name ) ); if( tmp ) { return g_type_check_instance_is_a( (GTypeInstance*) object, tmp ); } } return false; } //________________________________________________________ bool gtk_progress_bar_is_horizontal( GtkWidget* widget ) { if( !GTK_IS_PROGRESS_BAR( widget ) ) return true; switch( gtk_progress_bar_get_orientation( GTK_PROGRESS_BAR( widget ) ) ) { default: case GTK_PROGRESS_LEFT_TO_RIGHT: case GTK_PROGRESS_RIGHT_TO_LEFT: return true; case GTK_PROGRESS_BOTTOM_TO_TOP: case GTK_PROGRESS_TOP_TO_BOTTOM: return false; } } //________________________________________________________ bool gdk_map_to_toplevel( GdkWindow* window, GtkWidget* widget, gint* x, gint* y, gint* w, gint* h, bool frame ) { // always initialize arguments (to invalid values) if( x ) *x=0; if( y ) *y=0; if( w ) *w = -1; if( h ) *h = -1; if( !( window && GDK_IS_WINDOW( window ) ) ) { if( !widget ) return false; // this is an alternative way to get widget position with respect to top level window // and top level window size. This is used in case the GdkWindow passed as argument is // actually a 'non window' drawable window = gtk_widget_get_parent_window( widget ); if( frame ) gdk_toplevel_get_frame_size( window, w, h ); else gdk_toplevel_get_size( window, w, h ); int xlocal, ylocal; const bool success( gtk_widget_translate_coordinates( widget, gtk_widget_get_toplevel( widget ), 0, 0, &xlocal, &ylocal ) ); if( success ) { if( x ) *x=xlocal; if( y ) *y=ylocal; } return success && ((!w) || *w > 0) && ((!h) || *h>0); } else { // get window size and height if( frame ) gdk_toplevel_get_frame_size( window, w, h ); else gdk_toplevel_get_size( window, w, h ); Gtk::gdk_window_get_toplevel_origin( window, x, y ); return ((!w) || *w > 0) && ((!h) || *h>0); } } //________________________________________________________ void gdk_toplevel_get_size( GdkWindow* window, gint* w, gint* h ) { if( !( window && GDK_IS_WINDOW( window ) ) ) { if( w ) *w = -1; if( h ) *h = -1; return; } if( GdkWindow* topLevel = gdk_window_get_toplevel( window ) ) { gdk_drawable_get_size( topLevel, w, h ); } else gdk_drawable_get_size( window, w, h ); return; } //________________________________________________________ void gdk_toplevel_get_frame_size( GdkWindow* window, gint* w, gint* h ) { if( !( window && GDK_IS_WINDOW( window ) ) ) { if( w ) *w = -1; if( h ) *h = -1; return; } if( GdkWindow* topLevel = gdk_window_get_toplevel( window ) ) { GdkRectangle rect = {0, 0, -1, -1}; gdk_window_get_frame_extents( topLevel, &rect ); if( w ) *w = rect.width; if( h ) *h = rect.height; } return; } //________________________________________________________ void gdk_window_get_toplevel_origin( GdkWindow* window, gint* x, gint* y ) { if( x ) *x = 0; if( y ) *y = 0; if( !window ) return; while( window && GDK_IS_WINDOW( window ) && gdk_window_get_window_type( window ) != GDK_WINDOW_TOPLEVEL && gdk_window_get_window_type( window ) != GDK_WINDOW_TEMP ) { gint xloc; gint yloc; gdk_window_get_position( window, &xloc, &yloc ); if( x ) *x += xloc; if( y ) *y += yloc; window = gdk_window_get_parent( window ); } return; } //___________________________________________________________ GdkPixbuf* gdk_pixbuf_set_alpha( const GdkPixbuf *pixbuf, double alpha ) { g_return_val_if_fail( pixbuf != 0L, 0L); g_return_val_if_fail( GDK_IS_PIXBUF( pixbuf ), 0L ); /* Returns a copy of pixbuf with it's non-completely-transparent pixels to have an alpha level "alpha" of their original value. */ GdkPixbuf* target( gdk_pixbuf_add_alpha( pixbuf, false, 0, 0, 0 ) ); if( alpha >= 1.0 ) return target; if( alpha < 0 ) alpha = 0; const int width( gdk_pixbuf_get_width( target ) ); const int height( gdk_pixbuf_get_height( target ) ); const int rowstride( gdk_pixbuf_get_rowstride( target ) ); unsigned char* data = gdk_pixbuf_get_pixels( target ); for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { /* The "4" is the number of chars per pixel, in this case, RGBA, the 3 means "skip to the alpha" */ unsigned char* current = data + ( y*rowstride ) + ( x*4 ) + 3; *(current) = (unsigned char) ( *( current )*alpha ); } } return target; } //___________________________________________________________ GdkPixbuf* gdk_pixbuf_resize( GdkPixbuf* src, int width, int height ) { if( width == gdk_pixbuf_get_width( src ) && height == gdk_pixbuf_get_height( src ) ) { return static_cast<GdkPixbuf*>(g_object_ref (src)); } else { return gdk_pixbuf_scale_simple( src, width, height, GDK_INTERP_BILINEAR ); } } } <commit_msg>Removed gimp special handling of flat buttons because it does not work (due to stupid implementation on gimp side)<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * * GdkPixbuf modification code from Walmis * <http://gnome-look.org/content/show.php?content=77783&forumpage=3> * * 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., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygengtkutils.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <iostream> namespace Gtk { //________________________________________________________ bool gtk_widget_has_rgba( GtkWidget* widget ) { if( !widget ) return false; GdkScreen *screen( gtk_widget_get_screen (widget) ); if( gdk_screen_is_composited( screen ) ) { GdkVisual *visual = gtk_widget_get_visual (widget); return visual->depth == 32 && visual->red_mask == 0xff0000 && visual->green_mask == 0x00ff00 && visual->blue_mask == 0x0000ff; } else return false; } //________________________________________________________ GtkWidget* gtk_parent_button( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_BUTTON( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_menu( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_MENU( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_treeview( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_TREE_VIEW( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_combobox( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_COMBO_BOX( parent ) ) return parent; } return 0L; } //________________________________________________________ GtkWidget* gtk_parent_combobox_entry( GtkWidget* widget ) { GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_COMBO_BOX_ENTRY( parent ) ) return parent; } return 0L; } //________________________________________________________ bool gtk_button_is_flat( GtkWidget* widget ) { if( !GTK_IS_BUTTON( widget ) ) return false; if( GTK_IS_COMBO_BOX( widget ) ) return false; GObject* object( G_OBJECT( widget ) ); if( gtk_object_is_a( object, "ccm+Utils+PrettyButton" ) ) return true; GtkWidget *parent( widget ); while( parent && (parent = gtk_widget_get_parent( parent ) ) ) { if( GTK_IS_TOOLBAR( parent ) ) return true; } return false; } //________________________________________________________ bool gtk_object_is_a( const GObject* object, const gchar * type_name ) { if( object ) { const GType tmp( g_type_from_name( type_name ) ); if( tmp ) { return g_type_check_instance_is_a( (GTypeInstance*) object, tmp ); } } return false; } //________________________________________________________ bool gtk_progress_bar_is_horizontal( GtkWidget* widget ) { if( !GTK_IS_PROGRESS_BAR( widget ) ) return true; switch( gtk_progress_bar_get_orientation( GTK_PROGRESS_BAR( widget ) ) ) { default: case GTK_PROGRESS_LEFT_TO_RIGHT: case GTK_PROGRESS_RIGHT_TO_LEFT: return true; case GTK_PROGRESS_BOTTOM_TO_TOP: case GTK_PROGRESS_TOP_TO_BOTTOM: return false; } } //________________________________________________________ bool gdk_map_to_toplevel( GdkWindow* window, GtkWidget* widget, gint* x, gint* y, gint* w, gint* h, bool frame ) { // always initialize arguments (to invalid values) if( x ) *x=0; if( y ) *y=0; if( w ) *w = -1; if( h ) *h = -1; if( !( window && GDK_IS_WINDOW( window ) ) ) { if( !widget ) return false; // this is an alternative way to get widget position with respect to top level window // and top level window size. This is used in case the GdkWindow passed as argument is // actually a 'non window' drawable window = gtk_widget_get_parent_window( widget ); if( frame ) gdk_toplevel_get_frame_size( window, w, h ); else gdk_toplevel_get_size( window, w, h ); int xlocal, ylocal; const bool success( gtk_widget_translate_coordinates( widget, gtk_widget_get_toplevel( widget ), 0, 0, &xlocal, &ylocal ) ); if( success ) { if( x ) *x=xlocal; if( y ) *y=ylocal; } return success && ((!w) || *w > 0) && ((!h) || *h>0); } else { // get window size and height if( frame ) gdk_toplevel_get_frame_size( window, w, h ); else gdk_toplevel_get_size( window, w, h ); Gtk::gdk_window_get_toplevel_origin( window, x, y ); return ((!w) || *w > 0) && ((!h) || *h>0); } } //________________________________________________________ void gdk_toplevel_get_size( GdkWindow* window, gint* w, gint* h ) { if( !( window && GDK_IS_WINDOW( window ) ) ) { if( w ) *w = -1; if( h ) *h = -1; return; } if( GdkWindow* topLevel = gdk_window_get_toplevel( window ) ) { gdk_drawable_get_size( topLevel, w, h ); } else gdk_drawable_get_size( window, w, h ); return; } //________________________________________________________ void gdk_toplevel_get_frame_size( GdkWindow* window, gint* w, gint* h ) { if( !( window && GDK_IS_WINDOW( window ) ) ) { if( w ) *w = -1; if( h ) *h = -1; return; } if( GdkWindow* topLevel = gdk_window_get_toplevel( window ) ) { GdkRectangle rect = {0, 0, -1, -1}; gdk_window_get_frame_extents( topLevel, &rect ); if( w ) *w = rect.width; if( h ) *h = rect.height; } return; } //________________________________________________________ void gdk_window_get_toplevel_origin( GdkWindow* window, gint* x, gint* y ) { if( x ) *x = 0; if( y ) *y = 0; if( !window ) return; while( window && GDK_IS_WINDOW( window ) && gdk_window_get_window_type( window ) != GDK_WINDOW_TOPLEVEL && gdk_window_get_window_type( window ) != GDK_WINDOW_TEMP ) { gint xloc; gint yloc; gdk_window_get_position( window, &xloc, &yloc ); if( x ) *x += xloc; if( y ) *y += yloc; window = gdk_window_get_parent( window ); } return; } //___________________________________________________________ GdkPixbuf* gdk_pixbuf_set_alpha( const GdkPixbuf *pixbuf, double alpha ) { g_return_val_if_fail( pixbuf != 0L, 0L); g_return_val_if_fail( GDK_IS_PIXBUF( pixbuf ), 0L ); /* Returns a copy of pixbuf with it's non-completely-transparent pixels to have an alpha level "alpha" of their original value. */ GdkPixbuf* target( gdk_pixbuf_add_alpha( pixbuf, false, 0, 0, 0 ) ); if( alpha >= 1.0 ) return target; if( alpha < 0 ) alpha = 0; const int width( gdk_pixbuf_get_width( target ) ); const int height( gdk_pixbuf_get_height( target ) ); const int rowstride( gdk_pixbuf_get_rowstride( target ) ); unsigned char* data = gdk_pixbuf_get_pixels( target ); for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { /* The "4" is the number of chars per pixel, in this case, RGBA, the 3 means "skip to the alpha" */ unsigned char* current = data + ( y*rowstride ) + ( x*4 ) + 3; *(current) = (unsigned char) ( *( current )*alpha ); } } return target; } //___________________________________________________________ GdkPixbuf* gdk_pixbuf_resize( GdkPixbuf* src, int width, int height ) { if( width == gdk_pixbuf_get_width( src ) && height == gdk_pixbuf_get_height( src ) ) { return static_cast<GdkPixbuf*>(g_object_ref (src)); } else { return gdk_pixbuf_scale_simple( src, width, height, GDK_INTERP_BILINEAR ); } } } <|endoftext|>
<commit_before>#include "cinder/app/AppBasic.h" #include "cinder/Surface.h" #include "cinder/gl/Texture.h" #include "cinder/Capture.h" #include "cinder/Text.h" using namespace ci; using namespace ci::app; using namespace std; static const int WIDTH = 640, HEIGHT = 480; class CaptureApp : public AppBasic { public: void setup(); void keyDown( KeyEvent event ); void update(); void draw(); private: vector<CaptureRef> mCaptures; vector<gl::TextureRef> mTextures; vector<gl::TextureRef> mNameTextures; vector<Surface> mRetainedSurfaces; }; void CaptureApp::setup() { // list out the devices vector<Capture::DeviceRef> devices( Capture::getDevices() ); for( vector<Capture::DeviceRef>::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) { Capture::DeviceRef device = *deviceIt; console() << "Found Device " << device->getName() << " ID: " << device->getUniqueId() << std::endl; try { if( device->checkAvailable() ) { mCaptures.push_back( Capture::create( WIDTH, HEIGHT, device ) ); mCaptures.back()->start(); // placeholder text mTextures.push_back( gl::TextureRef() ); // render the name as a texture TextLayout layout; layout.setFont( Font( "Arial", 24 ) ); layout.setColor( Color( 1, 1, 1 ) ); layout.addLine( device->getName() ); mNameTextures.push_back( gl::Texture::create( layout.render( true ) ) ); } else console() << "device is NOT available" << std::endl; } catch( CaptureExc & ) { console() << "Unable to initialize device: " << device->getName() << endl; } } } void CaptureApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); else if( event.getChar() == ' ' ) { mCaptures.back()->isCapturing() ? mCaptures.back()->stop() : mCaptures.back()->start(); } else if( event.getChar() == 'r' ) { // retain a random surface to exercise the surface caching code int device = rand() % ( mCaptures.size() ); mRetainedSurfaces.push_back( mCaptures[device]->getSurface() ); console() << mRetainedSurfaces.size() << " surfaces retained." << std::endl; } else if( event.getChar() == 'u' ) { // unretain retained surface to exercise the Capture's surface caching code if( ! mRetainedSurfaces.empty() ) mRetainedSurfaces.pop_back(); console() << mRetainedSurfaces.size() << " surfaces retained." << std::endl; } } void CaptureApp::update() { for( vector<CaptureRef>::iterator cIt = mCaptures.begin(); cIt != mCaptures.end(); ++cIt ) { if( (*cIt)->checkNewFrame() ) { Surface8u surf = (*cIt)->getSurface(); mTextures[cIt - mCaptures.begin()] = gl::Texture::create( surf ); } } } void CaptureApp::draw() { gl::enableAlphaBlending(); gl::clear( Color::black() ); if( mCaptures.empty() ) return; float width = getWindowWidth() / mCaptures.size(); float height = width / ( WIDTH / (float)HEIGHT ); float x = 0, y = ( getWindowHeight() - height ) / 2.0f; for( vector<CaptureRef>::iterator cIt = mCaptures.begin(); cIt != mCaptures.end(); ++cIt ) { // draw the latest frame gl::color( Color::white() ); if( mTextures[cIt-mCaptures.begin()] ) gl::draw( mTextures[cIt-mCaptures.begin()], Rectf( x, y, x + width, y + height ) ); // draw the name gl::color( Color::black() ); gl::draw( mNameTextures[cIt-mCaptures.begin()], Vec2f( x + 10 + 1, y + 10 + 1 ) ); gl::color( Color( 0.5, 0.75, 1 ) ); gl::draw( mNameTextures[cIt-mCaptures.begin()], Vec2f( x + 10, y + 10 ) ); x += width; } } CINDER_APP_BASIC( CaptureApp, RendererGl ) <commit_msg>Update CaptureAdvanced sample.<commit_after>#include "cinder/app/AppBasic.h" #include "cinder/app/RendererGl.h" #include "cinder/Surface.h" #include "cinder/gl/Texture.h" #include "cinder/Capture.h" #include "cinder/Text.h" using namespace ci; using namespace ci::app; using namespace std; static const int WIDTH = 640, HEIGHT = 480; class CaptureApp : public AppBasic { public: void setup(); void keyDown( KeyEvent event ); void update(); void draw(); private: vector<CaptureRef> mCaptures; vector<gl::TextureRef> mTextures; vector<gl::TextureRef> mNameTextures; vector<Surface> mRetainedSurfaces; }; void CaptureApp::setup() { // list out the devices vector<Capture::DeviceRef> devices( Capture::getDevices() ); for( vector<Capture::DeviceRef>::const_iterator deviceIt = devices.begin(); deviceIt != devices.end(); ++deviceIt ) { Capture::DeviceRef device = *deviceIt; console() << "Found Device " << device->getName() << " ID: " << device->getUniqueId() << std::endl; try { if( device->checkAvailable() ) { mCaptures.push_back( Capture::create( WIDTH, HEIGHT, device ) ); mCaptures.back()->start(); // placeholder text mTextures.push_back( gl::TextureRef() ); // render the name as a texture TextLayout layout; layout.setFont( Font( "Arial", 24 ) ); layout.setColor( Color( 1, 1, 1 ) ); layout.addLine( device->getName() ); mNameTextures.push_back( gl::Texture::create( layout.render( true ) ) ); } else console() << "device is NOT available" << std::endl; } catch( CaptureExc & ) { console() << "Unable to initialize device: " << device->getName() << endl; } } } void CaptureApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); else if( event.getChar() == ' ' ) { mCaptures.back()->isCapturing() ? mCaptures.back()->stop() : mCaptures.back()->start(); } else if( event.getChar() == 'r' ) { // retain a random surface to exercise the surface caching code int device = rand() % ( mCaptures.size() ); mRetainedSurfaces.push_back( mCaptures[device]->getSurface() ); console() << mRetainedSurfaces.size() << " surfaces retained." << std::endl; } else if( event.getChar() == 'u' ) { // unretain retained surface to exercise the Capture's surface caching code if( ! mRetainedSurfaces.empty() ) mRetainedSurfaces.pop_back(); console() << mRetainedSurfaces.size() << " surfaces retained." << std::endl; } } void CaptureApp::update() { for( vector<CaptureRef>::iterator cIt = mCaptures.begin(); cIt != mCaptures.end(); ++cIt ) { if( (*cIt)->checkNewFrame() ) { Surface8u surf = (*cIt)->getSurface(); mTextures[cIt - mCaptures.begin()] = gl::Texture::create( surf ); } } } void CaptureApp::draw() { gl::enableAlphaBlending(); gl::clear( Color::black() ); if( mCaptures.empty() ) return; float width = getWindowWidth() / mCaptures.size(); float height = width / ( WIDTH / (float)HEIGHT ); float x = 0, y = ( getWindowHeight() - height ) / 2.0f; for( vector<CaptureRef>::iterator cIt = mCaptures.begin(); cIt != mCaptures.end(); ++cIt ) { // draw the latest frame gl::color( Color::white() ); if( mTextures[cIt-mCaptures.begin()] ) gl::draw( mTextures[cIt-mCaptures.begin()], Rectf( x, y, x + width, y + height ) ); // draw the name gl::color( Color::black() ); gl::draw( mNameTextures[cIt-mCaptures.begin()], Vec2f( x + 10 + 1, y + 10 + 1 ) ); gl::color( Color( 0.5, 0.75, 1 ) ); gl::draw( mNameTextures[cIt-mCaptures.begin()], Vec2f( x + 10, y + 10 ) ); x += width; } } CINDER_APP_BASIC( CaptureApp, RendererGl ) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTableShapeImportHelper.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:50:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX #define _SC_XMLTABLESHAPEIMPORTHELPER_HXX #ifndef _XMLOFF_SHAPEIMPORT_HXX_ #include <xmloff/shapeimport.hxx> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif class ScXMLImport; class ScXMLAnnotationContext; class XMLTableShapeImportHelper : public XMLShapeImportHelper { ::com::sun::star::table::CellAddress aStartCell; ScXMLAnnotationContext* pAnnotationContext; sal_Bool bOnTable; public: XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 ); ~XMLTableShapeImportHelper(); void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const; virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList, com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes); void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; } void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; } void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; } }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.9.326); FILE MERGED 2005/09/05 15:03:28 rt 1.9.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTableShapeImportHelper.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:59:29 $ * * 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 _SC_XMLTABLESHAPEIMPORTHELPER_HXX #define _SC_XMLTABLESHAPEIMPORTHELPER_HXX #ifndef _XMLOFF_SHAPEIMPORT_HXX_ #include <xmloff/shapeimport.hxx> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif class ScXMLImport; class ScXMLAnnotationContext; class XMLTableShapeImportHelper : public XMLShapeImportHelper { ::com::sun::star::table::CellAddress aStartCell; ScXMLAnnotationContext* pAnnotationContext; sal_Bool bOnTable; public: XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 ); ~XMLTableShapeImportHelper(); void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const; virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList, com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes); void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; } void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; } void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; } }; #endif <|endoftext|>
<commit_before>#ifndef __COMPUTE_TASK_HPP_INCLUDED #define __COMPUTE_TASK_HPP_INCLUDED #include "entity.hpp" #include "compute_task_struct.hpp" #include "pre_iterate_callback.hpp" #include "post_iterate_callback.hpp" #include "family_templates.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <vector> // std::vector // `yli::ontology::ComputeTask` is a class which contains the data for a single // computing task. `ComputeTask` does not have the OpenGL shaders used to process // the data. Instead, the shaders are contained by the parent `Entity` which is // an `yli::ontology::ComputeTask` instance. // // For example, `yli::ontology::Shader` can have vertex and fragment shaders for // computing the distances between nodes of a graph. Then, each `ComputeTask` // would contain the graph data, eg. as a distance matrix. Then, rendering a // `ComputeTask` means computing that task. // // Rendering a `ComputeTask` is done by iterating the task until either // `end_condition_callback_engine->execute()` returns `true`, or until // `n_max_iterations` is reached. If `end_condition_callback_engine` is `nullptr` // or `end_condition_callback_engine->execute()` does not not return an `AnyValue` // which contains `datatypes::BOOL`, then `end_condition_callback_engine` is ignored // and `n_max_iterations` is the exact number of iterations to be done. However, // even if `end_condition_callback_engine->execute()` would return an invalid return // value, that is, not an `AnyValue` which contains `datatypes::BOOL`, // `end_condition_callback_engine->execute()` is still called and taken into account // in every iteration. // // When iterating, there is a `PreIterateCallback` which is executed before each iteration, // and also a `PostIterateCallback` which is executed correspondingly after each iteration. // Of course `PreRenderCallback` and `PostRenderCallback` can be used as well. // `PreRenderCallback` gets executed before the first `PreIterateCallback` call, and // `PostRenderCallback` gets executed after the last `PostRenderCallback` call. // All these callbacks are optional and can be left to `nullptr` if they are not needed. namespace yli { namespace callback_system { class CallbackEngine; } namespace ontology { class Shader; class ComputeTask: public yli::ontology::Entity { public: ComputeTask(yli::ontology::Universe* const universe, const ComputeTaskStruct& compute_task_struct) : Entity(universe) { // constructor. this->parent = compute_task_struct.parent; this->end_condition_callback_engine = compute_task_struct.end_condition_callback_engine; this->n_max_iterations = compute_task_struct.n_max_iterations; this->compute_taskID = compute_task_struct.compute_taskID; this->framebuffer = 0; this->texture = 0; this->render_buffer = 0; this->texture_width = compute_task_struct.texture_width; this->texture_height = compute_task_struct.texture_height; this->preiterate_callback = compute_task_struct.preiterate_callback; this->postiterate_callback = compute_task_struct.postiterate_callback; // Get `childID` from `Shader` and set pointer to this `ComputeTask`. this->bind_to_parent(); // Create FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); // Bind offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); // Create texture. glGenTextures(1, &this->texture); glBindTexture(GL_TEXTURE_2D, this->texture); // Define texture. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->texture_width, this->texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); yli::opengl::set_filtering_parameters(); // Attach texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->texture, 0); // Create and bind render buffer with depth and stencil attachments. glGenRenderbuffers(1, &this->render_buffer); glBindRenderbuffer(GL_RENDERBUFFER, this->render_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, this->texture_width, this->texture_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->render_buffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cerr << "ERROR: `ComputeTask::ComputeTask`: framebuffer is not complete!\n"; } // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::ComputeTask*"; this->can_be_erased = true; } // destructor. ~ComputeTask(); yli::ontology::Entity* get_parent() const override; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend std::size_t yli::ontology::get_number_of_descendants(const std::vector<T1>& child_pointer_vector); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); private: void bind_to_parent(); // This method renders this `ComputeTask`, that is, computes this task. void render(); void preiterate() const; void postiterate() const; std::size_t get_number_of_children() const override; std::size_t get_number_of_descendants() const override; yli::ontology::Shader* parent; // pointer to the `Shader`. // End iterating when `end_condition_callback_engine` returns `true`. std::shared_ptr<yli::callback_system::CallbackEngine> end_condition_callback_engine; // This is the maximum number of iterations. // If `end_condition_callback_engine` is `nullptr`, then this is the number of iterations. // If `end_condition_callback_engine` is not `nullptr`, then this is the maximum number of iterations. std::size_t n_max_iterations; std::size_t compute_taskID; uint32_t framebuffer; uint32_t texture; uint32_t render_buffer; std::size_t texture_width; std::size_t texture_height; PreIterateCallback preiterate_callback; PostIterateCallback postiterate_callback; }; } } #endif <commit_msg>`yli::ontology::ComputeTask`: new member variables.<commit_after>#ifndef __COMPUTE_TASK_HPP_INCLUDED #define __COMPUTE_TASK_HPP_INCLUDED #include "entity.hpp" #include "compute_task_struct.hpp" #include "pre_iterate_callback.hpp" #include "post_iterate_callback.hpp" #include "family_templates.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <vector> // std::vector // `yli::ontology::ComputeTask` is a class which contains the data for a single // computing task. `ComputeTask` does not have the OpenGL shaders used to process // the data. Instead, the shaders are contained by the parent `Entity` which is // an `yli::ontology::ComputeTask` instance. // // For example, `yli::ontology::Shader` can have vertex and fragment shaders for // computing the distances between nodes of a graph. Then, each `ComputeTask` // would contain the graph data, eg. as a distance matrix. Then, rendering a // `ComputeTask` means computing that task. // // Rendering a `ComputeTask` is done by iterating the task until either // `end_condition_callback_engine->execute()` returns `true`, or until // `n_max_iterations` is reached. If `end_condition_callback_engine` is `nullptr` // or `end_condition_callback_engine->execute()` does not not return an `AnyValue` // which contains `datatypes::BOOL`, then `end_condition_callback_engine` is ignored // and `n_max_iterations` is the exact number of iterations to be done. However, // even if `end_condition_callback_engine->execute()` would return an invalid return // value, that is, not an `AnyValue` which contains `datatypes::BOOL`, // `end_condition_callback_engine->execute()` is still called and taken into account // in every iteration. // // When iterating, there is a `PreIterateCallback` which is executed before each iteration, // and also a `PostIterateCallback` which is executed correspondingly after each iteration. // Of course `PreRenderCallback` and `PostRenderCallback` can be used as well. // `PreRenderCallback` gets executed before the first `PreIterateCallback` call, and // `PostRenderCallback` gets executed after the last `PostRenderCallback` call. // All these callbacks are optional and can be left to `nullptr` if they are not needed. namespace yli { namespace callback_system { class CallbackEngine; } namespace ontology { class Shader; class ComputeTask: public yli::ontology::Entity { public: ComputeTask(yli::ontology::Universe* const universe, const ComputeTaskStruct& compute_task_struct) : Entity(universe) { // constructor. this->parent = compute_task_struct.parent; this->end_condition_callback_engine = compute_task_struct.end_condition_callback_engine; this->n_max_iterations = compute_task_struct.n_max_iterations; this->compute_taskID = compute_task_struct.compute_taskID; this->framebuffer = 0; this->texture = 0; this->render_buffer = 0; this->vertex_position_modelspaceID = 0; this->vertexUVID = 0; this->vertexbuffer = 0; this->uvbuffer = 0; this->texture_width = compute_task_struct.texture_width; this->texture_height = compute_task_struct.texture_height; this->preiterate_callback = compute_task_struct.preiterate_callback; this->postiterate_callback = compute_task_struct.postiterate_callback; // Get `childID` from `Shader` and set pointer to this `ComputeTask`. this->bind_to_parent(); // Create FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); // Bind offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); // Create texture. glGenTextures(1, &this->texture); glBindTexture(GL_TEXTURE_2D, this->texture); // Define texture. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->texture_width, this->texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); yli::opengl::set_filtering_parameters(); // Attach texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->texture, 0); // Create and bind render buffer with depth and stencil attachments. glGenRenderbuffers(1, &this->render_buffer); glBindRenderbuffer(GL_RENDERBUFFER, this->render_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, this->texture_width, this->texture_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->render_buffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cerr << "ERROR: `ComputeTask::ComputeTask`: framebuffer is not complete!\n"; } // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::ComputeTask*"; this->can_be_erased = true; } // destructor. ~ComputeTask(); yli::ontology::Entity* get_parent() const override; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend std::size_t yli::ontology::get_number_of_descendants(const std::vector<T1>& child_pointer_vector); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); private: void bind_to_parent(); // This method renders this `ComputeTask`, that is, computes this task. void render(); void preiterate() const; void postiterate() const; std::size_t get_number_of_children() const override; std::size_t get_number_of_descendants() const override; yli::ontology::Shader* parent; // pointer to the `Shader`. // End iterating when `end_condition_callback_engine` returns `true`. std::shared_ptr<yli::callback_system::CallbackEngine> end_condition_callback_engine; // This is the maximum number of iterations. // If `end_condition_callback_engine` is `nullptr`, then this is the number of iterations. // If `end_condition_callback_engine` is not `nullptr`, then this is the maximum number of iterations. std::size_t n_max_iterations; std::size_t compute_taskID; uint32_t framebuffer; uint32_t texture; uint32_t render_buffer; std::size_t texture_width; std::size_t texture_height; uint32_t vertex_position_modelspaceID; uint32_t vertexUVID; uint32_t vertexbuffer; uint32_t uvbuffer; PreIterateCallback preiterate_callback; PostIterateCallback postiterate_callback; }; } } #endif <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////////////////////// // header_normalize:: // // ATS plugin to convert headers into camel-case. It may be useful to solve // interworking issues with legacy origins not supporting lower case headers // required by protocols such as spdy/http2 etc. // // To use this plugin, configure a remap.config rule like // // map http://foo.com http://bar.com @plugin=header_normalize.so // // // The list of of all available parameters is in the README. // // // Note that the path to the plugin itself must be absolute, and by default it is // // /home/y/libexec/trafficserver/header_normalize.so // // #define UNUSED __attribute__ ((unused)) static char UNUSED rcsId__header_normalize_cc[] = "@(#) $Id: header_normalize.cc 218 2014-11-11 01:29:16Z sudheerv $ built on " __DATE__ " " __TIME__; #include <sys/time.h> #include <ts/ts.h> #include <ts/remap.h> #include <set> #include <string> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <netdb.h> #include <map> using namespace std; /////////////////////////////////////////////////////////////////////////////// // Some constants. // const char* PLUGIN_NAME = "header_normalize"; std::map<std::string, std::string, std::less<std::string> > hdrMap; static void buildHdrMap() { hdrMap["accept"] = "Accept"; hdrMap["accept-charset"] = "Accept-Charset"; hdrMap["accept-encoding"] = "Accept-Encoding"; hdrMap["accept-language"] = "Accept-Language"; hdrMap["accept-ranges"] = "Accept-Ranges"; hdrMap["age"] = "Age"; hdrMap["allow"] = "Allow"; hdrMap["approved"] = "Approved"; hdrMap["bytes"] = "Bytes"; hdrMap["cache-control"] = "Cache-Control"; hdrMap["client-ip"] = "Client-Ip"; hdrMap["connection"] = "Connection"; hdrMap["content-base"] = "Content-Base"; hdrMap["content-encoding"] = "Content-Encoding"; hdrMap["content-language"] = "Content-Language"; hdrMap["content-length"] = "Content-Length"; hdrMap["content-location"] = "Content-Location"; hdrMap["content-md5"] = "Content-MD5"; hdrMap["content-range"] = "Content-Range"; hdrMap["content-type"] = "Content-Type"; hdrMap["control"] = "Control"; hdrMap["cookie"] = "Cookie"; hdrMap["date"] = "Date"; hdrMap["distribution"] = "Distribution"; hdrMap["etag"] = "Etag"; hdrMap["expect"] = "Expect"; hdrMap["expires"] = "Expires"; hdrMap["followup-to"] = "Followup-To"; hdrMap["from"] = "From"; hdrMap["host"] = "Host"; hdrMap["if-match"] = "If-Match"; hdrMap["if-modified-since"] = "If-Modified-Since"; hdrMap["if-none-match"] = "If-None-Match"; hdrMap["if-range"] = "If-Range"; hdrMap["if-unmodified-since"] = "If-Unmodified-Since"; hdrMap["keep-alive"] = "Keep-Alive"; hdrMap["keywords"] = "Keywords"; hdrMap["last-modified"] = "Last-Modified"; hdrMap["lines"] = "Lines"; hdrMap["location"] = "Location"; hdrMap["max-forwards"] = "Max-Forwards"; hdrMap["message-id"] = "Message-Id"; hdrMap["newsgroups"] = "Newsgroups"; hdrMap["organization"] = "Organization"; hdrMap["path"] = "Path"; hdrMap["pragma"] = "Pragma"; hdrMap["proxy-authenticate"] = "Proxy-Authenticate"; hdrMap["proxy-authorization"] = "Proxy-Authorization"; hdrMap["proxy-connection"] = "Proxy-Connection"; hdrMap["public"] = "Public"; hdrMap["range"] = "Range"; hdrMap["references"] = "References"; hdrMap["referer"] = "Referer"; hdrMap["reply-to"] = "Reply-To"; hdrMap["retry-after"] = "Retry-After"; hdrMap["sender"] = "Sender"; hdrMap["server"] = "Server"; hdrMap["set-cookie"] = "Set-Cookie"; hdrMap["strict-transport-security"] = "Strict-Transport-Security"; hdrMap["subject"] = "Subject"; hdrMap["summary"] = "Summary"; hdrMap["te"] = "Te"; hdrMap["transfer-encoding"] = "Transfer-Encoding"; hdrMap["upgrade"] = "Upgrade"; hdrMap["user-agent"] = "User-Agent"; hdrMap["vary"] = "Vary"; hdrMap["via"] = "Via"; hdrMap["warning"] = "Warning"; hdrMap["www-authenticate"] = "Www-Authenticate"; hdrMap["xref"] = "Xref"; hdrMap["@datainfo"] = "@DataInfo"; hdrMap["x-id"] = "X-ID"; hdrMap["x-forwarded-for"] = "X-Forwarded-For"; hdrMap["sec-websocket-key"] = "Sec-WebSocket-Key"; hdrMap["sec-websocket-version"] = "Sec-WebSocket-Version"; } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin. // // // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { strncpy(errbuf, "[tsremap_init] - Invalid TSREMAP_INTERFACE argument", errbuf_size - 1); return TS_ERROR; } if (api_info->tsremap_version < TSREMAP_VERSION) { snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff)); return TS_ERROR; } buildHdrMap(); TSDebug(PLUGIN_NAME, "plugin is succesfully initialized"); return TS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // One instance per remap.config invocation. // TSReturnCode TSRemapNewInstance(int /* argc */, char * /* argv[] */, void ** /* ih */, char * /* errbuf */, int /* errbuf_size */) { return TS_SUCCESS; } void TSRemapDelteInstance(void * /* ih */) { } static int read_request_hook(TSCont /* contp */, TSEvent /* event */, void *edata) { TSHttpTxn rh = (TSHttpTxn) edata; TSMLoc hdr, next_hdr; TSMBuffer hdr_bufp; TSMLoc req_hdrs; if (TSHttpTxnClientReqGet(rh, &hdr_bufp, &req_hdrs) == TS_SUCCESS) { hdr = TSMimeHdrFieldGet(hdr_bufp, req_hdrs, 0); int n_mime_headers = TSMimeHdrFieldsCount(hdr_bufp, req_hdrs); TSDebug(PLUGIN_NAME, "*** Camel Casing %u hdrs in the request", n_mime_headers); for (int i = 0; i < n_mime_headers; ++i) { if (hdr == NULL) break; next_hdr = TSMimeHdrFieldNext(hdr_bufp, req_hdrs, hdr); int old_hdr_len; const char* old_hdr_name = TSMimeHdrFieldNameGet(hdr_bufp, req_hdrs, hdr, &old_hdr_len); // TSMimeHdrFieldNameGet returns the MIME_FIELD_NAME // for all MIME hdrs, which is always in Camel Case if (islower(old_hdr_name[0])) { TSDebug(PLUGIN_NAME, "*** non MIME Hdr %s, leaving it for now", old_hdr_name); TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; continue; } int hdr_value_len = 0; const char *hdr_value = TSMimeHdrFieldValueStringGet(hdr_bufp, req_hdrs, hdr, 0, &hdr_value_len); // hdr returned by TSMimeHdrFieldNameGet is already // in camel case, just destroy the lowercase spdy header // and replace it with TSMimeHdrFieldNameGet char* new_hdr_name = (char*)old_hdr_name; if (new_hdr_name) { TSMLoc new_hdr_loc; TSReturnCode rval = TSMimeHdrFieldCreateNamed(hdr_bufp, req_hdrs, new_hdr_name, old_hdr_len, &new_hdr_loc); if (rval == TS_SUCCESS) { TSDebug(PLUGIN_NAME, "*** hdr convert %s to %s", old_hdr_name, new_hdr_name); TSMimeHdrFieldValueStringSet(hdr_bufp, req_hdrs, new_hdr_loc, -1, hdr_value, hdr_value_len); TSMimeHdrFieldAppend(hdr_bufp, req_hdrs, new_hdr_loc); TSHandleMLocRelease(hdr_bufp, req_hdrs, new_hdr_loc); } TSMimeHdrFieldDestroy(hdr_bufp, req_hdrs, hdr); } else { TSDebug(PLUGIN_NAME, "*** can't find hdr %s in hdrMap", old_hdr_name); } TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; } TSHandleMLocRelease(hdr_bufp, TS_NULL_MLOC, req_hdrs); } TSHttpTxnReenable(rh, TS_EVENT_HTTP_CONTINUE); return 0; } void TSPluginInit(int /* argc */, const char * /* argv[] */) { TSDebug(PLUGIN_NAME, "initializing plugin"); TSCont contp; buildHdrMap(); contp = TSContCreate(read_request_hook, NULL); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp); } /////////////////////////////////////////////////////////////////////////////// // This is the main "entry" point for the plugin, called for every request. // TSRemapStatus TSRemapDoRemap (void * /* ih */, TSHttpTxn rh, TSRemapRequestInfo * /* rri */) { read_request_hook(NULL, TS_EVENT_HTTP_READ_REQUEST_HDR, rh); return TSREMAP_DID_REMAP; } <commit_msg>[TS-2812]: Adding a comment to optimize the hook to send_request_hdr_hook<commit_after>////////////////////////////////////////////////////////////////////////////////////////////// // header_normalize:: // // ATS plugin to convert headers into camel-case. It may be useful to solve // interworking issues with legacy origins not supporting lower case headers // required by protocols such as spdy/http2 etc. // // Note that the plugin currently uses READ_REQUEST_HDR_HOOK to camel-case // the headers. As an optimization, it can be changed to SEND_REQUEST_HDR_HOOK // so that it only converts, if/when the request is being sent to the origin // // To use this plugin, configure a remap.config rule like // // map http://foo.com http://bar.com @plugin=header_normalize.so // // // The list of of all available parameters is in the README. // // // Note that the path to the plugin itself must be absolute, and by default it is // // /home/y/libexec/trafficserver/header_normalize.so // // #define UNUSED __attribute__ ((unused)) static char UNUSED rcsId__header_normalize_cc[] = "@(#) $Id: header_normalize.cc 218 2014-11-11 01:29:16Z sudheerv $ built on " __DATE__ " " __TIME__; #include <sys/time.h> #include <ts/ts.h> #include <ts/remap.h> #include <set> #include <string> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <netdb.h> #include <map> using namespace std; /////////////////////////////////////////////////////////////////////////////// // Some constants. // const char* PLUGIN_NAME = "header_normalize"; std::map<std::string, std::string, std::less<std::string> > hdrMap; static void buildHdrMap() { hdrMap["accept"] = "Accept"; hdrMap["accept-charset"] = "Accept-Charset"; hdrMap["accept-encoding"] = "Accept-Encoding"; hdrMap["accept-language"] = "Accept-Language"; hdrMap["accept-ranges"] = "Accept-Ranges"; hdrMap["age"] = "Age"; hdrMap["allow"] = "Allow"; hdrMap["approved"] = "Approved"; hdrMap["bytes"] = "Bytes"; hdrMap["cache-control"] = "Cache-Control"; hdrMap["client-ip"] = "Client-Ip"; hdrMap["connection"] = "Connection"; hdrMap["content-base"] = "Content-Base"; hdrMap["content-encoding"] = "Content-Encoding"; hdrMap["content-language"] = "Content-Language"; hdrMap["content-length"] = "Content-Length"; hdrMap["content-location"] = "Content-Location"; hdrMap["content-md5"] = "Content-MD5"; hdrMap["content-range"] = "Content-Range"; hdrMap["content-type"] = "Content-Type"; hdrMap["control"] = "Control"; hdrMap["cookie"] = "Cookie"; hdrMap["date"] = "Date"; hdrMap["distribution"] = "Distribution"; hdrMap["etag"] = "Etag"; hdrMap["expect"] = "Expect"; hdrMap["expires"] = "Expires"; hdrMap["followup-to"] = "Followup-To"; hdrMap["from"] = "From"; hdrMap["host"] = "Host"; hdrMap["if-match"] = "If-Match"; hdrMap["if-modified-since"] = "If-Modified-Since"; hdrMap["if-none-match"] = "If-None-Match"; hdrMap["if-range"] = "If-Range"; hdrMap["if-unmodified-since"] = "If-Unmodified-Since"; hdrMap["keep-alive"] = "Keep-Alive"; hdrMap["keywords"] = "Keywords"; hdrMap["last-modified"] = "Last-Modified"; hdrMap["lines"] = "Lines"; hdrMap["location"] = "Location"; hdrMap["max-forwards"] = "Max-Forwards"; hdrMap["message-id"] = "Message-Id"; hdrMap["newsgroups"] = "Newsgroups"; hdrMap["organization"] = "Organization"; hdrMap["path"] = "Path"; hdrMap["pragma"] = "Pragma"; hdrMap["proxy-authenticate"] = "Proxy-Authenticate"; hdrMap["proxy-authorization"] = "Proxy-Authorization"; hdrMap["proxy-connection"] = "Proxy-Connection"; hdrMap["public"] = "Public"; hdrMap["range"] = "Range"; hdrMap["references"] = "References"; hdrMap["referer"] = "Referer"; hdrMap["reply-to"] = "Reply-To"; hdrMap["retry-after"] = "Retry-After"; hdrMap["sender"] = "Sender"; hdrMap["server"] = "Server"; hdrMap["set-cookie"] = "Set-Cookie"; hdrMap["strict-transport-security"] = "Strict-Transport-Security"; hdrMap["subject"] = "Subject"; hdrMap["summary"] = "Summary"; hdrMap["te"] = "Te"; hdrMap["transfer-encoding"] = "Transfer-Encoding"; hdrMap["upgrade"] = "Upgrade"; hdrMap["user-agent"] = "User-Agent"; hdrMap["vary"] = "Vary"; hdrMap["via"] = "Via"; hdrMap["warning"] = "Warning"; hdrMap["www-authenticate"] = "Www-Authenticate"; hdrMap["xref"] = "Xref"; hdrMap["@datainfo"] = "@DataInfo"; hdrMap["x-id"] = "X-ID"; hdrMap["x-forwarded-for"] = "X-Forwarded-For"; hdrMap["sec-websocket-key"] = "Sec-WebSocket-Key"; hdrMap["sec-websocket-version"] = "Sec-WebSocket-Version"; } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin. // // // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { strncpy(errbuf, "[tsremap_init] - Invalid TSREMAP_INTERFACE argument", errbuf_size - 1); return TS_ERROR; } if (api_info->tsremap_version < TSREMAP_VERSION) { snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff)); return TS_ERROR; } buildHdrMap(); TSDebug(PLUGIN_NAME, "plugin is succesfully initialized"); return TS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // One instance per remap.config invocation. // TSReturnCode TSRemapNewInstance(int /* argc */, char * /* argv[] */, void ** /* ih */, char * /* errbuf */, int /* errbuf_size */) { return TS_SUCCESS; } void TSRemapDelteInstance(void * /* ih */) { } static int read_request_hook(TSCont /* contp */, TSEvent /* event */, void *edata) { TSHttpTxn rh = (TSHttpTxn) edata; TSMLoc hdr, next_hdr; TSMBuffer hdr_bufp; TSMLoc req_hdrs; if (TSHttpTxnClientReqGet(rh, &hdr_bufp, &req_hdrs) == TS_SUCCESS) { hdr = TSMimeHdrFieldGet(hdr_bufp, req_hdrs, 0); int n_mime_headers = TSMimeHdrFieldsCount(hdr_bufp, req_hdrs); TSDebug(PLUGIN_NAME, "*** Camel Casing %u hdrs in the request", n_mime_headers); for (int i = 0; i < n_mime_headers; ++i) { if (hdr == NULL) break; next_hdr = TSMimeHdrFieldNext(hdr_bufp, req_hdrs, hdr); int old_hdr_len; const char* old_hdr_name = TSMimeHdrFieldNameGet(hdr_bufp, req_hdrs, hdr, &old_hdr_len); // TSMimeHdrFieldNameGet returns the MIME_FIELD_NAME // for all MIME hdrs, which is always in Camel Case if (islower(old_hdr_name[0])) { TSDebug(PLUGIN_NAME, "*** non MIME Hdr %s, leaving it for now", old_hdr_name); TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; continue; } int hdr_value_len = 0; const char *hdr_value = TSMimeHdrFieldValueStringGet(hdr_bufp, req_hdrs, hdr, 0, &hdr_value_len); // hdr returned by TSMimeHdrFieldNameGet is already // in camel case, just destroy the lowercase spdy header // and replace it with TSMimeHdrFieldNameGet char* new_hdr_name = (char*)old_hdr_name; if (new_hdr_name) { TSMLoc new_hdr_loc; TSReturnCode rval = TSMimeHdrFieldCreateNamed(hdr_bufp, req_hdrs, new_hdr_name, old_hdr_len, &new_hdr_loc); if (rval == TS_SUCCESS) { TSDebug(PLUGIN_NAME, "*** hdr convert %s to %s", old_hdr_name, new_hdr_name); TSMimeHdrFieldValueStringSet(hdr_bufp, req_hdrs, new_hdr_loc, -1, hdr_value, hdr_value_len); TSMimeHdrFieldAppend(hdr_bufp, req_hdrs, new_hdr_loc); TSHandleMLocRelease(hdr_bufp, req_hdrs, new_hdr_loc); } TSMimeHdrFieldDestroy(hdr_bufp, req_hdrs, hdr); } else { TSDebug(PLUGIN_NAME, "*** can't find hdr %s in hdrMap", old_hdr_name); } TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; } TSHandleMLocRelease(hdr_bufp, TS_NULL_MLOC, req_hdrs); } TSHttpTxnReenable(rh, TS_EVENT_HTTP_CONTINUE); return 0; } void TSPluginInit(int /* argc */, const char * /* argv[] */) { TSDebug(PLUGIN_NAME, "initializing plugin"); TSCont contp; buildHdrMap(); contp = TSContCreate(read_request_hook, NULL); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp); } /////////////////////////////////////////////////////////////////////////////// // This is the main "entry" point for the plugin, called for every request. // TSRemapStatus TSRemapDoRemap (void * /* ih */, TSHttpTxn rh, TSRemapRequestInfo * /* rri */) { read_request_hook(NULL, TS_EVENT_HTTP_READ_REQUEST_HDR, rh); return TSREMAP_DID_REMAP; } <|endoftext|>
<commit_before>// Copyright (c) 2013-2021 mogemimi. Distributed under the MIT license. #pragma once #include "pomdog/platform/win32/prerequisites_win32.hpp" #include "pomdog/basic/conditional_compilation.hpp" #include "pomdog/graphics/direct3d11/prerequisites_direct3d11.hpp" #include "pomdog/graphics/graphics_device.hpp" #include "pomdog/graphics/presentation_parameters.hpp" #include "pomdog/utility/errors.hpp" POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN #include <wrl/client.h> #include <memory> #include <vector> POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END namespace Pomdog::Detail::Direct3D11 { class AdapterManager final { private: std::vector<Microsoft::WRL::ComPtr<IDXGIAdapter1>> adapters; Microsoft::WRL::ComPtr<IDXGIAdapter1> activeAdapter; public: [[nodiscard]] std::unique_ptr<Error> EnumAdapters() noexcept; void Clear(); IDXGIAdapter1* ActiveAdapter() const; [[nodiscard]] std::tuple<Microsoft::WRL::ComPtr<IDXGIFactory1>, std::unique_ptr<Error>> GetFactory() noexcept; }; class GraphicsDeviceDirect3D11 final : public GraphicsDevice { public: [[nodiscard]] std::unique_ptr<Error> Initialize(const PresentationParameters& presentationParameters) noexcept; ~GraphicsDeviceDirect3D11(); /// Gets the currently supported shader language. ShaderLanguage GetSupportedLanguage() const noexcept override; /// Gets the presentation parameters. PresentationParameters GetPresentationParameters() const noexcept override; /// Creates a graphics command list. std::tuple<std::shared_ptr<GraphicsCommandList>, std::unique_ptr<Error>> CreateGraphicsCommandList() noexcept override; /// Creates a vertex buffer. std::tuple<std::shared_ptr<VertexBuffer>, std::unique_ptr<Error>> CreateVertexBuffer( const void* vertices, std::size_t vertexCount, std::size_t strideBytes, BufferUsage bufferUsage) noexcept override; /// Creates a vertex buffer. std::tuple<std::shared_ptr<VertexBuffer>, std::unique_ptr<Error>> CreateVertexBuffer( std::size_t vertexCount, std::size_t strideBytes, BufferUsage bufferUsage) noexcept override; /// Creates an index buffer. std::tuple<std::shared_ptr<IndexBuffer>, std::unique_ptr<Error>> CreateIndexBuffer( IndexElementSize elementSize, const void* indices, std::size_t indexCount, BufferUsage bufferUsage) noexcept override; /// Creates an index buffer. std::tuple<std::shared_ptr<IndexBuffer>, std::unique_ptr<Error>> CreateIndexBuffer( IndexElementSize elementSize, std::size_t indexCount, BufferUsage bufferUsage) noexcept override; /// Creates a constant buffer. std::tuple<std::shared_ptr<ConstantBuffer>, std::unique_ptr<Error>> CreateConstantBuffer( const void* sourceData, std::size_t sizeInBytes, BufferUsage bufferUsage) noexcept override; /// Creates a constant buffer. std::tuple<std::shared_ptr<ConstantBuffer>, std::unique_ptr<Error>> CreateConstantBuffer( std::size_t sizeInBytes, BufferUsage bufferUsage) noexcept override; /// Creates a pipeline state object. std::tuple<std::shared_ptr<PipelineState>, std::unique_ptr<Error>> CreatePipelineState(const PipelineStateDescription& description) noexcept override; /// Creates an effect reflection. std::tuple<std::shared_ptr<EffectReflection>, std::unique_ptr<Error>> CreateEffectReflection( const PipelineStateDescription& description, const std::shared_ptr<PipelineState>& pipelineState) noexcept override; /// Creates a shader object. std::tuple<std::unique_ptr<Shader>, std::unique_ptr<Error>> CreateShader( const Detail::ShaderBytecode& shaderBytecode, const Detail::ShaderCompileOptions& compileOptions) noexcept override; /// Creates a 2D render target. std::tuple<std::shared_ptr<RenderTarget2D>, std::unique_ptr<Error>> CreateRenderTarget2D( std::int32_t width, std::int32_t height) noexcept override; /// Creates a 2D render target. std::tuple<std::shared_ptr<RenderTarget2D>, std::unique_ptr<Error>> CreateRenderTarget2D( std::int32_t width, std::int32_t height, bool generateMipmap, SurfaceFormat format) noexcept override; /// Creates a depth stencil buffer. std::tuple<std::shared_ptr<DepthStencilBuffer>, std::unique_ptr<Error>> CreateDepthStencilBuffer( std::int32_t width, std::int32_t height, SurfaceFormat depthStencilFormat) noexcept override; /// Creates a sampler state object. std::tuple<std::shared_ptr<SamplerState>, std::unique_ptr<Error>> CreateSamplerState(const SamplerDescription& description) noexcept override; /// Creates a 2D texture. std::tuple<std::shared_ptr<Texture2D>, std::unique_ptr<Error>> CreateTexture2D( std::int32_t width, std::int32_t height) noexcept override; /// Creates a 2D texture. std::tuple<std::shared_ptr<Texture2D>, std::unique_ptr<Error>> CreateTexture2D( std::int32_t width, std::int32_t height, bool mipMap, SurfaceFormat format) noexcept override; /// Gets the pointer of the native graphics device. [[nodiscard]] Microsoft::WRL::ComPtr<ID3D11Device3> GetDevice() const noexcept; /// Gets the pointer of the IDXGIFactory1 object. [[nodiscard]] std::tuple<Microsoft::WRL::ComPtr<IDXGIFactory1>, std::unique_ptr<Error>> GetDXGIFactory() noexcept; void ClientSizeChanged(int width, int height); private: AdapterManager adapters; Microsoft::WRL::ComPtr<ID3D11Device3> device; Microsoft::WRL::ComPtr<ID3D11InfoQueue> infoQueue; D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_1; PresentationParameters presentationParameters; }; } // namespace Pomdog::Detail::Direct3D11 <commit_msg>Clang format<commit_after>// Copyright (c) 2013-2021 mogemimi. Distributed under the MIT license. #pragma once #include "pomdog/basic/conditional_compilation.hpp" #include "pomdog/graphics/direct3d11/prerequisites_direct3d11.hpp" #include "pomdog/graphics/graphics_device.hpp" #include "pomdog/graphics/presentation_parameters.hpp" #include "pomdog/platform/win32/prerequisites_win32.hpp" #include "pomdog/utility/errors.hpp" POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN #include <wrl/client.h> #include <memory> #include <vector> POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END namespace Pomdog::Detail::Direct3D11 { class AdapterManager final { private: std::vector<Microsoft::WRL::ComPtr<IDXGIAdapter1>> adapters; Microsoft::WRL::ComPtr<IDXGIAdapter1> activeAdapter; public: [[nodiscard]] std::unique_ptr<Error> EnumAdapters() noexcept; void Clear(); IDXGIAdapter1* ActiveAdapter() const; [[nodiscard]] std::tuple<Microsoft::WRL::ComPtr<IDXGIFactory1>, std::unique_ptr<Error>> GetFactory() noexcept; }; class GraphicsDeviceDirect3D11 final : public GraphicsDevice { public: [[nodiscard]] std::unique_ptr<Error> Initialize(const PresentationParameters& presentationParameters) noexcept; ~GraphicsDeviceDirect3D11(); /// Gets the currently supported shader language. ShaderLanguage GetSupportedLanguage() const noexcept override; /// Gets the presentation parameters. PresentationParameters GetPresentationParameters() const noexcept override; /// Creates a graphics command list. std::tuple<std::shared_ptr<GraphicsCommandList>, std::unique_ptr<Error>> CreateGraphicsCommandList() noexcept override; /// Creates a vertex buffer. std::tuple<std::shared_ptr<VertexBuffer>, std::unique_ptr<Error>> CreateVertexBuffer( const void* vertices, std::size_t vertexCount, std::size_t strideBytes, BufferUsage bufferUsage) noexcept override; /// Creates a vertex buffer. std::tuple<std::shared_ptr<VertexBuffer>, std::unique_ptr<Error>> CreateVertexBuffer( std::size_t vertexCount, std::size_t strideBytes, BufferUsage bufferUsage) noexcept override; /// Creates an index buffer. std::tuple<std::shared_ptr<IndexBuffer>, std::unique_ptr<Error>> CreateIndexBuffer( IndexElementSize elementSize, const void* indices, std::size_t indexCount, BufferUsage bufferUsage) noexcept override; /// Creates an index buffer. std::tuple<std::shared_ptr<IndexBuffer>, std::unique_ptr<Error>> CreateIndexBuffer( IndexElementSize elementSize, std::size_t indexCount, BufferUsage bufferUsage) noexcept override; /// Creates a constant buffer. std::tuple<std::shared_ptr<ConstantBuffer>, std::unique_ptr<Error>> CreateConstantBuffer( const void* sourceData, std::size_t sizeInBytes, BufferUsage bufferUsage) noexcept override; /// Creates a constant buffer. std::tuple<std::shared_ptr<ConstantBuffer>, std::unique_ptr<Error>> CreateConstantBuffer( std::size_t sizeInBytes, BufferUsage bufferUsage) noexcept override; /// Creates a pipeline state object. std::tuple<std::shared_ptr<PipelineState>, std::unique_ptr<Error>> CreatePipelineState(const PipelineStateDescription& description) noexcept override; /// Creates an effect reflection. std::tuple<std::shared_ptr<EffectReflection>, std::unique_ptr<Error>> CreateEffectReflection( const PipelineStateDescription& description, const std::shared_ptr<PipelineState>& pipelineState) noexcept override; /// Creates a shader object. std::tuple<std::unique_ptr<Shader>, std::unique_ptr<Error>> CreateShader( const Detail::ShaderBytecode& shaderBytecode, const Detail::ShaderCompileOptions& compileOptions) noexcept override; /// Creates a 2D render target. std::tuple<std::shared_ptr<RenderTarget2D>, std::unique_ptr<Error>> CreateRenderTarget2D( std::int32_t width, std::int32_t height) noexcept override; /// Creates a 2D render target. std::tuple<std::shared_ptr<RenderTarget2D>, std::unique_ptr<Error>> CreateRenderTarget2D( std::int32_t width, std::int32_t height, bool generateMipmap, SurfaceFormat format) noexcept override; /// Creates a depth stencil buffer. std::tuple<std::shared_ptr<DepthStencilBuffer>, std::unique_ptr<Error>> CreateDepthStencilBuffer( std::int32_t width, std::int32_t height, SurfaceFormat depthStencilFormat) noexcept override; /// Creates a sampler state object. std::tuple<std::shared_ptr<SamplerState>, std::unique_ptr<Error>> CreateSamplerState(const SamplerDescription& description) noexcept override; /// Creates a 2D texture. std::tuple<std::shared_ptr<Texture2D>, std::unique_ptr<Error>> CreateTexture2D( std::int32_t width, std::int32_t height) noexcept override; /// Creates a 2D texture. std::tuple<std::shared_ptr<Texture2D>, std::unique_ptr<Error>> CreateTexture2D( std::int32_t width, std::int32_t height, bool mipMap, SurfaceFormat format) noexcept override; /// Gets the pointer of the native graphics device. [[nodiscard]] Microsoft::WRL::ComPtr<ID3D11Device3> GetDevice() const noexcept; /// Gets the pointer of the IDXGIFactory1 object. [[nodiscard]] std::tuple<Microsoft::WRL::ComPtr<IDXGIFactory1>, std::unique_ptr<Error>> GetDXGIFactory() noexcept; void ClientSizeChanged(int width, int height); private: AdapterManager adapters; Microsoft::WRL::ComPtr<ID3D11Device3> device; Microsoft::WRL::ComPtr<ID3D11InfoQueue> infoQueue; D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_1; PresentationParameters presentationParameters; }; } // namespace Pomdog::Detail::Direct3D11 <|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 "native_client/src/trusted/plugin/file_downloader.h" #include <stdio.h> #include <string> #include "native_client/src/include/portability_io.h" #include "native_client/src/shared/platform/nacl_check.h" #include "native_client/src/shared/platform/nacl_time.h" #include "native_client/src/trusted/plugin/plugin.h" #include "native_client/src/trusted/plugin/utility.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_file_io.h" #include "ppapi/cpp/file_io.h" #include "ppapi/cpp/file_ref.h" #include "ppapi/cpp/url_request_info.h" #include "ppapi/cpp/url_response_info.h" namespace { const int32_t kExtensionUrlRequestStatusOk = 200; const int32_t kDataUriRequestStatusOk = 0; } namespace plugin { void FileDownloader::Initialize(Plugin* instance) { PLUGIN_PRINTF(("FileDownloader::FileDownloader (this=%p)\n", static_cast<void*>(this))); CHECK(instance != NULL); CHECK(instance_ == NULL); // Can only initialize once. instance_ = instance; callback_factory_.Initialize(this); file_io_trusted_interface_ = static_cast<const PPB_FileIOTrusted*>( pp::Module::Get()->GetBrowserInterface(PPB_FILEIOTRUSTED_INTERFACE)); url_loader_trusted_interface_ = static_cast<const PPB_URLLoaderTrusted*>( pp::Module::Get()->GetBrowserInterface(PPB_URLLOADERTRUSTED_INTERFACE)); } bool FileDownloader::Open( const nacl::string& url, DownloadFlags flags, const pp::CompletionCallback& callback, PP_URLLoaderTrusted_StatusCallback progress_callback) { PLUGIN_PRINTF(("FileDownloader::Open (url=%s)\n", url.c_str())); if (callback.pp_completion_callback().func == NULL || instance_ == NULL || file_io_trusted_interface_ == NULL) return false; CHECK(instance_ != NULL); open_time_ = NaClGetTimeOfDayMicroseconds(); url_to_open_ = url; url_ = url; file_open_notify_callback_ = callback; flags_ = flags; buffer_.clear(); pp::Module* module = pp::Module::Get(); pp::URLRequestInfo url_request(instance_); do { // Reset the url loader and file reader. // Note that we have the only reference to the underlying objects, so // this will implicitly close any pending IO and destroy them. url_loader_ = pp::URLLoader(instance_); url_scheme_ = instance_->GetUrlScheme(url); bool grant_universal_access = false; if (url_scheme_ == SCHEME_CHROME_EXTENSION) { if (instance_->IsForeignMIMEType()) { // This NEXE is being used as a content type handler rather than // directly by an HTML document. In that case, the NEXE runs in the // security context of the content it is rendering and the NEXE itself // appears to be a cross-origin resource stored in a Chrome extension. // We request universal access during this load so that we can read the // NEXE. grant_universal_access = true; } } else if (url_scheme_ == SCHEME_DATA) { // TODO(elijahtaylor) Remove this when data URIs can be read without // universal access. if (streaming_to_buffer()) { grant_universal_access = true; } else { // Open is to invoke a callback on success or failure. Schedule // it asynchronously to follow PPAPI's convention and avoid reentrancy. pp::Core* core = pp::Module::Get()->core(); core->CallOnMainThread(0, callback, PP_ERROR_NOACCESS); PLUGIN_PRINTF(("FileDownloader::Open (pp_error=PP_ERROR_NOACCESS)\n")); return true; } } if (url_loader_trusted_interface_ != NULL) { if (grant_universal_access) { url_loader_trusted_interface_->GrantUniversalAccess( url_loader_.pp_resource()); } if (progress_callback != NULL) { url_request.SetRecordDownloadProgress(true); url_loader_trusted_interface_->RegisterStatusCallback( url_loader_.pp_resource(), progress_callback); } } // Prepare the url request. url_request.SetURL(url_); if (streaming_to_file()) { file_reader_ = pp::FileIO(instance_); url_request.SetStreamToFile(true); } } while (0); void (FileDownloader::*start_notify)(int32_t); if (streaming_to_file()) start_notify = &FileDownloader::URLLoadStartNotify; else start_notify = &FileDownloader::URLBufferStartNotify; // Request asynchronous download of the url providing an on-load callback. // As long as this step is guaranteed to be asynchronous, we can call // synchronously all other internal callbacks that eventually result in the // invocation of the user callback. The user code will not be reentered. pp::CompletionCallback onload_callback = callback_factory_.NewRequiredCallback(start_notify); int32_t pp_error = url_loader_.Open(url_request, onload_callback); PLUGIN_PRINTF(("FileDownloader::Open (pp_error=%"NACL_PRId32")\n", pp_error)); CHECK(pp_error == PP_OK_COMPLETIONPENDING); return true; } int32_t FileDownloader::GetPOSIXFileDescriptor() { if (!streaming_to_file()) { return NACL_NO_FILE_DESC; } // Use the trusted interface to get the file descriptor. if (file_io_trusted_interface_ == NULL) { return NACL_NO_FILE_DESC; } int32_t file_desc = file_io_trusted_interface_->GetOSFileDescriptor( file_reader_.pp_resource()); #if NACL_WINDOWS // Convert the Windows HANDLE from Pepper to a POSIX file descriptor. int32_t posix_desc = _open_osfhandle(file_desc, _O_RDWR | _O_BINARY); if (posix_desc == -1) { // Close the Windows HANDLE if it can't be converted. CloseHandle(reinterpret_cast<HANDLE>(file_desc)); return NACL_NO_FILE_DESC; } file_desc = posix_desc; #endif return file_desc; } int64_t FileDownloader::TimeSinceOpenMilliseconds() const { int64_t now = NaClGetTimeOfDayMicroseconds(); // If Open() wasn't called or we somehow return an earlier time now, just // return the 0 rather than worse nonsense values. if (open_time_ < 0 || now < open_time_) return 0; return (now - open_time_) / NACL_MICROS_PER_MILLI; } bool FileDownloader::InitialResponseIsValid(int32_t pp_error) { if (pp_error != PP_OK) { // Url loading failed. file_open_notify_callback_.Run(pp_error); return false; } // Process the response, validating the headers to confirm successful loading. pp::URLResponseInfo url_response(url_loader_.GetResponseInfo()); if (url_response.is_null()) { PLUGIN_PRINTF(( "FileDownloader::InitialResponseIsValid (url_response=NULL)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } // Note that URLs in the chrome-extension scheme produce different error // codes than other schemes. This is because chrome-extension URLs are // really a special kind of file scheme, and therefore do not produce HTTP // status codes. pp::Var full_url = url_response.GetURL(); if (!full_url.is_string()) { PLUGIN_PRINTF(( "FileDownloader::InitialResponseIsValid (url is not a string)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } bool status_ok = false; int32_t status_code = url_response.GetStatusCode(); switch (url_scheme_) { case SCHEME_CHROME_EXTENSION: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (chrome-extension " "response status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == kExtensionUrlRequestStatusOk); break; case SCHEME_DATA: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (data URI " "response status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == kDataUriRequestStatusOk); break; case SCHEME_OTHER: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (HTTP response " "status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == NACL_HTTP_STATUS_OK); break; } if (!status_ok) { file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } return true; } void FileDownloader::URLLoadStartNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLLoadStartNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (!InitialResponseIsValid(pp_error)) return; // Finish streaming the body providing an optional callback. pp::CompletionCallback onload_callback = callback_factory_.NewOptionalCallback( &FileDownloader::URLLoadFinishNotify); pp_error = url_loader_.FinishStreamingToFile(onload_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLLoadStartNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { // Call manually to free allocated memory and report errors. This calls // |file_open_notify_callback_| with |pp_error| as the parameter. onload_callback.Run(pp_error); } } void FileDownloader::URLLoadFinishNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (pp_error != PP_OK) { // Streaming failed. file_open_notify_callback_.Run(pp_error); return; } pp::URLResponseInfo url_response(url_loader_.GetResponseInfo()); // Validated on load. CHECK(url_response.GetStatusCode() == NACL_HTTP_STATUS_OK || url_response.GetStatusCode() == kExtensionUrlRequestStatusOk); // Record the full url from the response. pp::Var full_url = url_response.GetURL(); PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (full_url=%s)\n", full_url.DebugString().c_str())); if (!full_url.is_string()) { file_open_notify_callback_.Run(PP_ERROR_FAILED); return; } url_ = full_url.AsString(); // The file is now fully downloaded. pp::FileRef file(url_response.GetBodyAsFileRef()); if (file.is_null()) { PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (file=NULL)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return; } // Open the file providing an optional callback. pp::CompletionCallback onopen_callback = callback_factory_.NewOptionalCallback(&FileDownloader::FileOpenNotify); pp_error = file_reader_.Open(file, PP_FILEOPENFLAG_READ, onopen_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { // Call manually to free allocated memory and report errors. This calls // |file_open_notify_callback_| with |pp_error| as the parameter. onopen_callback.Run(pp_error); } } void FileDownloader::URLBufferStartNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLBufferStartNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (!InitialResponseIsValid(pp_error)) return; // Finish streaming the body asynchronously providing a callback. pp::CompletionCallback onread_callback = callback_factory_.NewOptionalCallback(&FileDownloader::URLReadBodyNotify); pp_error = url_loader_.ReadResponseBody(temp_buffer_, kTempBufferSize, onread_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLBufferStartNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { onread_callback.Run(pp_error); } } void FileDownloader::URLReadBodyNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLReadBodyNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (pp_error < PP_OK) { file_open_notify_callback_.Run(pp_error); } else if (pp_error == PP_OK) { FileOpenNotify(PP_OK); } else { buffer_.insert(buffer_.end(), temp_buffer_, temp_buffer_ + pp_error); pp::CompletionCallback onread_callback = callback_factory_.NewOptionalCallback( &FileDownloader::URLReadBodyNotify); pp_error = url_loader_.ReadResponseBody(temp_buffer_, kTempBufferSize, onread_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); if (!async_notify_ok) { onread_callback.Run(pp_error); } } } void FileDownloader::FileOpenNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::FileOpenNotify (pp_error=%"NACL_PRId32")\n", pp_error)); file_open_notify_callback_.Run(pp_error); } bool FileDownloader::streaming_to_file() const { return (flags_ & DOWNLOAD_TO_BUFFER) == 0; } bool FileDownloader::streaming_to_buffer() const { return (flags_ & DOWNLOAD_TO_BUFFER) == 1; } } // namespace plugin <commit_msg>One more time, remove unused var BUG= none TEST= try Review URL: http://codereview.chromium.org/7826035<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 "native_client/src/trusted/plugin/file_downloader.h" #include <stdio.h> #include <string> #include "native_client/src/include/portability_io.h" #include "native_client/src/shared/platform/nacl_check.h" #include "native_client/src/shared/platform/nacl_time.h" #include "native_client/src/trusted/plugin/plugin.h" #include "native_client/src/trusted/plugin/utility.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_file_io.h" #include "ppapi/cpp/file_io.h" #include "ppapi/cpp/file_ref.h" #include "ppapi/cpp/url_request_info.h" #include "ppapi/cpp/url_response_info.h" namespace { const int32_t kExtensionUrlRequestStatusOk = 200; const int32_t kDataUriRequestStatusOk = 0; } namespace plugin { void FileDownloader::Initialize(Plugin* instance) { PLUGIN_PRINTF(("FileDownloader::FileDownloader (this=%p)\n", static_cast<void*>(this))); CHECK(instance != NULL); CHECK(instance_ == NULL); // Can only initialize once. instance_ = instance; callback_factory_.Initialize(this); file_io_trusted_interface_ = static_cast<const PPB_FileIOTrusted*>( pp::Module::Get()->GetBrowserInterface(PPB_FILEIOTRUSTED_INTERFACE)); url_loader_trusted_interface_ = static_cast<const PPB_URLLoaderTrusted*>( pp::Module::Get()->GetBrowserInterface(PPB_URLLOADERTRUSTED_INTERFACE)); } bool FileDownloader::Open( const nacl::string& url, DownloadFlags flags, const pp::CompletionCallback& callback, PP_URLLoaderTrusted_StatusCallback progress_callback) { PLUGIN_PRINTF(("FileDownloader::Open (url=%s)\n", url.c_str())); if (callback.pp_completion_callback().func == NULL || instance_ == NULL || file_io_trusted_interface_ == NULL) return false; CHECK(instance_ != NULL); open_time_ = NaClGetTimeOfDayMicroseconds(); url_to_open_ = url; url_ = url; file_open_notify_callback_ = callback; flags_ = flags; buffer_.clear(); pp::URLRequestInfo url_request(instance_); do { // Reset the url loader and file reader. // Note that we have the only reference to the underlying objects, so // this will implicitly close any pending IO and destroy them. url_loader_ = pp::URLLoader(instance_); url_scheme_ = instance_->GetUrlScheme(url); bool grant_universal_access = false; if (url_scheme_ == SCHEME_CHROME_EXTENSION) { if (instance_->IsForeignMIMEType()) { // This NEXE is being used as a content type handler rather than // directly by an HTML document. In that case, the NEXE runs in the // security context of the content it is rendering and the NEXE itself // appears to be a cross-origin resource stored in a Chrome extension. // We request universal access during this load so that we can read the // NEXE. grant_universal_access = true; } } else if (url_scheme_ == SCHEME_DATA) { // TODO(elijahtaylor) Remove this when data URIs can be read without // universal access. if (streaming_to_buffer()) { grant_universal_access = true; } else { // Open is to invoke a callback on success or failure. Schedule // it asynchronously to follow PPAPI's convention and avoid reentrancy. pp::Core* core = pp::Module::Get()->core(); core->CallOnMainThread(0, callback, PP_ERROR_NOACCESS); PLUGIN_PRINTF(("FileDownloader::Open (pp_error=PP_ERROR_NOACCESS)\n")); return true; } } if (url_loader_trusted_interface_ != NULL) { if (grant_universal_access) { url_loader_trusted_interface_->GrantUniversalAccess( url_loader_.pp_resource()); } if (progress_callback != NULL) { url_request.SetRecordDownloadProgress(true); url_loader_trusted_interface_->RegisterStatusCallback( url_loader_.pp_resource(), progress_callback); } } // Prepare the url request. url_request.SetURL(url_); if (streaming_to_file()) { file_reader_ = pp::FileIO(instance_); url_request.SetStreamToFile(true); } } while (0); void (FileDownloader::*start_notify)(int32_t); if (streaming_to_file()) start_notify = &FileDownloader::URLLoadStartNotify; else start_notify = &FileDownloader::URLBufferStartNotify; // Request asynchronous download of the url providing an on-load callback. // As long as this step is guaranteed to be asynchronous, we can call // synchronously all other internal callbacks that eventually result in the // invocation of the user callback. The user code will not be reentered. pp::CompletionCallback onload_callback = callback_factory_.NewRequiredCallback(start_notify); int32_t pp_error = url_loader_.Open(url_request, onload_callback); PLUGIN_PRINTF(("FileDownloader::Open (pp_error=%"NACL_PRId32")\n", pp_error)); CHECK(pp_error == PP_OK_COMPLETIONPENDING); return true; } int32_t FileDownloader::GetPOSIXFileDescriptor() { if (!streaming_to_file()) { return NACL_NO_FILE_DESC; } // Use the trusted interface to get the file descriptor. if (file_io_trusted_interface_ == NULL) { return NACL_NO_FILE_DESC; } int32_t file_desc = file_io_trusted_interface_->GetOSFileDescriptor( file_reader_.pp_resource()); #if NACL_WINDOWS // Convert the Windows HANDLE from Pepper to a POSIX file descriptor. int32_t posix_desc = _open_osfhandle(file_desc, _O_RDWR | _O_BINARY); if (posix_desc == -1) { // Close the Windows HANDLE if it can't be converted. CloseHandle(reinterpret_cast<HANDLE>(file_desc)); return NACL_NO_FILE_DESC; } file_desc = posix_desc; #endif return file_desc; } int64_t FileDownloader::TimeSinceOpenMilliseconds() const { int64_t now = NaClGetTimeOfDayMicroseconds(); // If Open() wasn't called or we somehow return an earlier time now, just // return the 0 rather than worse nonsense values. if (open_time_ < 0 || now < open_time_) return 0; return (now - open_time_) / NACL_MICROS_PER_MILLI; } bool FileDownloader::InitialResponseIsValid(int32_t pp_error) { if (pp_error != PP_OK) { // Url loading failed. file_open_notify_callback_.Run(pp_error); return false; } // Process the response, validating the headers to confirm successful loading. pp::URLResponseInfo url_response(url_loader_.GetResponseInfo()); if (url_response.is_null()) { PLUGIN_PRINTF(( "FileDownloader::InitialResponseIsValid (url_response=NULL)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } // Note that URLs in the chrome-extension scheme produce different error // codes than other schemes. This is because chrome-extension URLs are // really a special kind of file scheme, and therefore do not produce HTTP // status codes. pp::Var full_url = url_response.GetURL(); if (!full_url.is_string()) { PLUGIN_PRINTF(( "FileDownloader::InitialResponseIsValid (url is not a string)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } bool status_ok = false; int32_t status_code = url_response.GetStatusCode(); switch (url_scheme_) { case SCHEME_CHROME_EXTENSION: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (chrome-extension " "response status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == kExtensionUrlRequestStatusOk); break; case SCHEME_DATA: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (data URI " "response status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == kDataUriRequestStatusOk); break; case SCHEME_OTHER: PLUGIN_PRINTF(("FileDownloader::InitialResponseIsValid (HTTP response " "status_code=%"NACL_PRId32")\n", status_code)); status_ok = (status_code == NACL_HTTP_STATUS_OK); break; } if (!status_ok) { file_open_notify_callback_.Run(PP_ERROR_FAILED); return false; } return true; } void FileDownloader::URLLoadStartNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLLoadStartNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (!InitialResponseIsValid(pp_error)) return; // Finish streaming the body providing an optional callback. pp::CompletionCallback onload_callback = callback_factory_.NewOptionalCallback( &FileDownloader::URLLoadFinishNotify); pp_error = url_loader_.FinishStreamingToFile(onload_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLLoadStartNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { // Call manually to free allocated memory and report errors. This calls // |file_open_notify_callback_| with |pp_error| as the parameter. onload_callback.Run(pp_error); } } void FileDownloader::URLLoadFinishNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (pp_error != PP_OK) { // Streaming failed. file_open_notify_callback_.Run(pp_error); return; } pp::URLResponseInfo url_response(url_loader_.GetResponseInfo()); // Validated on load. CHECK(url_response.GetStatusCode() == NACL_HTTP_STATUS_OK || url_response.GetStatusCode() == kExtensionUrlRequestStatusOk); // Record the full url from the response. pp::Var full_url = url_response.GetURL(); PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (full_url=%s)\n", full_url.DebugString().c_str())); if (!full_url.is_string()) { file_open_notify_callback_.Run(PP_ERROR_FAILED); return; } url_ = full_url.AsString(); // The file is now fully downloaded. pp::FileRef file(url_response.GetBodyAsFileRef()); if (file.is_null()) { PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (file=NULL)\n")); file_open_notify_callback_.Run(PP_ERROR_FAILED); return; } // Open the file providing an optional callback. pp::CompletionCallback onopen_callback = callback_factory_.NewOptionalCallback(&FileDownloader::FileOpenNotify); pp_error = file_reader_.Open(file, PP_FILEOPENFLAG_READ, onopen_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLLoadFinishNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { // Call manually to free allocated memory and report errors. This calls // |file_open_notify_callback_| with |pp_error| as the parameter. onopen_callback.Run(pp_error); } } void FileDownloader::URLBufferStartNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLBufferStartNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (!InitialResponseIsValid(pp_error)) return; // Finish streaming the body asynchronously providing a callback. pp::CompletionCallback onread_callback = callback_factory_.NewOptionalCallback(&FileDownloader::URLReadBodyNotify); pp_error = url_loader_.ReadResponseBody(temp_buffer_, kTempBufferSize, onread_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); PLUGIN_PRINTF(("FileDownloader::URLBufferStartNotify (async_notify_ok=%d)\n", async_notify_ok)); if (!async_notify_ok) { onread_callback.Run(pp_error); } } void FileDownloader::URLReadBodyNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::URLReadBodyNotify (pp_error=%" NACL_PRId32")\n", pp_error)); if (pp_error < PP_OK) { file_open_notify_callback_.Run(pp_error); } else if (pp_error == PP_OK) { FileOpenNotify(PP_OK); } else { buffer_.insert(buffer_.end(), temp_buffer_, temp_buffer_ + pp_error); pp::CompletionCallback onread_callback = callback_factory_.NewOptionalCallback( &FileDownloader::URLReadBodyNotify); pp_error = url_loader_.ReadResponseBody(temp_buffer_, kTempBufferSize, onread_callback); bool async_notify_ok = (pp_error == PP_OK_COMPLETIONPENDING); if (!async_notify_ok) { onread_callback.Run(pp_error); } } } void FileDownloader::FileOpenNotify(int32_t pp_error) { PLUGIN_PRINTF(("FileDownloader::FileOpenNotify (pp_error=%"NACL_PRId32")\n", pp_error)); file_open_notify_callback_.Run(pp_error); } bool FileDownloader::streaming_to_file() const { return (flags_ & DOWNLOAD_TO_BUFFER) == 0; } bool FileDownloader::streaming_to_buffer() const { return (flags_ & DOWNLOAD_TO_BUFFER) == 1; } } // namespace plugin <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <stdint.h> #include <trace/interface.H> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <fapi2.H> #include <fapi2/plat_hwp_invoker.H> //Targeting #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> #include <targeting/common/target.H> #include <p9_pm_get_poundv_bucket.H> #include <p9_setup_evid.H> //SBE #include <sbe/sbeif.H> #include <initservice/mboxRegs.H> #include <p9_frequency_buckets.H> using namespace TARGETING; namespace ISTEP_06 { void* call_host_voltage_config( void *io_pArgs ) { TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config entry" ); ISTEP_ERROR::IStepError l_stepError; errlHndl_t l_err = nullptr; Target * l_sys = nullptr; TargetHandleList l_procList; TargetHandleList l_eqList; fapi2::voltageBucketData_t l_voltageData; fapi2::ReturnCode l_rc; uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX uint32_t l_vddBootVoltage = 0; //ATTR_VDD_BOOT_VOLTAGE uint32_t l_vdnBootVoltage = 0; //ATTR_VDN_BOOT_VOLTAGE uint32_t l_vcsBootVoltage = 0; //ATTR_VCS_BOOT_VOLTAGE uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ bool l_firstPass = true; PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ); PredicateHwas l_predPres; l_predPres.present(true); PredicatePostfixExpr l_presentEqs; l_presentEqs.push(&l_eqFilter).push(&l_predPres).And(); do { // Get the system target targetService().getTopLevelTarget(l_sys); // Set the Nest frequency to whatever we boot with l_err = SBE::getBootNestFreq( l_nestFreq ); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config.C::" "Failed getting the boot nest frequency from the SBE"); break; } l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq ); // Get the child proc chips getChildAffinityTargets( l_procList, l_sys, CLASS_CHIP, TYPE_PROC ); // for each proc target for( const auto & l_proc : l_procList ) { // get the child EQ targets targetService().getAssociated( l_eqList, l_proc, TargetService::CHILD_BY_AFFINITY, TargetService::ALL, &l_presentEqs ); if( l_eqList.empty() ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "No children of proc 0x%x found to have type EQ", get_huid(l_proc)); /*@ * @errortype * @moduleid ISTEP::MOD_VOLTAGE_CONFIG * @reasoncode ISTEP::RC_NO_PRESENT_EQS * @userdata1 Parent PROC huid * @devdesc No present EQs found on processor * @custdesc A problem occurred during the IPL of the system. */ l_err = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, ISTEP::MOD_VOLTAGE_CONFIG, ISTEP::RC_NO_PRESENT_EQS, get_huid(l_proc), 0, true /*HB SW error*/ ); break; } // for each child EQ target for( const auto & l_eq : l_eqList ) { // cast to fapi2 target fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq ); // get the #V data for this EQ FAPI_INVOKE_HWP( l_err, p9_pm_get_poundv_bucket, l_fapiEq, l_voltageData); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_voltage_config::p9_pm_get_poundv_bucket"); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } // Save the voltage data for future comparison if( l_firstPass ) { l_nominalFreq = l_voltageData.nomFreq; l_floorFreq = l_voltageData.PSFreq; l_ceilingFreq = l_voltageData.turboFreq; l_ultraTurboFreq = l_voltageData.uTurboFreq; l_turboFreq = l_voltageData.turboFreq; l_vddBootVoltage = l_voltageData.VddPSVltg; l_vdnBootVoltage = l_voltageData.VddPSVltg; l_vcsBootVoltage = l_voltageData.VcsPSVltg; l_firstPass = false; } else { // save it to variable and compare agains other nomFreq // All of the buckets should report the same Nominal frequency if( l_nominalFreq != l_voltageData.nomFreq ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "NOMINAL FREQ MISMATCH! expected: %d actual: %d", l_nominalFreq, l_voltageData.nomFreq ); l_err = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, ISTEP::MOD_VOLTAGE_CONFIG, ISTEP::RC_NOMINAL_FREQ_MISMATCH, l_nominalFreq, l_voltageData.nomFreq, false ); l_err->addHwCallout(l_proc, HWAS::SRCI_PRIORITY_HIGH, HWAS::DECONFIG, HWAS::GARD_NULL ); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } // Floor frequency is the maximum of the Power Save Freqs l_floorFreq = (l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq; // Ceiling frequency is the minimum of the Turbo Freqs l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ? l_voltageData.turboFreq : l_ceilingFreq; // Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ? l_voltageData.uTurboFreq : l_ultraTurboFreq; // Turbo frequency is the minimum of the Turbo Freqs l_turboFreq = l_ceilingFreq; } } // EQ for-loop // set the approprate attributes on the processor l_proc->setAttr<ATTR_VDD_BOOT_VOLTAGE>( l_vddBootVoltage ); l_proc->setAttr<ATTR_VDN_BOOT_VOLTAGE>( l_vdnBootVoltage ); l_proc->setAttr<ATTR_VCS_BOOT_VOLTAGE>( l_vcsBootVoltage ); TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting VDD/VDN/VCS boot voltage for proc huid = 0x%x" " VDD = %d, VDN = %d, VCS = %d", get_huid(l_proc), l_vddBootVoltage, l_vdnBootVoltage, l_vcsBootVoltage ); // call p9_setup_evid for each processor fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc); FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_voltage_config::p9_setup_evid"); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } } // PROC for-loop // If we hit an error from p9_setup_evid, quit if( l_err ) { break; } // set the frequency system targets l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq ); l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq ); l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq ); l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq ); l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting System Frequency Attributes: " "Nominal = %d, Floor = %d, Ceiling = %d, " "Turbo = %d, UltraTurbo = %d", l_nominalFreq, l_floorFreq, l_ceilingFreq, l_turboFreq, l_ultraTurboFreq ); // Setup the remaining attributes that are based on PB/Nest SBE::setNestFreqAttributes(l_nestFreq); //NEST_PLL_BUCKET for( size_t l_bucket = 1; l_bucket <= NEST_PLL_FREQ_BUCKETS; l_bucket++ ) { // The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to // take zero-based indexing into account. if( NEST_PLL_FREQ_LIST[l_bucket-1] == l_nestFreq ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ATTR_NEST_PLL_BUCKET getting set to %x", l_bucket); l_sys->setAttr<TARGETING::ATTR_NEST_PLL_BUCKET>(l_bucket); break; } } } while( 0 ); if( l_err ) { // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config exit" ); return l_stepError.getErrorHandle(); } }; <commit_msg>Read VDN from appropriate #V field<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <stdint.h> #include <trace/interface.H> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <fapi2.H> #include <fapi2/plat_hwp_invoker.H> //Targeting #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> #include <targeting/common/target.H> #include <p9_pm_get_poundv_bucket.H> #include <p9_setup_evid.H> //SBE #include <sbe/sbeif.H> #include <initservice/mboxRegs.H> #include <p9_frequency_buckets.H> using namespace TARGETING; namespace ISTEP_06 { void* call_host_voltage_config( void *io_pArgs ) { TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config entry" ); ISTEP_ERROR::IStepError l_stepError; errlHndl_t l_err = nullptr; Target * l_sys = nullptr; TargetHandleList l_procList; TargetHandleList l_eqList; fapi2::voltageBucketData_t l_voltageData; fapi2::ReturnCode l_rc; uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX uint32_t l_vddBootVoltage = 0; //ATTR_VDD_BOOT_VOLTAGE uint32_t l_vdnBootVoltage = 0; //ATTR_VDN_BOOT_VOLTAGE uint32_t l_vcsBootVoltage = 0; //ATTR_VCS_BOOT_VOLTAGE uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ bool l_firstPass = true; PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ); PredicateHwas l_predPres; l_predPres.present(true); PredicatePostfixExpr l_presentEqs; l_presentEqs.push(&l_eqFilter).push(&l_predPres).And(); do { // Get the system target targetService().getTopLevelTarget(l_sys); // Set the Nest frequency to whatever we boot with l_err = SBE::getBootNestFreq( l_nestFreq ); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config.C::" "Failed getting the boot nest frequency from the SBE"); break; } l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq ); // Get the child proc chips getChildAffinityTargets( l_procList, l_sys, CLASS_CHIP, TYPE_PROC ); // for each proc target for( const auto & l_proc : l_procList ) { // get the child EQ targets targetService().getAssociated( l_eqList, l_proc, TargetService::CHILD_BY_AFFINITY, TargetService::ALL, &l_presentEqs ); if( l_eqList.empty() ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "No children of proc 0x%x found to have type EQ", get_huid(l_proc)); /*@ * @errortype * @moduleid ISTEP::MOD_VOLTAGE_CONFIG * @reasoncode ISTEP::RC_NO_PRESENT_EQS * @userdata1 Parent PROC huid * @devdesc No present EQs found on processor * @custdesc A problem occurred during the IPL of the system. */ l_err = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, ISTEP::MOD_VOLTAGE_CONFIG, ISTEP::RC_NO_PRESENT_EQS, get_huid(l_proc), 0, true /*HB SW error*/ ); break; } // for each child EQ target for( const auto & l_eq : l_eqList ) { // cast to fapi2 target fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq ); // get the #V data for this EQ FAPI_INVOKE_HWP( l_err, p9_pm_get_poundv_bucket, l_fapiEq, l_voltageData); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_voltage_config::p9_pm_get_poundv_bucket"); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } // Save the voltage data for future comparison if( l_firstPass ) { l_nominalFreq = l_voltageData.nomFreq; l_floorFreq = l_voltageData.PSFreq; l_ceilingFreq = l_voltageData.turboFreq; l_ultraTurboFreq = l_voltageData.uTurboFreq; l_turboFreq = l_voltageData.turboFreq; l_vddBootVoltage = l_voltageData.VddPSVltg; l_vdnBootVoltage = l_voltageData.VdnPbVltg; l_vcsBootVoltage = l_voltageData.VcsPSVltg; l_firstPass = false; } else { // save it to variable and compare agains other nomFreq // All of the buckets should report the same Nominal frequency if( l_nominalFreq != l_voltageData.nomFreq ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "NOMINAL FREQ MISMATCH! expected: %d actual: %d", l_nominalFreq, l_voltageData.nomFreq ); l_err = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, ISTEP::MOD_VOLTAGE_CONFIG, ISTEP::RC_NOMINAL_FREQ_MISMATCH, l_nominalFreq, l_voltageData.nomFreq, false ); l_err->addHwCallout(l_proc, HWAS::SRCI_PRIORITY_HIGH, HWAS::DECONFIG, HWAS::GARD_NULL ); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } // Floor frequency is the maximum of the Power Save Freqs l_floorFreq = (l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq; // Ceiling frequency is the minimum of the Turbo Freqs l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ? l_voltageData.turboFreq : l_ceilingFreq; // Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ? l_voltageData.uTurboFreq : l_ultraTurboFreq; // Turbo frequency is the minimum of the Turbo Freqs l_turboFreq = l_ceilingFreq; } } // EQ for-loop // set the approprate attributes on the processor l_proc->setAttr<ATTR_VDD_BOOT_VOLTAGE>( l_vddBootVoltage ); l_proc->setAttr<ATTR_VDN_BOOT_VOLTAGE>( l_vdnBootVoltage ); l_proc->setAttr<ATTR_VCS_BOOT_VOLTAGE>( l_vcsBootVoltage ); TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting VDD/VDN/VCS boot voltage for proc huid = 0x%x" " VDD = %d, VDN = %d, VCS = %d", get_huid(l_proc), l_vddBootVoltage, l_vdnBootVoltage, l_vcsBootVoltage ); // call p9_setup_evid for each processor fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc); FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS); if( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Error in call_host_voltage_config::p9_setup_evid"); // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); continue; } } // PROC for-loop // If we hit an error from p9_setup_evid, quit if( l_err ) { break; } // set the frequency system targets l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq ); l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq ); l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq ); l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq ); l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting System Frequency Attributes: " "Nominal = %d, Floor = %d, Ceiling = %d, " "Turbo = %d, UltraTurbo = %d", l_nominalFreq, l_floorFreq, l_ceilingFreq, l_turboFreq, l_ultraTurboFreq ); // Setup the remaining attributes that are based on PB/Nest SBE::setNestFreqAttributes(l_nestFreq); //NEST_PLL_BUCKET for( size_t l_bucket = 1; l_bucket <= NEST_PLL_FREQ_BUCKETS; l_bucket++ ) { // The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to // take zero-based indexing into account. if( NEST_PLL_FREQ_LIST[l_bucket-1] == l_nestFreq ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ATTR_NEST_PLL_BUCKET getting set to %x", l_bucket); l_sys->setAttr<TARGETING::ATTR_NEST_PLL_BUCKET>(l_bucket); break; } } } while( 0 ); if( l_err ) { // Create IStep error log and cross reference occurred error l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_voltage_config exit" ); return l_stepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "hnsw_index_saver.h" #include "hnsw_graph.h" #include <vespa/searchlib/util/bufferwriter.h> namespace search::tensor { namespace { size_t count_valid_link_arrays(const HnswGraph & graph) { size_t count(0); size_t num_nodes = graph.node_refs.size(); for (size_t i = 0; i < num_nodes; ++i) { auto node_ref = graph.node_refs[i].load_acquire(); if (node_ref.valid()) { count += graph.nodes.get(node_ref).size(); } } return count; } } HnswIndexSaver::MetaData::MetaData() : entry_docid(0), entry_level(-1), refs(), nodes() {} HnswIndexSaver::MetaData::~MetaData() = default; HnswIndexSaver::~HnswIndexSaver() = default; HnswIndexSaver::HnswIndexSaver(const HnswGraph &graph) : _graph_links(graph.links), _meta_data() { auto entry = graph.get_entry_node(); _meta_data.entry_docid = entry.docid; _meta_data.entry_level = entry.level; size_t num_nodes = graph.node_refs.size(); assert (num_nodes <= (std::numeric_limits<uint32_t>::max() - 1)); size_t link_array_count = count_valid_link_arrays(graph); assert (link_array_count <= std::numeric_limits<uint32_t>::max()); _meta_data.refs.reserve(link_array_count); _meta_data.nodes.reserve(num_nodes+1); for (size_t i = 0; i < num_nodes; ++i) { _meta_data.nodes.push_back(_meta_data.refs.size()); auto node_ref = graph.node_refs[i].load_acquire(); if (node_ref.valid()) { auto levels = graph.nodes.get(node_ref); for (const auto& links_ref : levels) { _meta_data.refs.push_back(links_ref.load_acquire()); } } } _meta_data.nodes.push_back(_meta_data.refs.size()); } void HnswIndexSaver::save(BufferWriter& writer) const { writer.write(&_meta_data.entry_docid, sizeof(uint32_t)); writer.write(&_meta_data.entry_level, sizeof(int32_t)); uint32_t num_nodes = _meta_data.nodes.size() - 1; writer.write(&num_nodes, sizeof(uint32_t)); for (uint32_t i(0); i < num_nodes; i++) { uint32_t offset = _meta_data.nodes[i]; uint32_t next_offset = _meta_data.nodes[i+1]; uint32_t num_levels = next_offset - offset; writer.write(&num_levels, sizeof(uint32_t)); for (; offset < next_offset; offset++) { auto links_ref = _meta_data.refs[offset]; if (links_ref.valid()) { vespalib::ConstArrayRef<uint32_t> link_array = _graph_links.get(links_ref); uint32_t num_links = link_array.size(); writer.write(&num_links, sizeof(uint32_t)); writer.write(link_array.cbegin(), sizeof(uint32_t)*num_links); } else { uint32_t num_links = 0; writer.write(&num_links, sizeof(uint32_t)); } } } writer.flush(); } } <commit_msg>Include limits when needed.<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "hnsw_index_saver.h" #include "hnsw_graph.h" #include <vespa/searchlib/util/bufferwriter.h> #include <limits> namespace search::tensor { namespace { size_t count_valid_link_arrays(const HnswGraph & graph) { size_t count(0); size_t num_nodes = graph.node_refs.size(); for (size_t i = 0; i < num_nodes; ++i) { auto node_ref = graph.node_refs[i].load_acquire(); if (node_ref.valid()) { count += graph.nodes.get(node_ref).size(); } } return count; } } HnswIndexSaver::MetaData::MetaData() : entry_docid(0), entry_level(-1), refs(), nodes() {} HnswIndexSaver::MetaData::~MetaData() = default; HnswIndexSaver::~HnswIndexSaver() = default; HnswIndexSaver::HnswIndexSaver(const HnswGraph &graph) : _graph_links(graph.links), _meta_data() { auto entry = graph.get_entry_node(); _meta_data.entry_docid = entry.docid; _meta_data.entry_level = entry.level; size_t num_nodes = graph.node_refs.size(); assert (num_nodes <= (std::numeric_limits<uint32_t>::max() - 1)); size_t link_array_count = count_valid_link_arrays(graph); assert (link_array_count <= std::numeric_limits<uint32_t>::max()); _meta_data.refs.reserve(link_array_count); _meta_data.nodes.reserve(num_nodes+1); for (size_t i = 0; i < num_nodes; ++i) { _meta_data.nodes.push_back(_meta_data.refs.size()); auto node_ref = graph.node_refs[i].load_acquire(); if (node_ref.valid()) { auto levels = graph.nodes.get(node_ref); for (const auto& links_ref : levels) { _meta_data.refs.push_back(links_ref.load_acquire()); } } } _meta_data.nodes.push_back(_meta_data.refs.size()); } void HnswIndexSaver::save(BufferWriter& writer) const { writer.write(&_meta_data.entry_docid, sizeof(uint32_t)); writer.write(&_meta_data.entry_level, sizeof(int32_t)); uint32_t num_nodes = _meta_data.nodes.size() - 1; writer.write(&num_nodes, sizeof(uint32_t)); for (uint32_t i(0); i < num_nodes; i++) { uint32_t offset = _meta_data.nodes[i]; uint32_t next_offset = _meta_data.nodes[i+1]; uint32_t num_levels = next_offset - offset; writer.write(&num_levels, sizeof(uint32_t)); for (; offset < next_offset; offset++) { auto links_ref = _meta_data.refs[offset]; if (links_ref.valid()) { vespalib::ConstArrayRef<uint32_t> link_array = _graph_links.get(links_ref); uint32_t num_links = link_array.size(); writer.write(&num_links, sizeof(uint32_t)); writer.write(link_array.cbegin(), sizeof(uint32_t)*num_links); } else { uint32_t num_links = 0; writer.write(&num_links, sizeof(uint32_t)); } } } writer.flush(); } } <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> #include <fstream> #include <iostream> #include <map> #include <seqan/basic.h> #include <seqan/find.h> #include <seqan/modifier.h> #include <seqan/sequence.h> #include <seqan/store.h> #include "curve_smoothing.h" #include "witio.h" #include "find_myers_ukkonen_reads.h" using namespace seqan; int main(int argc, char **argv) { if (argc != 3) return 1; DnaString contig = argv[1]; DnaString read = argv[2]; Finder<DnaString> finder(contig); Pattern<DnaString, MyersUkkonenReads> pattern(read, -length(read)); EditDistanceScore scoring; while (find(finder, pattern)) { if (endPosition(finder) < length(read)) continue; if (endPosition(finder) > length(contig)) continue; findBegin(finder, pattern, getScore(pattern)); std::cout << "end = " << endPosition(finder) << ", begin = " << beginPosition(finder) << ", last = " << endPosition(finder) - 1 << ", score = " << getScore(pattern) << std::endl; Align<Segment<DnaString, InfixSegment> > ali; appendValue(rows(ali), infix(finder)); appendValue(rows(ali), infix(read, 0, length(read))); int scoreValue = globalAlignment(ali, scoring, NeedlemanWunsch()); std::cout << "Global alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } return 0; } <commit_msg>Using Dna5 in do_search now.<commit_after>#include <cmath> #include <cstdio> #include <fstream> #include <iostream> #include <map> #include <seqan/basic.h> #include <seqan/find.h> #include <seqan/modifier.h> #include <seqan/sequence.h> #include <seqan/store.h> #include "curve_smoothing.h" #include "witio.h" #include "find_myers_ukkonen_reads.h" using namespace seqan; int main(int argc, char **argv) { if (argc != 3) return 1; Dna5String contig = argv[1]; Dna5String read = argv[2]; Finder<Dna5String> finder(contig); Pattern<Dna5String, MyersUkkonenReads> pattern(read, -length(read)); EditDistanceScore scoring; while (find(finder, pattern)) { if (endPosition(finder) < length(read)) continue; if (endPosition(finder) > length(contig)) continue; findBegin(finder, pattern, getScore(pattern)); std::cout << "end = " << endPosition(finder) << ", begin = " << beginPosition(finder) << ", last = " << endPosition(finder) - 1 << ", score = " << getScore(pattern) << std::endl; Align<Segment<Dna5String, InfixSegment> > ali; appendValue(rows(ali), infix(finder)); appendValue(rows(ali), infix(read, 0, length(read))); int scoreValue = globalAlignment(ali, scoring, NeedlemanWunsch()); std::cout << "Global alignment with score " << scoreValue << std::endl; std::cout << ali << std::endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2004, Index Data. * See the file LICENSE for details. * * $Id: zlint.cpp,v 1.8 2004-12-13 20:50:54 adam Exp $ */ #include <stdio.h> #include <stdarg.h> #include <yaz/comstack.h> #include <yaz/options.h> #include <yaz/otherinfo.h> #include <yaz/charneg.h> #include <yaz/log.h> #include <zlint.h> class Zlint_t { public: friend class Zlint; Zlint_t(Zlint_test *t); ~Zlint_t(); private: Zlint_test *m_t; Zlint_t *m_next; int m_test_number_sequence; int m_test_ok; int m_test_reported; }; Zlint::Zlint(IYaz_PDU_Observable *the_PDU_Observable) : Yaz_Z_Assoc(the_PDU_Observable) { m_PDU_Observable = the_PDU_Observable; m_host = 0; m_tests = 0; m_cur_test = 0; m_database = 0; } Zlint::~Zlint() { while (m_tests) { Zlint_t *t = m_tests; m_tests = t->m_next; delete t; } xfree(m_host); xfree(m_database); } void Zlint::set_host(const char *cp) { xfree(m_host); m_host = xstrdup(cp); client(m_host); timeout(30); const char *basep; cs_get_host_args(m_host, &basep); if (!basep || !*basep) basep = "Default"; xfree(m_database); m_database = xstrdup(basep); } void Zlint::timeoutNotify() { if (m_cur_test) { if (m_cur_test->m_t->recv_fail(this, 2) != TEST_FINISHED) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::failNotify() { if (m_cur_test) { if (m_cur_test->m_t->recv_fail(this, 1) != TEST_FINISHED) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::connectNotify() { if (m_cur_test) { if (m_cur_test->m_t->init(this) != TEST_FINISHED) return; } close_goto_next(); } void Zlint::recv_GDU(Z_GDU *gdu, int len) { if (m_cur_test) { int r = m_cur_test->m_t->recv_gdu(this, gdu); if (r == TEST_CONTINUE) return; if (r == TEST_REOPEN) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::close_goto_next() { close(); if (m_cur_test) m_cur_test = m_cur_test->m_next; if (m_cur_test) client(m_host); timeout(30); } IYaz_PDU_Observer *Zlint::sessionNotify( IYaz_PDU_Observable *the_PDU_Observable, int fd) { return 0; } Z_ReferenceId *Zlint::mk_refid(const char *buf, int len) { Z_ReferenceId *id = (Z_ReferenceId *) odr_malloc(odr_encode(), sizeof(*id)); id->size = id->len = len; id->buf = (unsigned char*) odr_malloc(odr_encode(), len); memcpy(id->buf, buf, len); return id; } int Zlint::initResponseGetVersion(Z_InitResponse *init) { int no = 0; int off = 0; int i; for (i = 0; i<12; i++) if (ODR_MASK_GET(init->protocolVersion, no)) { no = i+1; if (off) yaz_log(YLOG_WARN, "%sbad formatted version"); } else off = 1; return no; } void Zlint::add_test(Zlint_test *t) { Zlint_t **d = &m_tests; while (*d) d = &(*d)->m_next; *d = new Zlint_t(t); if (!m_cur_test) m_cur_test = m_tests; } void Zlint::msg_check_for(const char *fmt, ...) { m_cur_test->m_test_ok = 0; m_cur_test->m_test_number_sequence++; m_cur_test->m_test_reported = 0; va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf ("Checking %s .. ", buf); va_end(ap); } void Zlint::msg_check_info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf (" %s\n", buf); va_end(ap); } void Zlint::msg_check_ok() { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 1; m_cur_test->m_test_reported = 1; printf ("OK\n"); } } void Zlint::msg_check_fail(const char *fmt, ...) { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 0; m_cur_test->m_test_reported = 1; printf ("Fail\n"); } va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf (" %s\n", buf); va_end(ap); } void Zlint::msg_check_notapp() { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 2; m_cur_test->m_test_reported = 1; printf ("Unsupported\n"); } } void Zlint::getDatabase(char ***db, int *num) { *db = (char**) odr_malloc(odr_encode(), 2*sizeof(char *)); (*db)[0] = m_database; (*db)[1] = 0; *num = 1; } Zlint_t::Zlint_t(Zlint_test *t) { m_test_number_sequence = 0; m_test_ok = 0; m_test_reported = 0; m_t = t; m_next = 0; } Zlint_t::~Zlint_t() { delete m_t; } Zlint_code Zlint_test_simple::recv_fail(Zlint *z, int reason) { z->msg_check_fail("target closed connection"); return TEST_FINISHED; } <commit_msg>Remove yaz_log call<commit_after>/* * Copyright (c) 2004, Index Data. * See the file LICENSE for details. * * $Id: zlint.cpp,v 1.9 2005-05-17 20:33:57 adam Exp $ */ #include <stdio.h> #include <stdarg.h> #include <yaz/comstack.h> #include <yaz/options.h> #include <yaz/otherinfo.h> #include <yaz/charneg.h> #include <yaz/log.h> #include <zlint.h> class Zlint_t { public: friend class Zlint; Zlint_t(Zlint_test *t); ~Zlint_t(); private: Zlint_test *m_t; Zlint_t *m_next; int m_test_number_sequence; int m_test_ok; int m_test_reported; }; Zlint::Zlint(IYaz_PDU_Observable *the_PDU_Observable) : Yaz_Z_Assoc(the_PDU_Observable) { m_PDU_Observable = the_PDU_Observable; m_host = 0; m_tests = 0; m_cur_test = 0; m_database = 0; } Zlint::~Zlint() { while (m_tests) { Zlint_t *t = m_tests; m_tests = t->m_next; delete t; } xfree(m_host); xfree(m_database); } void Zlint::set_host(const char *cp) { xfree(m_host); m_host = xstrdup(cp); client(m_host); timeout(30); const char *basep; cs_get_host_args(m_host, &basep); if (!basep || !*basep) basep = "Default"; xfree(m_database); m_database = xstrdup(basep); } void Zlint::timeoutNotify() { if (m_cur_test) { if (m_cur_test->m_t->recv_fail(this, 2) != TEST_FINISHED) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::failNotify() { if (m_cur_test) { if (m_cur_test->m_t->recv_fail(this, 1) != TEST_FINISHED) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::connectNotify() { if (m_cur_test) { if (m_cur_test->m_t->init(this) != TEST_FINISHED) return; } close_goto_next(); } void Zlint::recv_GDU(Z_GDU *gdu, int len) { if (m_cur_test) { int r = m_cur_test->m_t->recv_gdu(this, gdu); if (r == TEST_CONTINUE) return; if (r == TEST_REOPEN) { close(); client(m_host); timeout(30); return; } } close_goto_next(); } void Zlint::close_goto_next() { close(); if (m_cur_test) m_cur_test = m_cur_test->m_next; if (m_cur_test) client(m_host); timeout(30); } IYaz_PDU_Observer *Zlint::sessionNotify( IYaz_PDU_Observable *the_PDU_Observable, int fd) { return 0; } Z_ReferenceId *Zlint::mk_refid(const char *buf, int len) { Z_ReferenceId *id = (Z_ReferenceId *) odr_malloc(odr_encode(), sizeof(*id)); id->size = id->len = len; id->buf = (unsigned char*) odr_malloc(odr_encode(), len); memcpy(id->buf, buf, len); return id; } int Zlint::initResponseGetVersion(Z_InitResponse *init) { int no = 0; int off = 0; int i; for (i = 0; i<12; i++) if (ODR_MASK_GET(init->protocolVersion, no)) { no = i+1; } else off = 1; return no; } void Zlint::add_test(Zlint_test *t) { Zlint_t **d = &m_tests; while (*d) d = &(*d)->m_next; *d = new Zlint_t(t); if (!m_cur_test) m_cur_test = m_tests; } void Zlint::msg_check_for(const char *fmt, ...) { m_cur_test->m_test_ok = 0; m_cur_test->m_test_number_sequence++; m_cur_test->m_test_reported = 0; va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf ("Checking %s .. ", buf); va_end(ap); } void Zlint::msg_check_info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf (" %s\n", buf); va_end(ap); } void Zlint::msg_check_ok() { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 1; m_cur_test->m_test_reported = 1; printf ("OK\n"); } } void Zlint::msg_check_fail(const char *fmt, ...) { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 0; m_cur_test->m_test_reported = 1; printf ("Fail\n"); } va_list ap; va_start(ap, fmt); char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); printf (" %s\n", buf); va_end(ap); } void Zlint::msg_check_notapp() { if (!m_cur_test->m_test_reported) { m_cur_test->m_test_ok = 2; m_cur_test->m_test_reported = 1; printf ("Unsupported\n"); } } void Zlint::getDatabase(char ***db, int *num) { *db = (char**) odr_malloc(odr_encode(), 2*sizeof(char *)); (*db)[0] = m_database; (*db)[1] = 0; *num = 1; } Zlint_t::Zlint_t(Zlint_test *t) { m_test_number_sequence = 0; m_test_ok = 0; m_test_reported = 0; m_t = t; m_next = 0; } Zlint_t::~Zlint_t() { delete m_t; } Zlint_code Zlint_test_simple::recv_fail(Zlint *z, int reason) { z->msg_check_fail("target closed connection"); return TEST_FINISHED; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) #define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680 #include <xalanc/PlatformSupport/ArenaBlockBase.hpp> #include <xalanc/Include/XalanMemMgrAutoPtr.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class ObjectType, #if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS) class SizeType> #else class SizeType = unsigned short> #endif class ReusableArenaBlock : public ArenaBlockBase<ObjectType, SizeType> { public: typedef ArenaBlockBase<ObjectType, SizeType> BaseClassType; typedef typename BaseClassType::size_type size_type; typedef ReusableArenaBlock<ObjectType, SizeType> ThisType; struct NextBlock { enum { VALID_OBJECT_STAMP = 0xffddffdd }; size_type next; const int verificationStamp; NextBlock( size_type _next): next(_next), verificationStamp(VALID_OBJECT_STAMP) { } bool isValidFor( size_type rightBorder ) const { return ( ( verificationStamp == int(VALID_OBJECT_STAMP)) && ( next <= rightBorder ) ) ? true : false ; } static NextBlock* cast(void* thePointer) { return reinterpret_cast<NextBlock*>(thePointer); } static const NextBlock* cast(const void* thePointer) { return reinterpret_cast<const NextBlock*>(thePointer); } }; /* * Construct an ArenaBlock of the specified size * of objects. * * @param theBlockSize The size of the block (the * number of objects it can contain). */ ReusableArenaBlock( MemoryManagerType& theManager, size_type theBlockSize) : BaseClassType(theManager, theBlockSize), m_firstFreeBlock(0), m_nextFreeBlock(0) { XALAN_STATIC_ASSERT(sizeof(ObjectType) >= sizeof(NextBlock)); for( size_type i = 0; i < this->m_blockSize; ++i ) { new (&this->m_objectBlock[i]) NextBlock(size_type(i + 1)); } } ~ReusableArenaBlock() { size_type removedObjects = 0; for (size_type i = 0; i < this->m_blockSize && removedObjects < this->m_objectCount; ++i) { NextBlock* const pStruct = NextBlock::cast(&this->m_objectBlock[i]); if ( isOccupiedBlock(pStruct) ) { this->m_objectBlock[i].~ObjectType(); ++removedObjects; } } } static ThisType* create( MemoryManagerType& theManager, size_type theBlockSize) { ThisType* theInstance; return XalanConstruct( theManager, theInstance, theManager, theBlockSize); } /* * Allocate a block. Once the object is constructed, you must call * commitAllocation(). * * @return a pointer to the new block. */ ObjectType* allocateBlock() { if ( this->m_objectCount == this->m_blockSize ) { assert ( this->m_firstFreeBlock == (this->m_blockSize + 1) ); return 0; } else { assert( this->m_objectCount < this->m_blockSize ); ObjectType* theResult = 0; assert ( this->m_firstFreeBlock <= this->m_blockSize ); assert ( this->m_nextFreeBlock <= this->m_blockSize ); // check if any part was allocated but not commited if(this->m_firstFreeBlock != this->m_nextFreeBlock) { // return the previously allocated block and wait for a commit theResult = this->m_objectBlock + this->m_firstFreeBlock; } else { theResult = this->m_objectBlock + this->m_firstFreeBlock; assert(size_type(theResult - this->m_objectBlock) < this->m_blockSize); this->m_nextFreeBlock = NextBlock::cast(theResult)->next; assert(NextBlock::cast(theResult)->isValidFor(this->m_blockSize)); assert(this->m_nextFreeBlock <= this->m_blockSize); ++this->m_objectCount; } return theResult; } } /* * Commit the previous allocation. * * @param theBlock the address that was returned by allocateBlock() */ void commitAllocation(ObjectType* /* theBlock */) { assert ( this->m_objectCount <= this->m_blockSize ); this->m_firstFreeBlock = this->m_nextFreeBlock; } /* * Destroy the object, and return the block to the free list. * The behavior is undefined if the object pointed to is not * owned by the block. * * @param theObject the address of the object. */ void destroyObject(ObjectType* theObject) { assert(theObject != 0); // check if any uncommited block is there, add it to the list if ( this->m_firstFreeBlock != this->m_nextFreeBlock ) { // Return it to the pool of free blocks void* const p = this->m_objectBlock + this->m_firstFreeBlock; new (p) NextBlock(this->m_nextFreeBlock); this->m_nextFreeBlock = this->m_firstFreeBlock; } assert(ownsObject(theObject) == true); assert(shouldDestroyBlock(theObject)); XalanDestroy(*theObject); new (theObject) NextBlock(this->m_firstFreeBlock); m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock); assert (this->m_firstFreeBlock <= this->m_blockSize); --this->m_objectCount; } /* * Determine if this block owns the specified object. Note * that even if the object address is within our block, this * call will return false if no object currently occupies the * block. See also ownsBlock(). * * @param theObject the address of the object. * @return true if we own the object, false if not. */ bool ownsObject(const ObjectType* theObject) const { assert ( theObject != 0 ); return isOccupiedBlock(NextBlock::cast(theObject)); } protected: /* * Determine if the block should be destroyed. Returns true, * unless the object is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block should be destroyed, false if not. */ bool shouldDestroyBlock(const ObjectType* theObject) const { assert(size_type(theObject - this->m_objectBlock) < this->m_blockSize); return !isOnFreeList(theObject); } bool isOccupiedBlock(const NextBlock* block) const { assert( block !=0 ); return !(this->ownsBlock(reinterpret_cast<const ObjectType*>(block)) && block->isValidFor(this->m_blockSize)); } private: // Not implemented... ReusableArenaBlock(const ReusableArenaBlock<ObjectType, SizeType>&); ReusableArenaBlock<ObjectType, SizeType>& operator=(const ReusableArenaBlock<ObjectType, SizeType>&); bool operator==(const ReusableArenaBlock<ObjectType, SizeType>&) const; /* * Determine if the block is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block is on the free list, false if not. */ bool isOnFreeList(const ObjectType* theObject) const { if ( this->m_objectCount == 0 ) { return false; } else { ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock; for (size_type i = 0; i < this->m_blockSize - this->m_objectCount; ++i) { assert(this->ownsBlock(pRunPtr)); if (pRunPtr == theObject) { return true; } else { NextBlock* const p = reinterpret_cast<NextBlock*>(pRunPtr); assert(p->isValidFor(this->m_blockSize)); pRunPtr = this->m_objectBlock + p->next; } } return false; } } // Data members... size_type m_firstFreeBlock; size_type m_nextFreeBlock; }; XALAN_CPP_NAMESPACE_END #endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) <commit_msg>Patch for XALANC-659.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) #define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680 #include <xalanc/PlatformSupport/ArenaBlockBase.hpp> #include <xalanc/Include/XalanMemMgrAutoPtr.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class ObjectType, #if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS) class SizeType> #else class SizeType = unsigned short> #endif class ReusableArenaBlock : public ArenaBlockBase<ObjectType, SizeType> { public: typedef ArenaBlockBase<ObjectType, SizeType> BaseClassType; typedef typename BaseClassType::size_type size_type; typedef ReusableArenaBlock<ObjectType, SizeType> ThisType; struct NextBlock { enum { VALID_OBJECT_STAMP = 0xffddffdd }; size_type next; const int verificationStamp; NextBlock( size_type _next): next(_next), verificationStamp(VALID_OBJECT_STAMP) { } bool isValidFor( size_type rightBorder ) const { return ( ( verificationStamp == int(VALID_OBJECT_STAMP)) && ( next <= rightBorder ) ) ? true : false ; } }; /* * Construct an ArenaBlock of the specified size * of objects. * * @param theBlockSize The size of the block (the * number of objects it can contain). */ ReusableArenaBlock( MemoryManagerType& theManager, size_type theBlockSize) : BaseClassType(theManager, theBlockSize), m_firstFreeBlock(0), m_nextFreeBlock(0) { XALAN_STATIC_ASSERT(sizeof(ObjectType) >= sizeof(NextBlock)); for( size_type i = 0; i < this->m_blockSize; ++i ) { new (&this->m_objectBlock[i]) NextBlock(size_type(i + 1)); } } ~ReusableArenaBlock() { size_type removedObjects = 0; for (size_type i = 0; i < this->m_blockSize && removedObjects < this->m_objectCount; ++i) { if ( isOccupiedBlock(&this->m_objectBlock[i]) ) { this->m_objectBlock[i].~ObjectType(); ++removedObjects; } } } static ThisType* create( MemoryManagerType& theManager, size_type theBlockSize) { ThisType* theInstance; return XalanConstruct( theManager, theInstance, theManager, theBlockSize); } /* * Allocate a block. Once the object is constructed, you must call * commitAllocation(). * * @return a pointer to the new block. */ ObjectType* allocateBlock() { if ( this->m_objectCount == this->m_blockSize ) { assert ( this->m_firstFreeBlock == (this->m_blockSize + 1) ); return 0; } else { assert( this->m_objectCount < this->m_blockSize ); ObjectType* theResult = 0; assert ( this->m_firstFreeBlock <= this->m_blockSize ); assert ( this->m_nextFreeBlock <= this->m_blockSize ); // check if any part was allocated but not commited if(this->m_firstFreeBlock != this->m_nextFreeBlock) { // return the previously allocated block and wait for a commit theResult = this->m_objectBlock + this->m_firstFreeBlock; } else { theResult = this->m_objectBlock + this->m_firstFreeBlock; assert(size_type(theResult - this->m_objectBlock) < this->m_blockSize); NextBlock* const theBlock = reinterpret_cast<NextBlock*>(theResult); this->m_nextFreeBlock = theBlock->next; assert(theBlock->isValidFor(this->m_blockSize)); assert(this->m_nextFreeBlock <= this->m_blockSize); ++this->m_objectCount; } return theResult; } } /* * Commit the previous allocation. * * @param theBlock the address that was returned by allocateBlock() */ void commitAllocation(ObjectType* /* theBlock */) { assert ( this->m_objectCount <= this->m_blockSize ); this->m_firstFreeBlock = this->m_nextFreeBlock; } /* * Destroy the object, and return the block to the free list. * The behavior is undefined if the object pointed to is not * owned by the block. * * @param theObject the address of the object. */ void destroyObject(ObjectType* theObject) { assert(theObject != 0); // check if any uncommited block is there, add it to the list if ( this->m_firstFreeBlock != this->m_nextFreeBlock ) { // Return it to the pool of free blocks void* const p = this->m_objectBlock + this->m_firstFreeBlock; new (p) NextBlock(this->m_nextFreeBlock); this->m_nextFreeBlock = this->m_firstFreeBlock; } assert(ownsObject(theObject) == true); assert(shouldDestroyBlock(theObject)); XalanDestroy(*theObject); new (theObject) NextBlock(this->m_firstFreeBlock); m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock); assert (this->m_firstFreeBlock <= this->m_blockSize); --this->m_objectCount; } /* * Determine if this block owns the specified object. Note * that even if the object address is within our block, this * call will return false if no object currently occupies the * block. See also ownsBlock(). * * @param theObject the address of the object. * @return true if we own the object, false if not. */ bool ownsObject(const ObjectType* theObject) const { assert ( theObject != 0 ); return isOccupiedBlock(theObject); } protected: /* * Determine if the block should be destroyed. Returns true, * unless the object is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block should be destroyed, false if not. */ bool shouldDestroyBlock(const ObjectType* theObject) const { assert(size_type(theObject - this->m_objectBlock) < this->m_blockSize); return !isOnFreeList(theObject); } bool isOccupiedBlock(const ObjectType* block) const { assert( block !=0 ); return !(this->ownsBlock(block) && reinterpret_cast<const NextBlock*>(block)->isValidFor(this->m_blockSize)); } private: // Not implemented... ReusableArenaBlock(const ReusableArenaBlock<ObjectType, SizeType>&); ReusableArenaBlock<ObjectType, SizeType>& operator=(const ReusableArenaBlock<ObjectType, SizeType>&); bool operator==(const ReusableArenaBlock<ObjectType, SizeType>&) const; /* * Determine if the block is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block is on the free list, false if not. */ bool isOnFreeList(const ObjectType* theObject) const { if ( this->m_objectCount == 0 ) { return false; } else { ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock; for (size_type i = 0; i < this->m_blockSize - this->m_objectCount; ++i) { assert(this->ownsBlock(pRunPtr)); if (pRunPtr == theObject) { return true; } else { NextBlock* const p = reinterpret_cast<NextBlock*>(pRunPtr); assert(p->isValidFor(this->m_blockSize)); pRunPtr = this->m_objectBlock + p->next; } } return false; } } // Data members... size_type m_firstFreeBlock; size_type m_nextFreeBlock; }; XALAN_CPP_NAMESPACE_END #endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) <|endoftext|>
<commit_before>#ifndef __avm_cxx #define __avm_cxx #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkVector.h" #include "itkImage.h" #include "itkImageRegionConstIterator.h" #include "itkGradientToMagnitudeImageFilter.h" #include "itkExceptionObject.h" #include <map> #include <iostream> #include <string> template < unsigned int NImageDimension, unsigned int NSpaceDimension, class ValueType > ValueType run_avm(const char * inputFileName, const char * outputFileName = 0) { /** Typedefs */ const unsigned int ImageDimension = NImageDimension; const unsigned int SpaceDimension = NSpaceDimension; typedef ValueType InputValueType; typedef itk::Vector<InputValueType, SpaceDimension> InputPixelType; typedef InputValueType OutputPixelType; typedef itk::Image<InputPixelType, ImageDimension> InputImageType; typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType; typedef typename OutputImageType::Pointer OutputImagePointer; typedef itk::ImageRegionConstIterator<OutputImageType> IteratorType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ImageFileWriter<OutputImageType> WriterType; typedef typename ReaderType::Pointer ReaderPointer; typedef typename WriterType::Pointer WriterPointer; typedef itk::GradientToMagnitudeImageFilter< InputImageType, OutputImageType> FilterType; typedef typename FilterType::Pointer FilterPointer; /** Create variables */ ReaderPointer reader = ReaderType::New(); WriterPointer writer = 0; FilterPointer filter = FilterType::New(); OutputImagePointer magnitudeImage = 0; /** Setup the pipeline */ reader->SetFileName(inputFileName); filter->SetInput( reader->GetOutput() ); magnitudeImage = filter->GetOutput(); /** Only write to disk if an outputFileName is given */ if (outputFileName) { if (std::string(outputFileName) != "") { writer = WriterType::New(); writer->SetFileName(outputFileName); writer->SetInput( magnitudeImage ); } } try { if (writer) { writer->Update(); } else { magnitudeImage->Update(); } } catch (itk::ExceptionObject & err) { std::cerr << err << std::endl; throw err; } /** Sum over the resulting image and divide by the number of pixels */ IteratorType iterator(magnitudeImage, magnitudeImage->GetLargestPossibleRegion() ); double sum = 0.0; unsigned long nrOfPixels = 0; for (iterator = iterator.Begin(); !iterator.IsAtEnd(); ++iterator) { sum += iterator.Value(); ++nrOfPixels; } ValueType averageVectorMagnitude = static_cast<ValueType>( sum / nrOfPixels ); return averageVectorMagnitude; } // end function run_avm void PrintUsageString(void) { std::cerr << "Calculate the average magnitude of the vectors in a vector image.\n\n" << "Usage:\n" << "AverageVectorMagnitude\n" << "\t-in InputVectorImageFileName\n" << "\t[-out OutputImageFileName]\n" << "\t-id ImageDimension\n" << "\t-sd SpaceDimension (the dimension of the vectors)\n" << std::endl; } int main(int argc, char** argv) { typedef std::map<std::string, std::string> ArgMapType; typedef float ValueType; ArgMapType argmap; std::string inputFileName(""); std::string outputFileName(""); std::string imageDimension(""); std::string spaceDimension(""); /** Fill the argument map */ for (unsigned int i = 1; i<argc; i+=2) { if ( (i+1) < argc) { argmap[ argv[i] ] = argv[i+1]; } else { argmap[ argv[i] ] = ""; } } /** Help needed? */ if (argmap.count("-h") || argmap.count("-help") || argmap.count("--help") ) { PrintUsageString(); return -1; } if ( argmap.count("-in") ) { inputFileName = argmap["-in"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } if ( argmap.count("-out") ) { outputFileName = argmap["-out"]; } if ( argmap.count("-id") ) { imageDimension = argmap["-id"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } if ( argmap.count("-sd") ) { spaceDimension = argmap["-sd"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } ValueType averageVectorMagnitude; if (imageDimension == "2") { if (spaceDimension == "2") { averageVectorMagnitude = run_avm<2,2,float>(inputFileName.c_str(), outputFileName.c_str() ); } else if (spaceDimension == "3") { averageVectorMagnitude = run_avm<2,3,float>(inputFileName.c_str(), outputFileName.c_str()); } } else if (imageDimension == "3") { if (spaceDimension == "2") { averageVectorMagnitude = run_avm<3,2,float>(inputFileName.c_str(), outputFileName.c_str()); } else if (spaceDimension == "3") { averageVectorMagnitude = run_avm<3,3,float>(inputFileName.c_str(), outputFileName.c_str()); } } std::cout << "The average magnitude of the vectors in image \"" << inputFileName << "\" is: " << averageVectorMagnitude << std::endl; if ( !outputFileName.empty() ) { std::cout << "The magnitude image is written as \"" << outputFileName << "\"" << std::endl; } return 0; } // end function main #endif // #ifndef __avm_cxx <commit_msg>ENH: fix unsigned int warnings<commit_after>#ifndef __avm_cxx #define __avm_cxx #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkVector.h" #include "itkImage.h" #include "itkImageRegionConstIterator.h" #include "itkGradientToMagnitudeImageFilter.h" #include "itkExceptionObject.h" #include <map> #include <iostream> #include <string> template < unsigned int NImageDimension, unsigned int NSpaceDimension, class ValueType > ValueType run_avm(const char * inputFileName, const char * outputFileName = 0) { /** Typedefs */ const unsigned int ImageDimension = NImageDimension; const unsigned int SpaceDimension = NSpaceDimension; typedef ValueType InputValueType; typedef itk::Vector<InputValueType, SpaceDimension> InputPixelType; typedef InputValueType OutputPixelType; typedef itk::Image<InputPixelType, ImageDimension> InputImageType; typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType; typedef typename OutputImageType::Pointer OutputImagePointer; typedef itk::ImageRegionConstIterator<OutputImageType> IteratorType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ImageFileWriter<OutputImageType> WriterType; typedef typename ReaderType::Pointer ReaderPointer; typedef typename WriterType::Pointer WriterPointer; typedef itk::GradientToMagnitudeImageFilter< InputImageType, OutputImageType> FilterType; typedef typename FilterType::Pointer FilterPointer; /** Create variables */ ReaderPointer reader = ReaderType::New(); WriterPointer writer = 0; FilterPointer filter = FilterType::New(); OutputImagePointer magnitudeImage = 0; /** Setup the pipeline */ reader->SetFileName(inputFileName); filter->SetInput( reader->GetOutput() ); magnitudeImage = filter->GetOutput(); /** Only write to disk if an outputFileName is given */ if (outputFileName) { if (std::string(outputFileName) != "") { writer = WriterType::New(); writer->SetFileName(outputFileName); writer->SetInput( magnitudeImage ); } } try { if (writer) { writer->Update(); } else { magnitudeImage->Update(); } } catch (itk::ExceptionObject & err) { std::cerr << err << std::endl; throw err; } /** Sum over the resulting image and divide by the number of pixels */ IteratorType iterator(magnitudeImage, magnitudeImage->GetLargestPossibleRegion() ); double sum = 0.0; unsigned long nrOfPixels = 0; for (iterator = iterator.Begin(); !iterator.IsAtEnd(); ++iterator) { sum += iterator.Value(); ++nrOfPixels; } ValueType averageVectorMagnitude = static_cast<ValueType>( sum / nrOfPixels ); return averageVectorMagnitude; } // end function run_avm void PrintUsageString(void) { std::cerr << "Calculate the average magnitude of the vectors in a vector image.\n\n" << "Usage:\n" << "AverageVectorMagnitude\n" << "\t-in InputVectorImageFileName\n" << "\t[-out OutputImageFileName]\n" << "\t-id ImageDimension\n" << "\t-sd SpaceDimension (the dimension of the vectors)\n" << std::endl; } int main(int argc, char** argv) { typedef std::map<std::string, std::string> ArgMapType; typedef float ValueType; ArgMapType argmap; std::string inputFileName(""); std::string outputFileName(""); std::string imageDimension(""); std::string spaceDimension(""); /** Fill the argument map */ for (unsigned int i = 1; i < static_cast<unsigned int>(argc); i+=2) { if ( (i+1) < static_cast<unsigned int>(argc)) { argmap[ argv[i] ] = argv[i+1]; } else { argmap[ argv[i] ] = ""; } } /** Help needed? */ if (argmap.count("-h") || argmap.count("-help") || argmap.count("--help") ) { PrintUsageString(); return -1; } if ( argmap.count("-in") ) { inputFileName = argmap["-in"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } if ( argmap.count("-out") ) { outputFileName = argmap["-out"]; } if ( argmap.count("-id") ) { imageDimension = argmap["-id"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } if ( argmap.count("-sd") ) { spaceDimension = argmap["-sd"]; } else { std::cerr << "Not enough arguments\n"; PrintUsageString(); return -1; } ValueType averageVectorMagnitude; if (imageDimension == "2") { if (spaceDimension == "2") { averageVectorMagnitude = run_avm<2,2,float>(inputFileName.c_str(), outputFileName.c_str() ); } else if (spaceDimension == "3") { averageVectorMagnitude = run_avm<2,3,float>(inputFileName.c_str(), outputFileName.c_str()); } } else if (imageDimension == "3") { if (spaceDimension == "2") { averageVectorMagnitude = run_avm<3,2,float>(inputFileName.c_str(), outputFileName.c_str()); } else if (spaceDimension == "3") { averageVectorMagnitude = run_avm<3,3,float>(inputFileName.c_str(), outputFileName.c_str()); } } std::cout << "The average magnitude of the vectors in image \"" << inputFileName << "\" is: " << averageVectorMagnitude << std::endl; if ( !outputFileName.empty() ) { std::cout << "The magnitude image is written as \"" << outputFileName << "\"" << std::endl; } return 0; } // end function main #endif // #ifndef __avm_cxx <|endoftext|>
<commit_before>#include <stdexcept> #include "map/filters/FloodFillFilter.h" FloodFillFilter::FloodFillFilter() { _x1 = 0; _y1 = 0; _x2 = LEVEL_MAX_WIDTH; _y2 = LEVEL_MAX_HEIGHT; _tile = WallTile; } void FloodFillFilter::apply(Level& level) { if(_x1 > _x2 || _y1 > _y2) { throw std::out_of_range("Start coordinates cannot exceed end coordinates"); } if(_x1 >= level.getWidth()) { _x1 = level.getWidth() - 1; } if(_x2 >= level.getWidth()) { _x2 = level.getWidth() - 1; } if(_y1 >= level.getHeight()) { _y1 = level.getHeight() - 1; } if(_y2 >= level.getHeight()) { _y2 = level.getHeight() - 1; } for(uint32_t x = _x1; x <= _x2; x++) { for(uint32_t y = _y1; y <= _y2; y++) { level.setTile(x, y, _tile); } } } void FloodFillFilter::setStart(uint32_t x, uint32_t y) { _x1 = x; _y1 = y; } void FloodFillFilter::setEnd(uint32_t x, uint32_t y) { _x2 = x; _y2 = y; } void FloodFillFilter::setTile(Tile tile) { _tile = tile; } <commit_msg>Added TODO note about LEVEL_MAX_* constants<commit_after>#include <stdexcept> #include "map/filters/FloodFillFilter.h" FloodFillFilter::FloodFillFilter() { _x1 = 0; _y1 = 0; /// @todo Is this an appropriate solution? _x2 = LEVEL_MAX_WIDTH; _y2 = LEVEL_MAX_HEIGHT; _tile = WallTile; } void FloodFillFilter::apply(Level& level) { if(_x1 > _x2 || _y1 > _y2) { throw std::out_of_range("Start coordinates cannot exceed end coordinates"); } if(_x1 >= level.getWidth()) { _x1 = level.getWidth() - 1; } if(_x2 >= level.getWidth()) { _x2 = level.getWidth() - 1; } if(_y1 >= level.getHeight()) { _y1 = level.getHeight() - 1; } if(_y2 >= level.getHeight()) { _y2 = level.getHeight() - 1; } for(uint32_t x = _x1; x <= _x2; x++) { for(uint32_t y = _y1; y <= _y2; y++) { level.setTile(x, y, _tile); } } } void FloodFillFilter::setStart(uint32_t x, uint32_t y) { _x1 = x; _y1 = y; } void FloodFillFilter::setEnd(uint32_t x, uint32_t y) { _x2 = x; _y2 = y; } void FloodFillFilter::setTile(Tile tile) { _tile = tile; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <Module.h> #include <Version.h> #include <machine/Network.h> #include <processor/Processor.h> #include <network-stack/Endpoint.h> #include <network-stack/TcpManager.h> #include <network-stack/RoutingTable.h> #include <network-stack/NetworkStack.h> #include <network-stack/ConnectionBasedEndpoint.h> class StringCallback : public Log::LogCallback { public: StringCallback() : m_Str() { } virtual void callback(const char *s) { m_Str += s; } virtual inline ~StringCallback() { } String &getStr() { return m_Str; } private: String m_Str; }; #define LISTEN_PORT 1234 StringCallback *pCallback = 0; int clientThread(void *p) { if(!p) return 0; ConnectionBasedEndpoint *pClient = reinterpret_cast<ConnectionBasedEndpoint*>(p); NOTICE("Got a client - state is " << pClient->state() << "."); // Wait for data from the client - block. if(!pClient->dataReady(true)) { WARNING("Client from IP: " << pClient->getRemoteIp().toString() << " wasn't a proper HTTP client."); pClient->close(); return 0; } // Read all incoming data from the client. Assume no nulls. /// \todo Wait until last 4 bytes are \r\n\r\n - that's the end of the HTTP header. String inputData(""); while(pClient->dataReady(false)) { char buff[512]; pClient->recv(reinterpret_cast<uintptr_t>(buff), 512, true, false); inputData += buff; } bool bHeadRequest = false; List<String*> firstLine = inputData.tokenise(' '); String operation = *firstLine.popFront(); if(!(operation == String("GET"))) { if(operation == String("HEAD")) bHeadRequest = true; else { NOTICE("Unsupported HTTP method: '" << operation << "'"); pClient->close(); return 0; } } bool bNotFound = false; String path = *firstLine.popFront(); if(!(path == String("/"))) bNotFound = true; // Got a heap of information now - prepare to return size_t code = bNotFound ? 404 : 200; NormalStaticString statusLine; statusLine = "HTTP/1.0 "; statusLine += code; statusLine += " "; statusLine += bNotFound ? "Not Found" : "OK"; // Build the response String response; response = statusLine; response += "\r\nContent-type: text/html"; response += "\r\n\r\n"; // Do we need data there? if(!bHeadRequest) { // Formulate data itself if(bNotFound) { response += "Error 404: Page not found."; } else { response += "<html><head><title>Pedigree - Live System Status Report</title></head><body>"; response += "<h1>Pedigree Live Status Report</h1>"; response += "<p>This is a live status report from a running Pedigree system.</p>"; response += "<h3>Current Build</h3><pre>"; { HugeStaticString str; str += "Pedigree - revision "; str += g_pBuildRevision; str += "<br />===========================<br />Built at "; str += g_pBuildTime; str += " by "; str += g_pBuildUser; str += " on "; str += g_pBuildMachine; str += "<br />Build flags: "; str += g_pBuildFlags; str += "<br />"; response += str; } response += "</pre>"; response += "<h3>Network Interfaces</h3>"; response += "<table border='1'><tr><th>Interface #</th><th>IP Address</th><th>Subnet Mask</th><th>Gateway</th><th>DNS Servers</th></tr>"; size_t i; for (i = 0; i < NetworkStack::instance().getNumDevices(); i++) { Network* card = NetworkStack::instance().getDevice(i); StationInfo info = card->getStationInfo(); // Interface number response += "<tr><td>"; TinyStaticString s; s.append(i); response += s; if(card == RoutingTable::instance().DefaultRoute()) response += " <b>(default route)</b>"; response += "</td>"; // IP address response += "<td>"; response += info.ipv4.toString(); response += "</td>"; // Subnet mask response += "<td>"; response += info.subnetMask.toString(); response += "</td>"; // Gateway response += "<td>"; response += info.gateway.toString(); response += "</td>"; // DNS servers response += "<td>"; if(!info.nDnsServers) response += "(none)"; else { for(size_t j = 0; j < info.nDnsServers; j++) { response += info.dnsServers[j].toString(); if((j + 1) < info.nDnsServers) response += "<br />"; } } response += "</td></tr>"; } response += "</table>"; response += "<h3>Kernel Log</h3>"; response += "<pre>"; response += pCallback->getStr(); response += "</pre>"; response += "</body></html>"; } } // Send to the client pClient->send(response.length(), reinterpret_cast<uintptr_t>(static_cast<const char*>(response))); // All done - close the connection pClient->close(); return 0; } int mainThread(void *p) { ConnectionBasedEndpoint *pEndpoint = static_cast<ConnectionBasedEndpoint*>(TcpManager::instance().getEndpoint(LISTEN_PORT, RoutingTable::instance().DefaultRoute())); pEndpoint->listen(); while(1) { ConnectionBasedEndpoint *pClient = static_cast<ConnectionBasedEndpoint*>(pEndpoint->accept()); if(!pClient) continue; new Thread(Processor::information().getCurrentThread()->getParent(), clientThread, pClient); } return 0; } static void init() { pCallback = new StringCallback(); Log::instance().installCallback(pCallback); new Thread(Processor::information().getCurrentThread()->getParent(), mainThread, 0); } static void destroy() { } MODULE_INFO("Status Server", &init, &destroy, "network-stack", "init"); <commit_msg>Fixed the status server to shut down the connection cleanly rather than completely drop it from the system.<commit_after>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <Module.h> #include <Version.h> #include <machine/Network.h> #include <processor/Processor.h> #include <network-stack/Endpoint.h> #include <network-stack/TcpManager.h> #include <network-stack/RoutingTable.h> #include <network-stack/NetworkStack.h> #include <network-stack/ConnectionBasedEndpoint.h> class StringCallback : public Log::LogCallback { public: StringCallback() : m_Str() { } virtual void callback(const char *s) { m_Str += s; } virtual inline ~StringCallback() { } String &getStr() { return m_Str; } private: String m_Str; }; #define LISTEN_PORT 1234 StringCallback *pCallback = 0; int clientThread(void *p) { if(!p) return 0; ConnectionBasedEndpoint *pClient = reinterpret_cast<ConnectionBasedEndpoint*>(p); NOTICE("Got a client - state is " << pClient->state() << "."); // Wait for data from the client - block. if(!pClient->dataReady(true)) { WARNING("Client from IP: " << pClient->getRemoteIp().toString() << " wasn't a proper HTTP client."); pClient->close(); return 0; } // Read all incoming data from the client. Assume no nulls. /// \todo Wait until last 4 bytes are \r\n\r\n - that's the end of the HTTP header. String inputData(""); while(pClient->dataReady(false)) { char buff[512]; pClient->recv(reinterpret_cast<uintptr_t>(buff), 512, true, false); inputData += buff; } // No longer want any content from the server pClient->shutdown(Endpoint::ShutReceiving); bool bHeadRequest = false; List<String*> firstLine = inputData.tokenise(' '); String operation = *firstLine.popFront(); if(!(operation == String("GET"))) { if(operation == String("HEAD")) bHeadRequest = true; else { NOTICE("Unsupported HTTP method: '" << operation << "'"); pClient->close(); return 0; } } bool bNotFound = false; String path = *firstLine.popFront(); if(!(path == String("/"))) bNotFound = true; // Got a heap of information now - prepare to return size_t code = bNotFound ? 404 : 200; NormalStaticString statusLine; statusLine = "HTTP/1.0 "; statusLine += code; statusLine += " "; statusLine += bNotFound ? "Not Found" : "OK"; // Build the response String response; response = statusLine; response += "\r\nContent-type: text/html"; response += "\r\n\r\n"; // Do we need data there? if(!bHeadRequest) { // Formulate data itself if(bNotFound) { response += "Error 404: Page not found."; } else { response += "<html><head><title>Pedigree - Live System Status Report</title></head><body>"; response += "<h1>Pedigree Live Status Report</h1>"; response += "<p>This is a live status report from a running Pedigree system.</p>"; response += "<h3>Current Build</h3><pre>"; { HugeStaticString str; str += "Pedigree - revision "; str += g_pBuildRevision; str += "<br />===========================<br />Built at "; str += g_pBuildTime; str += " by "; str += g_pBuildUser; str += " on "; str += g_pBuildMachine; str += "<br />Build flags: "; str += g_pBuildFlags; str += "<br />"; response += str; } response += "</pre>"; response += "<h3>Network Interfaces</h3>"; response += "<table border='1'><tr><th>Interface #</th><th>IP Address</th><th>Subnet Mask</th><th>Gateway</th><th>DNS Servers</th></tr>"; size_t i; for (i = 0; i < NetworkStack::instance().getNumDevices(); i++) { Network* card = NetworkStack::instance().getDevice(i); StationInfo info = card->getStationInfo(); // Interface number response += "<tr><td>"; TinyStaticString s; s.append(i); response += s; if(card == RoutingTable::instance().DefaultRoute()) response += " <b>(default route)</b>"; response += "</td>"; // IP address response += "<td>"; response += info.ipv4.toString(); response += "</td>"; // Subnet mask response += "<td>"; response += info.subnetMask.toString(); response += "</td>"; // Gateway response += "<td>"; response += info.gateway.toString(); response += "</td>"; // DNS servers response += "<td>"; if(!info.nDnsServers) response += "(none)"; else { for(size_t j = 0; j < info.nDnsServers; j++) { response += info.dnsServers[j].toString(); if((j + 1) < info.nDnsServers) response += "<br />"; } } response += "</td></tr>"; } response += "</table>"; response += "<h3>Kernel Log</h3>"; response += "<pre>"; response += pCallback->getStr(); response += "</pre>"; response += "</body></html>"; } } // Send to the client pClient->send(response.length(), reinterpret_cast<uintptr_t>(static_cast<const char*>(response))); // Nothing more to send, bring down our side of the connection pClient->shutdown(Endpoint::ShutSending); // Leave the endpoint to be cleaned up when the connection is shut down cleanly /// \todo Does it get cleaned up if we do this? return 0; } int mainThread(void *p) { ConnectionBasedEndpoint *pEndpoint = static_cast<ConnectionBasedEndpoint*>(TcpManager::instance().getEndpoint(LISTEN_PORT, RoutingTable::instance().DefaultRoute())); pEndpoint->listen(); while(1) { ConnectionBasedEndpoint *pClient = static_cast<ConnectionBasedEndpoint*>(pEndpoint->accept()); if(!pClient) continue; new Thread(Processor::information().getCurrentThread()->getParent(), clientThread, pClient); } return 0; } static void init() { pCallback = new StringCallback(); Log::instance().installCallback(pCallback); new Thread(Processor::information().getCurrentThread()->getParent(), mainThread, 0); } static void destroy() { } MODULE_INFO("Status Server", &init, &destroy, "network-stack", "init"); <|endoftext|>
<commit_before>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_joint_free_flyer_hpp__ #define __se3_joint_free_flyer_hpp__ #include "pinocchio/multibody/joint/joint-base.hpp" #include "pinocchio/multibody/constraint.hpp" namespace se3 { struct JointDataFreeFlyer; struct JointModelFreeFlyer; struct JointFreeFlyer { struct BiasZero { operator Motion () const { return Motion::Zero(); } }; // struct BiasZero friend const Motion & operator+ ( const Motion& v, const BiasZero&) { return v; } friend const Motion & operator+ ( const BiasZero&,const Motion& v) { return v; } struct ConstraintIdentity { SE3::Matrix6 se3Action(const SE3 & m) const { return m.toActionMatrix(); } struct TransposeConst { Force::Vector6 operator* (const Force & phi) { return phi.toVector(); } }; TransposeConst transpose() const { return TransposeConst(); } operator ConstraintXd () const { return ConstraintXd(SE3::Matrix6::Identity()); } }; // struct ConstraintIdentity template<typename D> friend Motion operator* (const ConstraintIdentity&, const Eigen::MatrixBase<D>& v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,6); return Motion(v); } }; // struct JointFreeFlyer /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */ Inertia::Matrix6 operator*( const Inertia& Y,const JointFreeFlyer::ConstraintIdentity & ) { return Y.matrix(); } /* [CRBA] MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */ template<typename D> const Eigen::MatrixBase<D> & operator*( const JointFreeFlyer::ConstraintIdentity::TransposeConst &, const Eigen::MatrixBase<D> & F ) { return F; } namespace internal { template<> struct ActionReturn<JointFreeFlyer::ConstraintIdentity > { typedef SE3::Matrix6 Type; }; } template<> struct traits<JointFreeFlyer> { typedef JointDataFreeFlyer JointData; typedef JointModelFreeFlyer JointModel; typedef JointFreeFlyer::ConstraintIdentity Constraint_t; typedef SE3 Transformation_t; typedef Motion Motion_t; typedef JointFreeFlyer::BiasZero Bias_t; typedef Eigen::Matrix<double,6,6> F_t; enum { NQ = 7, NV = 6 }; }; template<> struct traits<JointDataFreeFlyer> { typedef JointFreeFlyer Joint; }; template<> struct traits<JointModelFreeFlyer> { typedef JointFreeFlyer Joint; }; struct JointDataFreeFlyer : public JointDataBase<JointDataFreeFlyer> { typedef JointFreeFlyer Joint; SE3_JOINT_TYPEDEF; typedef Eigen::Matrix<double,6,6> Matrix6; typedef Eigen::Quaternion<double> Quaternion; typedef Eigen::Matrix<double,3,1> Vector3; Constraint_t S; Transformation_t M; Motion_t v; Bias_t c; F_t F; // TODO if not used anymore, clean F_t JointDataFreeFlyer() : M(1) { } }; struct JointModelFreeFlyer : public JointModelBase<JointModelFreeFlyer> { typedef JointFreeFlyer Joint; SE3_JOINT_TYPEDEF; JointData createData() const { return JointData(); } void calc( JointData& data, const Eigen::VectorXd & qs) const { Eigen::VectorXd::ConstFixedSegmentReturnType<NQ>::Type q = qs.segment<NQ>(idx_q()); const JointData::Quaternion quat(Eigen::Matrix<double,4,1> (q.tail <4> ())); // TODO data.M.rotation (quat.matrix()); data.M.translation (q.head<3>()); } void calc( JointData& data, const Eigen::VectorXd & qs, const Eigen::VectorXd & vs ) const { Eigen::VectorXd::ConstFixedSegmentReturnType<NQ>::Type q = qs.segment<NQ>(idx_q()); data.v = vs.segment<NV>(idx_v()); const JointData::Quaternion quat(Eigen::Matrix<double,4,1> (q.tail <4> ())); // TODO // data.M = SE3(quat.matrix(),q.head<3>()); data.M.rotation (quat.matrix()); data.M.translation (q.head<3>()); } }; } // namespace se3 #endif // ifndef __se3_joint_free_flyer_hpp__ <commit_msg>[C++] JointFreeFlyer is now CRTP<commit_after>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_joint_free_flyer_hpp__ #define __se3_joint_free_flyer_hpp__ #include "pinocchio/multibody/joint/joint-base.hpp" #include "pinocchio/multibody/constraint.hpp" namespace se3 { struct JointDataFreeFlyer; struct JointModelFreeFlyer; struct ConstraintIdentity; template <> struct traits< ConstraintIdentity > { typedef double Scalar_t; typedef Eigen::Matrix<double,3,1,0> Vector3; typedef Eigen::Matrix<double,4,1,0> Vector4; typedef Eigen::Matrix<double,6,1,0> Vector6; typedef Eigen::Matrix<double,3,3,0> Matrix3; typedef Eigen::Matrix<double,4,4,0> Matrix4; typedef Eigen::Matrix<double,6,6,0> Matrix6; typedef Matrix3 Angular_t; typedef Vector3 Linear_t; typedef Matrix6 ActionMatrix_t; typedef Eigen::Quaternion<double,0> Quaternion_t; typedef SE3Tpl<double,0> SE3; typedef ForceTpl<double,0> Force; typedef MotionTpl<double,0> Motion; typedef Symmetric3Tpl<double,0> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; typedef Eigen::Matrix<Scalar_t,1,1,0> JointMotion; typedef Eigen::Matrix<Scalar_t,1,1,0> JointForce; typedef Eigen::Matrix<Scalar_t,6,1> DenseBase; }; // traits ConstraintRevolute struct ConstraintIdentity : ConstraintBase < ConstraintIdentity > { SPATIAL_TYPEDEF_NO_TEMPLATE(ConstraintIdentity); enum { NV = 6, Options = 0 }; typedef traits<ConstraintIdentity>::JointMotion JointMotion; typedef traits<ConstraintIdentity>::JointForce JointForce; typedef traits<ConstraintIdentity>::DenseBase DenseBase; SE3::Matrix6 se3Action(const SE3 & m) const { return m.toActionMatrix(); } struct TransposeConst { Force::Vector6 operator* (const Force & phi) { return phi.toVector(); } }; TransposeConst transpose() const { return TransposeConst(); } operator ConstraintXd () const { return ConstraintXd(SE3::Matrix6::Identity()); } }; // struct ConstraintIdentity template<typename D> Motion operator* (const ConstraintIdentity&, const Eigen::MatrixBase<D>& v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,6); return Motion(v); } /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */ Inertia::Matrix6 operator*( const Inertia& Y,const ConstraintIdentity & ) { return Y.matrix(); } /* [CRBA] MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */ template<typename D> const Eigen::MatrixBase<D> & operator*( const ConstraintIdentity::TransposeConst &, const Eigen::MatrixBase<D> & F ) { return F; } namespace internal { template<> struct ActionReturn<ConstraintIdentity > { typedef SE3::Matrix6 Type; }; } struct JointFreeFlyer{ }; template<> struct traits<JointFreeFlyer> { typedef JointDataFreeFlyer JointData; typedef JointModelFreeFlyer JointModel; typedef ConstraintIdentity Constraint_t; typedef SE3 Transformation_t; typedef Motion Motion_t; typedef BiasZero Bias_t; typedef Eigen::Matrix<double,6,6> F_t; enum { NQ = 7, NV = 6 }; }; template<> struct traits<JointDataFreeFlyer> { typedef JointFreeFlyer Joint; }; template<> struct traits<JointModelFreeFlyer> { typedef JointFreeFlyer Joint; }; struct JointDataFreeFlyer : public JointDataBase<JointDataFreeFlyer> { typedef JointFreeFlyer Joint; SE3_JOINT_TYPEDEF; typedef Eigen::Matrix<double,6,6> Matrix6; typedef Eigen::Quaternion<double> Quaternion; typedef Eigen::Matrix<double,3,1> Vector3; Constraint_t S; Transformation_t M; Motion_t v; Bias_t c; F_t F; // TODO if not used anymore, clean F_t JointDataFreeFlyer() : M(1) { } }; struct JointModelFreeFlyer : public JointModelBase<JointModelFreeFlyer> { typedef JointFreeFlyer Joint; SE3_JOINT_TYPEDEF; JointData createData() const { return JointData(); } void calc( JointData& data, const Eigen::VectorXd & qs) const { Eigen::VectorXd::ConstFixedSegmentReturnType<NQ>::Type q = qs.segment<NQ>(idx_q()); const JointData::Quaternion quat(Eigen::Matrix<double,4,1> (q.tail <4> ())); // TODO data.M.rotation (quat.matrix()); data.M.translation (q.head<3>()); } void calc( JointData& data, const Eigen::VectorXd & qs, const Eigen::VectorXd & vs ) const { Eigen::VectorXd::ConstFixedSegmentReturnType<NQ>::Type q = qs.segment<NQ>(idx_q()); data.v = vs.segment<NV>(idx_v()); const JointData::Quaternion quat(Eigen::Matrix<double,4,1> (q.tail <4> ())); // TODO // data.M = SE3(quat.matrix(),q.head<3>()); data.M.rotation (quat.matrix()); data.M.translation (q.head<3>()); } }; } // namespace se3 #endif // ifndef __se3_joint_free_flyer_hpp__ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_freq.C /// @brief Calculate and save off DIMM frequencies /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP FW Owner: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <p9_mss_freq.H> // std lib #include <map> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/spd_decoder.H> #include <lib/spd/spd_factory.H> #include <lib/freq/cas_latency.H> #include <generic/memory/lib/utils/c_str.H> #include <lib/freq/cycle_time.H> #include <lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/utils/index.H> #include <lib/shared/mss_const.H> using fapi2::TARGET_TYPE_MCS; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::TARGET_TYPE_MCBIST; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Calculate and save off DIMM frequencies /// @param[in] i_target, the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target ) { // TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard // (if not impossible) to know the appropriate freq if we don't have information // for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as // there is no check for other freq's and we end up setting the chosen freq to // the default. // So for now, iterate over all the MCBIST. This isn't great as we do this work // twice for every MC. However, attribute access is cheap so this will suffice for // the time being. std::vector<uint64_t> l_min_dimm_freq(mss::MCS_PER_MC, 0); std::vector<uint64_t> l_desired_cas_latency(mss::MCS_PER_MC, 0); const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target); // If there are no DIMM, we can just get out. if (mss::count_dimm(l_mcbist) == 0) { FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist)); return FAPI2_RC_SUCCESS; } for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist)) { const auto l_index = mss::index(l_mcs); // Get cached decoder std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches; FAPI_TRY( mss::spd::populate_decoder_caches(l_mcs, l_factory_caches), "%s. Failed to populate decoder cache", mss::c_str(i_target) ); { // instantiation of class that calculates CL algorithm fapi2::ReturnCode l_rc; mss::cas_latency l_cas_latency( l_mcs, l_factory_caches, l_rc ); FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(i_target) ); if(l_cas_latency.iv_dimm_list_empty) { // Cannot fail out for an empty DIMM configuration, so default values are set FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.", mss::c_str(i_target) ); } else { // We set this to a non-0 so we avoid divide-by-zero errors in the conversions which // go from clocks to time (and vice versa.) We have other bugs if there was really // no MT/s determined and there really is a DIMM installed, so this is ok. // We pick the maximum frequency supported by the system as the default. l_min_dimm_freq[l_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666; uint64_t l_tCKmin = 0; // Find CAS latency using JEDEC algorithm FAPI_TRY( l_cas_latency.find_cl(l_desired_cas_latency[l_index], l_tCKmin) ); FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d", mss::c_str(i_target), l_desired_cas_latency[l_index], l_tCKmin); // Find dimm transfer speed from selected tCK FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_index]), "%s. Failed ps_to_freq()", mss::c_str(i_target) ); FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_index], mss::c_str(l_mcs)); FAPI_TRY(mss::select_supported_freq(l_mcs, l_min_dimm_freq[l_index]), "Failed select_supported_freq() for %s", mss::c_str(l_mcs)); FAPI_INF("%s. Selected DIMM speed from supported speeds: %d", mss::c_str(i_target), l_min_dimm_freq[l_index]); }// end else } // close scope FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency[l_index] ), "%s. Failed set_CL_attr()", mss::c_str(i_target) ); } // close for each mcs FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq), "%s. Failed set_freq_attrs()", mss::c_str(i_target) ); fapi_try_exit: return fapi2::current_err; }// p9_mss_freq }// extern C <commit_msg>Move find API to share among memory controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_freq.C /// @brief Calculate and save off DIMM frequencies /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP FW Owner: Brian Silver <bsilver@us.ibm.com> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <p9_mss_freq.H> // std lib #include <map> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/spd_decoder.H> #include <lib/spd/spd_factory.H> #include <lib/freq/cas_latency.H> #include <generic/memory/lib/utils/c_str.H> #include <lib/freq/cycle_time.H> #include <generic/memory/lib/utils/find.H> #include <lib/utils/count_dimm.H> #include <lib/utils/index.H> #include <lib/shared/mss_const.H> using fapi2::TARGET_TYPE_MCS; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::TARGET_TYPE_MCBIST; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Calculate and save off DIMM frequencies /// @param[in] i_target, the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_freq( const fapi2::Target<TARGET_TYPE_MCS>& i_target ) { // TODO RTC:161701 p9_mss_freq needs to be re-worked to work per-MC as it's hard // (if not impossible) to know the appropriate freq if we don't have information // for both MCS. Setting one to max freq doesn't work in the case of 0 DIMM as // there is no check for other freq's and we end up setting the chosen freq to // the default. // So for now, iterate over all the MCBIST. This isn't great as we do this work // twice for every MC. However, attribute access is cheap so this will suffice for // the time being. std::vector<uint64_t> l_min_dimm_freq(mss::MCS_PER_MC, 0); std::vector<uint64_t> l_desired_cas_latency(mss::MCS_PER_MC, 0); const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target); // If there are no DIMM, we can just get out. if (mss::count_dimm(l_mcbist) == 0) { FAPI_INF("Seeing no DIMM on %s, no freq to set", mss::c_str(l_mcbist)); return FAPI2_RC_SUCCESS; } for (const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(l_mcbist)) { const auto l_index = mss::index(l_mcs); // Get cached decoder std::vector< std::shared_ptr<mss::spd::decoder> > l_factory_caches; FAPI_TRY( mss::spd::populate_decoder_caches(l_mcs, l_factory_caches), "%s. Failed to populate decoder cache", mss::c_str(i_target) ); { // instantiation of class that calculates CL algorithm fapi2::ReturnCode l_rc; mss::cas_latency l_cas_latency( l_mcs, l_factory_caches, l_rc ); FAPI_TRY( l_rc, "%s. Failed to initialize cas_latency ctor", mss::c_str(i_target) ); if(l_cas_latency.iv_dimm_list_empty) { // Cannot fail out for an empty DIMM configuration, so default values are set FAPI_INF("%s. DIMM list is empty! Setting default values for CAS latency and DIMM speed.", mss::c_str(i_target) ); } else { // We set this to a non-0 so we avoid divide-by-zero errors in the conversions which // go from clocks to time (and vice versa.) We have other bugs if there was really // no MT/s determined and there really is a DIMM installed, so this is ok. // We pick the maximum frequency supported by the system as the default. l_min_dimm_freq[l_index] = fapi2::ENUM_ATTR_MSS_FREQ_MT2666; uint64_t l_tCKmin = 0; // Find CAS latency using JEDEC algorithm FAPI_TRY( l_cas_latency.find_cl(l_desired_cas_latency[l_index], l_tCKmin) ); FAPI_INF("%s. Result from CL algorithm, CL (nck): %d, tCK (ps): %d", mss::c_str(i_target), l_desired_cas_latency[l_index], l_tCKmin); // Find dimm transfer speed from selected tCK FAPI_TRY( mss::ps_to_freq(l_tCKmin, l_min_dimm_freq[l_index]), "%s. Failed ps_to_freq()", mss::c_str(i_target) ); FAPI_INF("DIMM speed from selected tCK (ps): %d for %s", l_min_dimm_freq[l_index], mss::c_str(l_mcs)); FAPI_TRY(mss::select_supported_freq(l_mcs, l_min_dimm_freq[l_index]), "Failed select_supported_freq() for %s", mss::c_str(l_mcs)); FAPI_INF("%s. Selected DIMM speed from supported speeds: %d", mss::c_str(i_target), l_min_dimm_freq[l_index]); }// end else } // close scope FAPI_TRY(mss::set_CL_attr(l_mcs, l_desired_cas_latency[l_index] ), "%s. Failed set_CL_attr()", mss::c_str(i_target) ); } // close for each mcs FAPI_TRY(mss::set_freq_attrs(l_mcbist, l_min_dimm_freq), "%s. Failed set_freq_attrs()", mss::c_str(i_target) ); fapi_try_exit: return fapi2::current_err; }// p9_mss_freq }// extern C <|endoftext|>
<commit_before>#include <cerrno> #include <Bull/Core/System/LastErrorImpl.hpp> namespace Bull { namespace prv { unsigned int LastErrorImpl::m_lastError = 0; /*! \brief Get the last error code sent by the OS * * \return Return the code of the last error * */ unsigned int LastErrorImpl::getCode() { return errno; } /*! \brief Get the message associated to the last error * * \return Return the message associated to the last error * */ String LastErrorImpl::getMessage() { return String(); } } } <commit_msg>[Core/System/LastError/Unix] Implement get message string<commit_after>#include <cerrno> #include <cstring> #include <Bull/Core/System/LastErrorImpl.hpp> namespace Bull { namespace prv { unsigned int LastErrorImpl::m_lastError = 0; /*! \brief Get the last error code sent by the OS * * \return Return the code of the last error * */ unsigned int LastErrorImpl::getCode() { m_lastError = errno; return m_lastError; } /*! \brief Get the message associated to the last error * * \return Return the message associated to the last error * */ String LastErrorImpl::getMessage() { if(m_lastError == 0) { m_lastError = errno; } if(m_lastError == 0) { return ""; } return strerror(m_lastError); } } } <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // The drive gear propels the tracked vehicle // // ============================================================================= #include "DriveGear.h" #include "assets/ChCylinderShape.h" #include "assets/ChTriangleMeshShape.h" #include "assets/ChTexture.h" #include "assets/ChColorAsset.h" // collision mesh #include "geometry/ChCTriangleMeshSoup.h" #include "utils/ChUtilsData.h" #include "utils/ChUtilsInputOutput.h" namespace chrono { // static variables const std::string DriveGear::m_meshName = "gear_mesh"; const std::string DriveGear::m_meshFile = utils::GetModelDataFile("gearMesh.obj"); const double DriveGear::m_mass = 436.7; const ChVector<> DriveGear::m_inertia(13.87, 12.22, 12.22); const double DriveGear::m_radius = 0.212; // to collision surface const double DriveGear::m_width = 0.259; const double DriveGear::m_widthGap = 0.189; // inner distance between cydliners const double DriveGear::m_shaft_inertia = 0.4; // connects to driveline DriveGear::DriveGear(const std::string& name, VisualizationType vis, CollisionType collide) : m_vis(vis), m_collide(collide) { // create the body, set the basic info m_gear = ChSharedPtr<ChBody>(new ChBody); m_gear->SetNameString(name+"_body"); m_gear->SetMass(m_mass); m_gear->SetInertiaXX(m_inertia); // create the revolute joint m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute); m_revolute->SetNameString(name+"_revolute"); // create the shaft components m_axle = ChSharedPtr<ChShaft>(new ChShaft); m_axle->SetNameString(name + "_axle"); m_axle->SetInertia(m_shaft_inertia ); // create the shaft to gear connection m_axle_to_gear = ChSharedPtr<ChShaftsBody>(new ChShaftsBody); m_axle_to_gear->SetNameString(name + "_axle_to_gear"); AddVisualization(); } void DriveGear::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChCoordsys<>& local_Csys) { // add any collision geometry AddCollisionGeometry(); // get the local frame in the absolute ref. frame ChFrame<> gear_to_abs(local_Csys); gear_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs()); // transform the drive gear body, add to system m_gear->SetPos(gear_to_abs.GetPos()); m_gear->SetRot(gear_to_abs.GetRot()); chassis->GetSystem()->Add(m_gear); // initialize the revolute joint, add to system // TODO: (check) may need to rotate the rotation axis m_revolute->Initialize(chassis, m_gear, ChCoordsys<>(gear_to_abs.GetPos(), gear_to_abs.GetRot()) ); chassis->GetSystem()->AddLink(m_revolute); // initialize the axle shaft and connection to the drive gear body, add both to the system chassis->GetSystem()->Add(m_axle); m_axle_to_gear->Initialize(m_axle, m_gear, VECT_Z); chassis->GetSystem()->Add(m_axle_to_gear); } void DriveGear::AddVisualization() { // Attach visualization asset switch (m_vis) { case VisualizationType::PRIMITIVES: { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().rad = m_radius; cyl->GetCylinderGeometry().p1 = ChVector<>(0, m_width / 2, 0); cyl->GetCylinderGeometry().p2 = ChVector<>(0, -m_width / 2, 0); m_gear->AddAsset(cyl); ChSharedPtr<ChTexture> tex(new ChTexture); tex->SetTextureFilename(GetChronoDataFile("bluwhite.png")); m_gear->AddAsset(tex); break; } case VisualizationType::MESH: { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(getMeshFile(), false, false); ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape); trimesh_shape->SetMesh(trimesh); trimesh_shape->SetName(getMeshName()); m_gear->AddAsset(trimesh_shape); ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.3f, 0.3f, 0.3f)); m_gear->AddAsset(mcolor); break; } } } void DriveGear::AddCollisionGeometry() { // add collision geometrey, if enabled. Warn if disabled m_gear->SetCollide(true); m_gear->GetCollisionModel()->ClearModel(); switch (m_collide) { case CollisionType::NONE: { m_gear->SetCollide(false); GetLog() << " !!! DriveGear " << m_gear->GetName() << " collision deactivated !!! \n\n"; } case CollisionType::PRIMITIVES: { // use a simple cylinder m_gear->GetCollisionModel()->AddCylinder(m_radius, m_radius, m_width, ChVector<>(),Q_from_AngAxis(CH_C_PI_2,VECT_X)); break; } case CollisionType::MESH: { // use a triangle mesh geometry::ChTriangleMeshSoup temp_trianglemesh; // TODO: fill the triangleMesh here with some track shoe geometry m_gear->GetCollisionModel()->SetSafeMargin(0.004); // inward safe margin m_gear->GetCollisionModel()->SetEnvelope(0.010); // distance of the outward "collision envelope" m_gear->GetCollisionModel()->ClearModel(); // is there an offset?? double shoelength = 0.2; ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass m_gear->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement); break; } case CollisionType::CONVEXHULL: { // use convex hulls, loaded from file ChStreamInAsciiFile chull_file(GetChronoDataFile("drive_gear.chulls").c_str()); // transform the collision geometry as needed double mangle = 45.0; // guess ChQuaternion<>rot; rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X); ChMatrix33<> rot_offset(rot); ChVector<> disp_offset(0,0,0); // no displacement offset m_gear->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset); break; } } // end switch // set collision family m_gear->GetCollisionModel()->SetFamily( (int)CollisionFam::GEARS ); // don't collide with other rolling elements or ground m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::HULL ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GEARS ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::WHEELS ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GROUND ); m_gear->GetCollisionModel()->BuildModel(); } } // end namespace chrono <commit_msg>two cylinders for visualization. and for addGeometry()<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // The drive gear propels the tracked vehicle // // ============================================================================= #include "DriveGear.h" #include "assets/ChCylinderShape.h" #include "assets/ChTriangleMeshShape.h" #include "assets/ChTexture.h" #include "assets/ChColorAsset.h" // collision mesh #include "geometry/ChCTriangleMeshSoup.h" #include "utils/ChUtilsData.h" #include "utils/ChUtilsInputOutput.h" namespace chrono { // static variables const std::string DriveGear::m_meshName = "gear_mesh"; const std::string DriveGear::m_meshFile = utils::GetModelDataFile("gearMesh.obj"); const double DriveGear::m_mass = 436.7; const ChVector<> DriveGear::m_inertia(13.87, 12.22, 12.22); const double DriveGear::m_radius = 0.212; // to collision surface const double DriveGear::m_width = 0.259; const double DriveGear::m_widthGap = 0.189; // inner distance between cydliners const double DriveGear::m_shaft_inertia = 0.4; // connects to driveline DriveGear::DriveGear(const std::string& name, VisualizationType vis, CollisionType collide) : m_vis(vis), m_collide(collide) { // create the body, set the basic info m_gear = ChSharedPtr<ChBody>(new ChBody); m_gear->SetNameString(name+"_body"); m_gear->SetMass(m_mass); m_gear->SetInertiaXX(m_inertia); // create the revolute joint m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute); m_revolute->SetNameString(name+"_revolute"); // create the shaft components m_axle = ChSharedPtr<ChShaft>(new ChShaft); m_axle->SetNameString(name + "_axle"); m_axle->SetInertia(m_shaft_inertia ); // create the shaft to gear connection m_axle_to_gear = ChSharedPtr<ChShaftsBody>(new ChShaftsBody); m_axle_to_gear->SetNameString(name + "_axle_to_gear"); AddVisualization(); } void DriveGear::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChCoordsys<>& local_Csys) { // add any collision geometry AddCollisionGeometry(); // get the local frame in the absolute ref. frame ChFrame<> gear_to_abs(local_Csys); gear_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs()); // transform the drive gear body, add to system m_gear->SetPos(gear_to_abs.GetPos()); m_gear->SetRot(gear_to_abs.GetRot()); chassis->GetSystem()->Add(m_gear); // initialize the revolute joint, add to system // TODO: (check) may need to rotate the rotation axis m_revolute->Initialize(chassis, m_gear, ChCoordsys<>(gear_to_abs.GetPos(), gear_to_abs.GetRot()) ); chassis->GetSystem()->AddLink(m_revolute); // initialize the axle shaft and connection to the drive gear body, add both to the system chassis->GetSystem()->Add(m_axle); m_axle_to_gear->Initialize(m_axle, m_gear, VECT_Z); chassis->GetSystem()->Add(m_axle_to_gear); } void DriveGear::AddVisualization() { // Attach visualization asset switch (m_vis) { case VisualizationType::PRIMITIVES: { // define the gear as two concentric cylinders with a gap ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().rad = m_radius; cyl->GetCylinderGeometry().p1 = ChVector<>(0, 0, m_width/2.0); cyl->GetCylinderGeometry().p2 = ChVector<>(0, 0, m_widthGap/2.0); m_gear->AddAsset(cyl); // second cylinder is a mirror of the first, about x-y plane cyl->GetCylinderGeometry().p1.z *= -1; cyl->GetCylinderGeometry().p2.z *= -1; m_gear->AddAsset(cyl); ChSharedPtr<ChTexture> tex(new ChTexture); tex->SetTextureFilename(GetChronoDataFile("bluwhite.png")); m_gear->AddAsset(tex); break; } case VisualizationType::MESH: { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(getMeshFile(), false, false); ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape); trimesh_shape->SetMesh(trimesh); trimesh_shape->SetName(getMeshName()); m_gear->AddAsset(trimesh_shape); ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.3f, 0.3f, 0.3f)); m_gear->AddAsset(mcolor); break; } } } void DriveGear::AddCollisionGeometry() { // add collision geometrey, if enabled. Warn if disabled m_gear->SetCollide(true); m_gear->GetCollisionModel()->ClearModel(); switch (m_collide) { case CollisionType::NONE: { m_gear->SetCollide(false); GetLog() << " !!! DriveGear " << m_gear->GetName() << " collision deactivated !!! \n\n"; } case CollisionType::PRIMITIVES: { double half_cyl_width = (m_width - m_widthGap)/2.0; ChVector<> shape_offset = ChVector<>(0, 0, half_cyl_width + m_widthGap/2.0); // use two simple cylinders. m_gear->GetCollisionModel()->AddCylinder(m_radius, m_radius, half_cyl_width, shape_offset, Q_from_AngAxis(CH_C_PI_2,VECT_X)); // mirror first cylinder about the x-y plane shape_offset.z *= -1; m_gear->GetCollisionModel()->AddCylinder(m_radius, m_radius, half_cyl_width, shape_offset, Q_from_AngAxis(CH_C_PI_2,VECT_X)); break; } case CollisionType::MESH: { // use a triangle mesh geometry::ChTriangleMeshSoup temp_trianglemesh; // TODO: fill the triangleMesh here with some track shoe geometry m_gear->GetCollisionModel()->SetSafeMargin(0.004); // inward safe margin m_gear->GetCollisionModel()->SetEnvelope(0.010); // distance of the outward "collision envelope" m_gear->GetCollisionModel()->ClearModel(); // is there an offset?? double shoelength = 0.2; ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass m_gear->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement); break; } case CollisionType::CONVEXHULL: { // use convex hulls, loaded from file ChStreamInAsciiFile chull_file(GetChronoDataFile("drive_gear.chulls").c_str()); // transform the collision geometry as needed double mangle = 45.0; // guess ChQuaternion<>rot; rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X); ChMatrix33<> rot_offset(rot); ChVector<> disp_offset(0,0,0); // no displacement offset m_gear->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset); break; } } // end switch // set collision family m_gear->GetCollisionModel()->SetFamily( (int)CollisionFam::GEARS ); // don't collide with other rolling elements or ground m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::HULL ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GEARS ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::WHEELS ); m_gear->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GROUND ); m_gear->GetCollisionModel()->BuildModel(); } } // end namespace chrono <|endoftext|>
<commit_before>/* * Copyright 2017, Flávio Keglevich * * 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. */ /** * Native implementation of the AWB (Automatic White Balance) algorithms * * Created by Flávio Keglevich on 09/12/2018. */ #include <jni.h> #include <omp.h> #include <android/log.h> extern "C" { JNIEXPORT void JNICALL Java_com_fkeglevich_rawdumper_raw_awb_GrayWorld_nativeCalculate(JNIEnv *env, jclass type, jint width, jint height, jint bpl, jbyteArray data_, jdoubleArray output_) { jbyte *data = env->GetByteArrayElements(data_, NULL); jshort *buffer = (jshort*) data; bpl /= 2; int t = 1; double cc0Avg = 0; double cc1Avg = 0; double cc2Avg = 0; double cc3Avg = 0; double linCc0; double linCc1; double linCc2; double linCc3; for (int row = 0; row < height; row += 2) { for (int col = 0; col < width; col += 2) { linCc0 = (buffer[row * bpl + col] - 64.0) / (1023.0 - 64.0); linCc1 = (buffer[row * bpl + col + 1] - 64.0) / (1023.0 - 64.0); linCc2 = (buffer[(row + 1) * bpl + col] - 64.0) / (1023.0 - 64.0); linCc3 = (buffer[(row + 1) * bpl + col + 1] - 64.0) / (1023.0 - 64.0); cc0Avg += (linCc0 - cc0Avg) / t; cc1Avg += (linCc1 - cc1Avg) / t; cc2Avg += (linCc2 - cc2Avg) / t; cc3Avg += (linCc3 - cc3Avg) / t; t++; } } env->ReleaseByteArrayElements(data_, data, 0); //MAJOR TODO: Update sensor pattern, black and white values //assuming GRBG: double G = (cc0Avg + cc3Avg) / 2; double R = cc1Avg / G; double B = cc2Avg / G; jdouble* output = env->GetDoubleArrayElements(output_, NULL); output[0] = R; output[1] = B; env->ReleaseDoubleArrayElements(output_, output, 0); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "R: %f", R); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "G: %f", 1.0); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "B: %f", B); } }<commit_msg>Minor changes<commit_after>/* * Copyright 2017, Flávio Keglevich * * 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. */ /** * Native implementation of the AWB (Automatic White Balance) algorithms * * Created by Flávio Keglevich on 09/12/2018. */ #include <jni.h> #include <omp.h> #include <android/log.h> extern "C" { JNIEXPORT void JNICALL Java_com_fkeglevich_rawdumper_raw_awb_GrayWorld_nativeCalculate(JNIEnv *env, jclass type, jint width, jint height, jint bpl, jbyteArray data_, jdoubleArray output_) { jbyte *data = env->GetByteArrayElements(data_, NULL); jshort *buffer = (jshort*) data; bpl /= 2; int t = 1; double cc0Avg = 0; double cc1Avg = 0; double cc2Avg = 0; double cc3Avg = 0; double linCc0; double linCc1; double linCc2; double linCc3; double blackLevel = 64.0; for (int row = 0; row < height; row += 2) { for (int col = 0; col < width; col += 2) { linCc0 = (buffer[row * bpl + col] - blackLevel) / (1023.0 - blackLevel); linCc1 = (buffer[row * bpl + col + 1] - blackLevel) / (1023.0 - blackLevel); linCc2 = (buffer[(row + 1) * bpl + col] - blackLevel) / (1023.0 - blackLevel); linCc3 = (buffer[(row + 1) * bpl + col + 1] - blackLevel) / (1023.0 - blackLevel); cc0Avg += (linCc0 - cc0Avg) / t; cc1Avg += (linCc1 - cc1Avg) / t; cc2Avg += (linCc2 - cc2Avg) / t; cc3Avg += (linCc3 - cc3Avg) / t; t++; } } env->ReleaseByteArrayElements(data_, data, 0); //MAJOR TODO: Update sensor pattern, black and white values //assuming GRBG: double G = (cc0Avg + cc3Avg) / 2; double R = cc1Avg / G; double B = cc2Avg / G; jdouble* output = env->GetDoubleArrayElements(output_, NULL); output[0] = R; output[1] = B; env->ReleaseDoubleArrayElements(output_, output, 0); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "R: %f", R); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "G: %f", 1.0); __android_log_print(ANDROID_LOG_DEBUG, "AWB", "B: %f", B); } }<|endoftext|>
<commit_before>#include <iostream> #include <array> #include <functional> #include <map> #include <set> #include <algorithm> #include "Vipper/Vipper.h" #include "Modules/Gameplay/Entities/CLevel.h" #include "Modules/Gameplay/Entities/CGameSession.h" #include "Modules/Gameplay/View/CGameplayView.h" namespace RunTheWorld { Vec2 project(Vec3 v, Vec3 camera) { float xz = (v.x - camera.x) / (1.0f - v.z + camera.z); float yz = (v.y - camera.y) / (1.0f - v.z + camera.z); Vec2 v2(320 + (xz * 640), 240 - (yz * 480)); return v2; } void CGameplayView::drawBackdropForHeading(int modulus, int zone) { getRenderer()->drawBitmapAt(-640 + modulus, 0, 640, 480, mBackdrop[zone]); getRenderer()->drawBitmapAt(modulus, 0, 640, 480, mBackdrop[zone]); } CGameplayView::CGameplayView(std::shared_ptr<CGameSession> session, std::shared_ptr<Vipper::IRenderer> renderer) : IView(renderer), mGameSession(session) { mBackdrop[0] = renderer->loadBitmap("res/3.png"); mBackdrop[1] = renderer->loadBitmap("res/2.png"); mBackdrop[2] = renderer->loadBitmap("res/1.png"); mCar[0][0] = renderer->loadBitmap("res/big0.png"); mCar[1][0] = renderer->loadBitmap("res/big1.png"); mCar[2][0] = renderer->loadBitmap("res/big2.png"); mCar[0][1] = renderer->loadBitmap("res/med0.png"); mCar[1][1] = renderer->loadBitmap("res/med1.png"); mCar[2][1] = renderer->loadBitmap("res/med2.png"); mCar[0][2] = renderer->loadBitmap("res/small0.png"); mCar[1][2] = renderer->loadBitmap("res/small1.png"); mCar[2][2] = renderer->loadBitmap("res/small2.png"); mOtherCar[0][0] = renderer->loadBitmap("res/obig0.png"); mOtherCar[1][0] = renderer->loadBitmap("res/obig1.png"); mOtherCar[2][0] = renderer->loadBitmap("res/obig2.png"); mOtherCar[0][1] = renderer->loadBitmap("res/omed0.png"); mOtherCar[1][1] = renderer->loadBitmap("res/omed1.png"); mOtherCar[2][1] = renderer->loadBitmap("res/omed2.png"); mOtherCar[0][2] = renderer->loadBitmap("res/osmall0.png"); mOtherCar[1][2] = renderer->loadBitmap("res/osmall1.png"); mOtherCar[2][2] = renderer->loadBitmap("res/osmall2.png"); mSmoke = renderer->loadBitmap("res/smoke.png"); mHitSound = renderer->loadSound("res/hit.wav"); mBrakeSound = renderer->loadSound("res/brake.wav"); mAccelerateSound = renderer->loadSound("res/accel.wav"); mUIFont = renderer->loadFont("res/albaregular.ttf", 15); } void CGameplayView::drawTextAt(std::pair<int, int> position, std::string text) { auto renderer = getRenderer(); renderer->drawTextAt(position.first, position.second, text, {0xFF, 0xFF, 0x00, 0xFF}, mUIFont); } void CGameplayView::drawGaugeAt(std::pair<int, int> position, int howFilled) { auto renderer = getRenderer(); renderer->drawSquare(position.first, position.second, 100, position.second + 20, {0, 0, 255, 255}); renderer->drawSquare(position.first, position.second, howFilled, position.second + 20, {255, 0, 0, 255}); } void CGameplayView::show() { auto game = this->mGameSession->getLevel(); auto renderer = getRenderer(); int numberOfStripeShades = 4; int completelyArbitraryCurveEasingFactor = 100; int shapeDelta = 0; int roadWidth = 1; char shape = game->track[game->elementIndex]; char slope = game->slopes[game->elementIndex]; auto camera = Vec3((game->x) / (640 * 2), 0.2f, (game->carSpeed / 500)); if (shape == ')') { shapeDelta = -1; } if (shape == '(') { shapeDelta = 1; } float slopeDelta = 0; if (slope == '/') { slopeDelta = 1; } if (slope == '\\') { slopeDelta = -1; } int distanceToCurrentShape = 0; if (game->distanceToNextElement > (CLevel::kSegmentLengthInMeters / 2)) { distanceToCurrentShape = (CLevel::kSegmentLengthInMeters - game->distanceToNextElement); } else { distanceToCurrentShape = (game->distanceToNextElement); } int halfScreenHeight = 480 / 2; auto slopeAddedLines = (2 * CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta); int modulus = static_cast<int>(game->mHeading * 640) % 640; while (modulus < 0) { modulus += 640; } int shadingStripesCount = 0; // drawBackdropForHeading( modulus, game->zone ); renderer->drawSquare(0, halfScreenHeight - slopeAddedLines, 640, 480, {0, 64, 0, 255}); renderer->drawSquare(0, 0, 640, halfScreenHeight - slopeAddedLines, {0, 0, 0, 255}); Vec2 previousLeft(-1, -1); Vec2 previousRight(-1, -1); shadingStripesCount = 0; float initialSlope = CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta; float currentStripeHeight = initialSlope; float stripeHeightDelta = (-initialSlope) / 480.0f; for (int y = halfScreenHeight; y > -1; y--) { shadingStripesCount = (shadingStripesCount + 1) % 1024; currentStripeHeight = initialSlope + ((2.0f * (halfScreenHeight - y)) * stripeHeightDelta); float curve = (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * shapeDelta * y * y / completelyArbitraryCurveEasingFactor; auto leftPoint = project(Vec3(-(roadWidth / 2.0f) + curve, -0.5f + currentStripeHeight, -y), camera); auto rightPoint = project(Vec3((roadWidth / 2.0f) + curve, -0.5f + currentStripeHeight, -y), camera); //if it's valid if (previousLeft.y < 0) { previousLeft = leftPoint; previousRight = rightPoint; } int count = (-shadingStripesCount + static_cast<long>(game->distanceRan)) % numberOfStripeShades; renderer->fill(leftPoint.x, rightPoint.x, leftPoint.y, previousLeft.x, previousRight.x, previousLeft.y, {255 * (count + 10) / 20, 255 * (count + 10) / 20, 255 * (count + 10) / 20, 255}); previousLeft = leftPoint; previousRight = rightPoint; } initialSlope = CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta; stripeHeightDelta = (-initialSlope) / 480; auto cars = game->getCarsAhead(1024); auto playerLane = (game->x) / 640; for (auto foe : cars) { auto y = std::get<0>(foe) - game->distanceRan; float curve = (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * shapeDelta * y * y / completelyArbitraryCurveEasingFactor; auto lane = std::get<1>(foe); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - y + 1)) * stripeHeightDelta); auto carProjection0 = project(Vec3(curve + lane - 0.2f, -1 + currentStripeHeight, -y + 0), camera); auto carProjection1 = project(Vec3(curve + lane + 0.2f, -1 + currentStripeHeight, -y + 0), camera); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - y - 1)) * stripeHeightDelta); auto carProjection2 = project(Vec3(curve + lane - 0.2f, -1 + currentStripeHeight, -y - 1), camera); auto carProjection3 = project(Vec3(curve + lane + 0.2f, -1 + currentStripeHeight, -y - 1), camera); int carSprite = (lane + 1) + 1; int carSize = 0; int sizeX = 32; int sizeY = 8; if (y <= 5) { carSize = 0; sizeX = 128; sizeY = 64; } else if (5 <= y && y <= 25) { carSize = 1; sizeX = 64; sizeY = 32; } else if (25 <= y && y <= 75) { carSize = 2; sizeX = 32; sizeY = 16; } else { continue; } auto centerX = carProjection0.x + ((carProjection1.x - carProjection0.x) / 2); auto centerY = carProjection0.y + ((carProjection2.y - carProjection0.y) / 2); renderer->fill(carProjection0.x, carProjection1.x, carProjection0.y, carProjection2.x, carProjection3.x, centerY, {0, 0, 0, 0}); renderer->drawBitmapAt(centerX - (sizeX / 2), centerY - (sizeY / 2), sizeX, sizeY, mOtherCar[carSprite][carSize]); } { auto lane = (game->x) / 640; currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - 4)) * stripeHeightDelta); auto carProjection2 = project(Vec3(lane - 0.2f, -1 + currentStripeHeight, -2 - 1), camera); auto carProjection3 = project(Vec3(lane + 0.2f, -1 + currentStripeHeight, -2 - 1), camera); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - 2.1)) * stripeHeightDelta); auto carProjection0 = project(Vec3(lane - 0.2f, -1 + currentStripeHeight, -2), camera); auto carProjection1 = project(Vec3(lane + 0.2f, -1 + currentStripeHeight, -2), camera); int black[3] = {0, 0, 0}; auto centerX = carProjection0.x + ((carProjection1.x - carProjection0.x) / 2); auto centerY = carProjection0.y + ((carProjection2.y - carProjection0.y) / 2); int carSprite = (lane + 1) + 1; renderer->fill(carProjection0.x, carProjection1.x, carProjection0.y, carProjection2.x, carProjection3.x, centerY, {0, 0, 0, 0}); renderer->drawBitmapAt(centerX - 64, centerY - 32, 128, 32, mCar[carSprite][0]); if (game->smoking) { renderer->drawBitmapAt(centerX - 64, centerY, 100, 33, mSmoke); } } if (game->hit) { renderer->playSound(mHitSound); game->hit = false; } if (game->brake) { renderer->playSound(mBrakeSound); game->brake = false; } if (game->accel) { renderer->playSound(mAccelerateSound); game->accel = false; } } void CGameplayView::onClick(std::pair<int, int> position) { if (position.first > 420) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kRight); } else if (position.first < 210) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kLeft); } if (position.second > 320) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kDown); } else if (position.second < 160) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kUp); } } void CGameplayView::onKeyUp(Vipper::ECommand keyCode) { this->mGameSession->getLevel()->onKeyUp(keyCode); } void CGameplayView::onKeyDown(Vipper::ECommand keyCode) { this->mGameSession->getLevel()->onKeyDown(keyCode); } } <commit_msg>Simplify calculations, despite still being slow on SX machines<commit_after>#include <iostream> #include <array> #include <functional> #include <map> #include <set> #include <algorithm> #include "Vipper/Vipper.h" #include "Modules/Gameplay/Entities/CLevel.h" #include "Modules/Gameplay/Entities/CGameSession.h" #include "Modules/Gameplay/View/CGameplayView.h" namespace RunTheWorld { Vec2 project(Vec3 v, Vec3 camera) { float xz = (v.x - camera.x) / (1.0f - v.z + camera.z); float yz = (v.y - camera.y) / (1.0f - v.z + camera.z); Vec2 v2(320 + (xz * 640), 240 - (yz * 480)); return v2; } void CGameplayView::drawBackdropForHeading(int modulus, int zone) { getRenderer()->drawBitmapAt(-640 + modulus, 0, 640, 480, mBackdrop[zone]); getRenderer()->drawBitmapAt(modulus, 0, 640, 480, mBackdrop[zone]); } CGameplayView::CGameplayView(std::shared_ptr<CGameSession> session, std::shared_ptr<Vipper::IRenderer> renderer) : IView(renderer), mGameSession(session) { mBackdrop[0] = renderer->loadBitmap("res/3.png"); mBackdrop[1] = renderer->loadBitmap("res/2.png"); mBackdrop[2] = renderer->loadBitmap("res/1.png"); mCar[0][0] = renderer->loadBitmap("res/big0.png"); mCar[1][0] = renderer->loadBitmap("res/big1.png"); mCar[2][0] = renderer->loadBitmap("res/big2.png"); mCar[0][1] = renderer->loadBitmap("res/med0.png"); mCar[1][1] = renderer->loadBitmap("res/med1.png"); mCar[2][1] = renderer->loadBitmap("res/med2.png"); mCar[0][2] = renderer->loadBitmap("res/small0.png"); mCar[1][2] = renderer->loadBitmap("res/small1.png"); mCar[2][2] = renderer->loadBitmap("res/small2.png"); mOtherCar[0][0] = renderer->loadBitmap("res/obig0.png"); mOtherCar[1][0] = renderer->loadBitmap("res/obig1.png"); mOtherCar[2][0] = renderer->loadBitmap("res/obig2.png"); mOtherCar[0][1] = renderer->loadBitmap("res/omed0.png"); mOtherCar[1][1] = renderer->loadBitmap("res/omed1.png"); mOtherCar[2][1] = renderer->loadBitmap("res/omed2.png"); mOtherCar[0][2] = renderer->loadBitmap("res/osmall0.png"); mOtherCar[1][2] = renderer->loadBitmap("res/osmall1.png"); mOtherCar[2][2] = renderer->loadBitmap("res/osmall2.png"); mSmoke = renderer->loadBitmap("res/smoke.png"); mHitSound = renderer->loadSound("res/hit.wav"); mBrakeSound = renderer->loadSound("res/brake.wav"); mAccelerateSound = renderer->loadSound("res/accel.wav"); mUIFont = renderer->loadFont("res/albaregular.ttf", 15); } void CGameplayView::drawTextAt(std::pair<int, int> position, std::string text) { auto renderer = getRenderer(); renderer->drawTextAt(position.first, position.second, text, {0xFF, 0xFF, 0x00, 0xFF}, mUIFont); } void CGameplayView::drawGaugeAt(std::pair<int, int> position, int howFilled) { auto renderer = getRenderer(); renderer->drawSquare(position.first, position.second, 100, position.second + 20, {0, 0, 255, 255}); renderer->drawSquare(position.first, position.second, howFilled, position.second + 20, {255, 0, 0, 255}); } void CGameplayView::show() { auto game = this->mGameSession->getLevel(); auto renderer = getRenderer(); int numberOfStripeShades = 4; int completelyArbitraryCurveEasingFactor = 100; int shapeDelta = 0; char shape = game->track[game->elementIndex]; char slope = game->slopes[game->elementIndex]; Vec3 camera = Vec3((game->x) / (640 * 2), 0.2f, (game->carSpeed / 500)); if (shape == ')') { shapeDelta = -1; } if (shape == '(') { shapeDelta = 1; } float slopeDelta = 0; if (slope == '/') { slopeDelta = 1; } if (slope == '\\') { slopeDelta = -1; } int distanceToCurrentShape = 0; if (game->distanceToNextElement > (CLevel::kSegmentLengthInMeters / 2)) { distanceToCurrentShape = (CLevel::kSegmentLengthInMeters - game->distanceToNextElement); } else { distanceToCurrentShape = (game->distanceToNextElement); } int halfScreenHeight = 480 / 2; float slopeAddedLines = (2 * CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta); int modulus = static_cast<int>(game->mHeading * 640) % 640; while (modulus < 0) { modulus += 640; } int shadingStripesCount = 0; // drawBackdropForHeading( modulus, game->zone ); renderer->drawSquare(0, halfScreenHeight - slopeAddedLines, 640, 480, {0, 64, 0, 255}); renderer->drawSquare(0, 0, 640, halfScreenHeight - slopeAddedLines, {0, 0, 0, 255}); Vec2 previousLeft(-1, -1); Vec2 previousRight(-1, -1); shadingStripesCount = 0; float initialSlope = CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta; float currentStripeHeight = initialSlope; float stripeHeightDelta = (-initialSlope) / 480; for (int y = halfScreenHeight; y > -1; y--) { shadingStripesCount = (shadingStripesCount + 1) % 1024; currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - y)) * stripeHeightDelta); float curve = (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * shapeDelta * y * y / completelyArbitraryCurveEasingFactor; Vec2 leftPoint = project(Vec3(curve - 1, -1 + currentStripeHeight, -y), camera); Vec2 rightPoint = project(Vec3(curve + 1, -1 + currentStripeHeight, -y), camera); //if it's valid if (previousLeft.y < 0) { previousLeft = leftPoint; previousRight = rightPoint; } int count = (-shadingStripesCount + static_cast<long>(game->distanceRan)) % numberOfStripeShades; int shade = ((count + 16) * 256) / 32; renderer->fill(leftPoint.x, rightPoint.x, leftPoint.y, previousLeft.x, previousRight.x, previousLeft.y, {shade, shade, shade, 255}); previousLeft = leftPoint; previousRight = rightPoint; } initialSlope = CLevel::kSlopeHeightInMeters * (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * slopeDelta; stripeHeightDelta = (-initialSlope) / 480; auto cars = game->getCarsAhead(1024); float playerLane = (game->x) / 640; for (auto foe : cars) { float y = std::get<0>(foe) - game->distanceRan; float curve = (distanceToCurrentShape / static_cast<float>(CLevel::kSegmentLengthInMeters)) * shapeDelta * y * y / completelyArbitraryCurveEasingFactor; float lane = std::get<1>(foe); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - y + 1)) * stripeHeightDelta); Vec2 carProjection0 = project(Vec3(curve + lane - 0.2f, -1 + currentStripeHeight, -y + 0), camera); Vec2 carProjection1 = project(Vec3(curve + lane + 0.2f, -1 + currentStripeHeight, -y + 0), camera); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - y - 1)) * stripeHeightDelta); Vec2 carProjection2 = project(Vec3(curve + lane - 0.2f, -1 + currentStripeHeight, -y - 1), camera); Vec2 carProjection3 = project(Vec3(curve + lane + 0.2f, -1 + currentStripeHeight, -y - 1), camera); int carSprite = (lane + 1) + 1; int carSize = 0; int sizeX = 32; int sizeY = 8; if (y <= 5) { carSize = 0; sizeX = 128; sizeY = 64; } else if (5 <= y && y <= 25) { carSize = 1; sizeX = 64; sizeY = 32; } else if (25 <= y && y <= 75) { carSize = 2; sizeX = 32; sizeY = 16; } else { continue; } float centerX = carProjection0.x + ((carProjection1.x - carProjection0.x) / 2); float centerY = carProjection0.y + ((carProjection2.y - carProjection0.y) / 2); renderer->fill(carProjection0.x, carProjection1.x, carProjection0.y, carProjection2.x, carProjection3.x, centerY, {0, 0, 0, 0}); renderer->drawBitmapAt(centerX - (sizeX / 2), centerY - (sizeY / 2), sizeX, sizeY, mOtherCar[carSprite][carSize]); } { float lane = (game->x) / 640; currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - 4)) * stripeHeightDelta); Vec2 carProjection2 = project(Vec3(lane - 0.2f, -1 + currentStripeHeight, -2 - 1), camera); Vec2 carProjection3 = project(Vec3(lane + 0.2f, -1 + currentStripeHeight, -2 - 1), camera); currentStripeHeight = initialSlope + ((2 * (halfScreenHeight - 2.1)) * stripeHeightDelta); Vec2 carProjection0 = project(Vec3(lane - 0.2f, -1 + currentStripeHeight, -2), camera); Vec2 carProjection1 = project(Vec3(lane + 0.2f, -1 + currentStripeHeight, -2), camera); float centerX = carProjection0.x + ((carProjection1.x - carProjection0.x) / 2); float centerY = carProjection0.y + ((carProjection2.y - carProjection0.y) / 2); int carSprite = (lane + 1) + 1; renderer->fill(carProjection0.x, carProjection1.x, carProjection0.y, carProjection2.x, carProjection3.x, centerY, {0, 0, 0, 0}); renderer->drawBitmapAt(centerX - 64, centerY - 32, 128, 32, mCar[carSprite][0]); if (game->smoking) { renderer->drawBitmapAt(centerX - 64, centerY, 100, 33, mSmoke); } } if (game->hit) { renderer->playSound(mHitSound); game->hit = false; } if (game->brake) { renderer->playSound(mBrakeSound); game->brake = false; } if (game->accel) { renderer->playSound(mAccelerateSound); game->accel = false; } } void CGameplayView::onClick(std::pair<int, int> position) { if (position.first > 420) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kRight); } else if (position.first < 210) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kLeft); } if (position.second > 320) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kDown); } else if (position.second < 160) { this->mGameSession->getLevel()->onKeyDown(Vipper::ECommand::kUp); } } void CGameplayView::onKeyUp(Vipper::ECommand keyCode) { this->mGameSession->getLevel()->onKeyUp(keyCode); } void CGameplayView::onKeyDown(Vipper::ECommand keyCode) { this->mGameSession->getLevel()->onKeyDown(keyCode); } } <|endoftext|>
<commit_before>/** * \file * \brief ThreadListNode class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ #include "estd/IntrusiveList.hpp" namespace distortos { namespace internal { /** * \brief ThreadListNode class is a base for ThreadControlBlock that provides nodes for intrusive lists * * This class is needed to break circular dependency - MutexList is contained in ThreadControlBlock and ThreadList is * contained in MutexControlBlock. */ class ThreadListNode { public: /** * \brief ThreadListNode's constructor * * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest */ constexpr ThreadListNode(const uint8_t priority) : threadListNode{}, threadGroupNode{}, priority_{priority}, boostedPriority_{} { } /** * \return effective priority of thread */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return priority of thread */ uint8_t getPriority() const { return priority_; } /// node for intrusive list in thread lists estd::IntrusiveListNode threadListNode; /// node for intrusive list in thread group estd::IntrusiveListNode threadGroupNode; protected: /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ <commit_msg>Make ThreadListNode's constructor explicit<commit_after>/** * \file * \brief ThreadListNode class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ #include "estd/IntrusiveList.hpp" namespace distortos { namespace internal { /** * \brief ThreadListNode class is a base for ThreadControlBlock that provides nodes for intrusive lists * * This class is needed to break circular dependency - MutexList is contained in ThreadControlBlock and ThreadList is * contained in MutexControlBlock. */ class ThreadListNode { public: /** * \brief ThreadListNode's constructor * * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest */ constexpr explicit ThreadListNode(const uint8_t priority) : threadListNode{}, threadGroupNode{}, priority_{priority}, boostedPriority_{} { } /** * \return effective priority of thread */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return priority of thread */ uint8_t getPriority() const { return priority_; } /// node for intrusive list in thread lists estd::IntrusiveListNode threadListNode; /// node for intrusive list in thread group estd::IntrusiveListNode threadGroupNode; protected: /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_THREADLISTNODE_HPP_ <|endoftext|>
<commit_before>#ifndef VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES #define VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES #include <vsmc/internal/common.hpp> namespace vsmc { namespace internal { template <unsigned Index, typename EvalType> struct NumericNewtonCotesEval { static double result (const double *coeff, double a, double h, const EvalType &eval) { return coeff[Index] * eval(a + (Index - 1) * h) + NumericNewtonCotesEval<Index - 1, EvalType>:: result(coeff, a, h, eval); } }; template <typename EvalType> struct NumericNewtonCotesEval<1, EvalType> { static double result (const double *coeff, double a, double h, const EvalType &eval) { return coeff[1] * eval(a); } }; template <unsigned Degree> class NumericNewtonCotesCoeff { public : static NumericNewtonCotesCoeff<Degree> &instance () { static NumericNewtonCotesCoeff<Degree> coeff; return coeff; } const double *coeff() const { return coeff_; } private : double coeff_[Degree + 2]; NumericNewtonCotesCoeff () {coeff_init(traits::integral_constant<unsigned, Degree>());} NumericNewtonCotesCoeff (const NumericNewtonCotesCoeff<Degree> &); NumericNewtonCotesCoeff<Degree> &operator= (const NumericNewtonCotesCoeff<Degree> &); void coeff_init (traits::integral_constant<unsigned, 1>) { coeff_[0] = 0.5; coeff_[1] = 1; coeff_[2] = 1; } void coeff_init (traits::integral_constant<unsigned, 2>) { coeff_[0] = 1.0 / 6.0; coeff_[1] = 1; coeff_[2] = 4; coeff_[3] = 1; } void coeff_init (traits::integral_constant<unsigned, 3>) { coeff_[0] = 0.125; coeff_[1] = 1; coeff_[2] = 3; coeff_[3] = 3; coeff_[4] = 1; } void coeff_init (traits::integral_constant<unsigned, 4>) { coeff_[0] = 1.0 / 90.0; coeff_[1] = 7; coeff_[2] = 32; coeff_[3] = 12; coeff_[4] = 32; coeff_[5] = 7; } void coeff_init (traits::integral_constant<unsigned, 5>) { coeff_[0] = 1.0 / 288.0; coeff_[1] = 19; coeff_[2] = 75; coeff_[3] = 50; coeff_[4] = 50; coeff_[5] = 75; coeff_[6] = 19; } void coeff_init (traits::integral_constant<unsigned, 6>) { coeff_[0] = 1.0 / 840.0; coeff_[1] = 41; coeff_[2] = 216; coeff_[3] = 27; coeff_[4] = 272; coeff_[5] = 27; coeff_[6] = 216; coeff_[7] = 41; } void coeff_init (traits::integral_constant<unsigned, 7>) { coeff_[0] = 1.0 / 17280.0; coeff_[1] = 751; coeff_[2] = 3577; coeff_[3] = 1323; coeff_[4] = 2989; coeff_[5] = 2989; coeff_[6] = 1323; coeff_[7] = 3577; coeff_[8] = 751; } void coeff_init (traits::integral_constant<unsigned, 8>) { coeff_[0] = 1.0 / 28350.0; coeff_[1] = 989; coeff_[2] = 5888; coeff_[3] = -928; coeff_[4] = 10496; coeff_[5] = -4540; coeff_[6] = 10496; coeff_[7] = -928; coeff_[8] = 5888; coeff_[9] = 989; } void coeff_init (traits::integral_constant<unsigned, 9>) { coeff_[0] = 1.0 / 89600.0; coeff_[1] = 2857; coeff_[2] = 15741; coeff_[3] = 1080; coeff_[4] = 19344; coeff_[5] = 5778; coeff_[6] = 5778; coeff_[7] = 19344; coeff_[8] = 1080; coeff_[9] = 15741; coeff_[10] = 2857; } void coeff_init (traits::integral_constant<unsigned, 10>) { coeff_[0] = 1.0 / 598752.0; coeff_[1] = 16067; coeff_[2] = 106300; coeff_[3] = -48525; coeff_[4] = 272400; coeff_[5] = -260550; coeff_[6] = 427368; coeff_[7] = -260550; coeff_[8] = 272400; coeff_[9] = -48525; coeff_[10] = 106300; coeff_[11] = 16067; } }; } // namespace vsmc::internal /// \brief Numerical integration with the (closed) Newton-Cotes formulae /// \ingroup Integrate template <unsigned Degree, template <typename> class NumericImpl> class NumericNewtonCotes : public NumericImpl<NumericNewtonCotes<Degree, NumericImpl> > { public : typedef typename NumericImpl<NumericNewtonCotes<Degree, NumericImpl> >:: size_type size_type; typedef typename NumericImpl<NumericNewtonCotes<Degree, NumericImpl> >:: eval_type eval_type; NumericNewtonCotes () : coeff_(internal::NumericNewtonCotesCoeff<Degree>::instance().coeff()) {} double integrate_segment (double a, double b, const eval_type &eval) const { VSMC_STATIC_ASSERT_NUMERIC_NEWTON_COTES_DEGREE(Degree); double h = (b - a) / Degree; return coeff_[0] * (b - a) * ( internal::NumericNewtonCotesEval<Degree, eval_type>:: result(coeff_, a, h, eval) + coeff_[Degree + 1] * eval(b)); } static VSMC_CONSTEXPR unsigned max_degree () { return max_degree_; } private : static const unsigned max_degree_ = 10; const double *coeff_; }; // class NumericNewtonCotes } // namespace vsmc #endif // VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES <commit_msg>clean<commit_after>#ifndef VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES #define VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES #include <vsmc/internal/common.hpp> namespace vsmc { namespace internal { template <unsigned Index, typename EvalType> struct NumericNewtonCotesEval { static double result (const double *coeff, double a, double h, const EvalType &eval) { return coeff[Index] * eval(a + (Index - 1) * h) + NumericNewtonCotesEval<Index - 1, EvalType>:: result(coeff, a, h, eval); } }; template <typename EvalType> struct NumericNewtonCotesEval<1, EvalType> { static double result (const double *coeff, double a, double h, const EvalType &eval) { return coeff[1] * eval(a); } }; template <unsigned Degree> class NumericNewtonCotesCoeff { public : static NumericNewtonCotesCoeff<Degree> &instance () { static NumericNewtonCotesCoeff<Degree> coeff; return coeff; } const double *coeff() const {return coeff_;} private : double coeff_[Degree + 2]; NumericNewtonCotesCoeff () {coeff_init(traits::integral_constant<unsigned, Degree>());} NumericNewtonCotesCoeff (const NumericNewtonCotesCoeff<Degree> &); NumericNewtonCotesCoeff<Degree> &operator= (const NumericNewtonCotesCoeff<Degree> &); void coeff_init (traits::integral_constant<unsigned, 1>) { coeff_[0] = 0.5; coeff_[1] = 1; coeff_[2] = 1; } void coeff_init (traits::integral_constant<unsigned, 2>) { coeff_[0] = 1.0 / 6.0; coeff_[1] = 1; coeff_[2] = 4; coeff_[3] = 1; } void coeff_init (traits::integral_constant<unsigned, 3>) { coeff_[0] = 0.125; coeff_[1] = 1; coeff_[2] = 3; coeff_[3] = 3; coeff_[4] = 1; } void coeff_init (traits::integral_constant<unsigned, 4>) { coeff_[0] = 1.0 / 90.0; coeff_[1] = 7; coeff_[2] = 32; coeff_[3] = 12; coeff_[4] = 32; coeff_[5] = 7; } void coeff_init (traits::integral_constant<unsigned, 5>) { coeff_[0] = 1.0 / 288.0; coeff_[1] = 19; coeff_[2] = 75; coeff_[3] = 50; coeff_[4] = 50; coeff_[5] = 75; coeff_[6] = 19; } void coeff_init (traits::integral_constant<unsigned, 6>) { coeff_[0] = 1.0 / 840.0; coeff_[1] = 41; coeff_[2] = 216; coeff_[3] = 27; coeff_[4] = 272; coeff_[5] = 27; coeff_[6] = 216; coeff_[7] = 41; } void coeff_init (traits::integral_constant<unsigned, 7>) { coeff_[0] = 1.0 / 17280.0; coeff_[1] = 751; coeff_[2] = 3577; coeff_[3] = 1323; coeff_[4] = 2989; coeff_[5] = 2989; coeff_[6] = 1323; coeff_[7] = 3577; coeff_[8] = 751; } void coeff_init (traits::integral_constant<unsigned, 8>) { coeff_[0] = 1.0 / 28350.0; coeff_[1] = 989; coeff_[2] = 5888; coeff_[3] = -928; coeff_[4] = 10496; coeff_[5] = -4540; coeff_[6] = 10496; coeff_[7] = -928; coeff_[8] = 5888; coeff_[9] = 989; } void coeff_init (traits::integral_constant<unsigned, 9>) { coeff_[0] = 1.0 / 89600.0; coeff_[1] = 2857; coeff_[2] = 15741; coeff_[3] = 1080; coeff_[4] = 19344; coeff_[5] = 5778; coeff_[6] = 5778; coeff_[7] = 19344; coeff_[8] = 1080; coeff_[9] = 15741; coeff_[10] = 2857; } void coeff_init (traits::integral_constant<unsigned, 10>) { coeff_[0] = 1.0 / 598752.0; coeff_[1] = 16067; coeff_[2] = 106300; coeff_[3] = -48525; coeff_[4] = 272400; coeff_[5] = -260550; coeff_[6] = 427368; coeff_[7] = -260550; coeff_[8] = 272400; coeff_[9] = -48525; coeff_[10] = 106300; coeff_[11] = 16067; } }; } // namespace vsmc::internal /// \brief Numerical integration with the (closed) Newton-Cotes formulae /// \ingroup Integrate template <unsigned Degree, template <typename> class NumericImpl> class NumericNewtonCotes : public NumericImpl<NumericNewtonCotes<Degree, NumericImpl> > { public : typedef typename NumericImpl<NumericNewtonCotes<Degree, NumericImpl> >:: size_type size_type; typedef typename NumericImpl<NumericNewtonCotes<Degree, NumericImpl> >:: eval_type eval_type; NumericNewtonCotes () : coeff_(internal::NumericNewtonCotesCoeff<Degree>::instance().coeff()) {} double integrate_segment (double a, double b, const eval_type &eval) const { VSMC_STATIC_ASSERT_NUMERIC_NEWTON_COTES_DEGREE(Degree); double h = (b - a) / Degree; return coeff_[0] * (b - a) * ( internal::NumericNewtonCotesEval<Degree, eval_type>:: result(coeff_, a, h, eval) + coeff_[Degree + 1] * eval(b)); } static VSMC_CONSTEXPR unsigned max_degree () {return max_degree_;} private : static const unsigned max_degree_ = 10; const double *coeff_; }; // class NumericNewtonCotes } // namespace vsmc #endif // VSMC_UTILITY_INTEGRATE_NUMERIC_NEWTON_COTES <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "KmlPlacemarkTagWriter.h" #include "KmlElementDictionary.h" #include "GeoDataExtendedData.h" #include "GeoDataPlacemark.h" #include "GeoDataTypes.h" #include "GeoWriter.h" namespace Marble { //needs to handle a specific doctype. different versions different writer classes? //don't use the tag dictionary for tag names, because with the writer we are using // the object type strings instead //FIXME: USE object strings provided by idis static GeoTagWriterRegistrar s_writerPlacemark( GeoTagWriter::QualifiedName(GeoDataTypes::GeoDataPlacemarkType, kml::kmlTag_nameSpace22), new KmlPlacemarkTagWriter() ); bool KmlPlacemarkTagWriter::write( const GeoDataObject &node, GeoWriter& writer ) const { const GeoDataPlacemark &placemark = static_cast<const GeoDataPlacemark&>(node); writer.writeStartElement( kml::kmlTag_Placemark ); if( !placemark.name().isEmpty() ) { writer.writeStartElement( "name" ); writer.writeCharacters( placemark.name() ); writer.writeEndElement(); } if( !placemark.description().isEmpty() ) { writer.writeStartElement( "description" ); if( placemark.descriptionIsCDATA() ) { writer.writeCDATA( placemark.description() ); } else { writer.writeCharacters( placemark.description() ); } writer.writeEndElement(); } if( !placemark.extendedData().isEmpty() ){ writeElement( placemark.extendedData(), writer ); } if( placemark.geometry() ) { writeElement( *placemark.geometry(), writer ); } if( placemark.lookAt() ){ writeElement( *placemark.lookAt(), writer ); } writer.writeEndElement(); return true; } } <commit_msg>- Missing header file<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "KmlPlacemarkTagWriter.h" #include "KmlElementDictionary.h" #include "GeoDataPlacemark.h" #include "GeoDataExtendedData.h" #include "GeoDataTypes.h" #include "GeoWriter.h" namespace Marble { //needs to handle a specific doctype. different versions different writer classes? //don't use the tag dictionary for tag names, because with the writer we are using // the object type strings instead //FIXME: USE object strings provided by idis static GeoTagWriterRegistrar s_writerPlacemark( GeoTagWriter::QualifiedName(GeoDataTypes::GeoDataPlacemarkType, kml::kmlTag_nameSpace22), new KmlPlacemarkTagWriter() ); bool KmlPlacemarkTagWriter::write( const GeoDataObject &node, GeoWriter& writer ) const { const GeoDataPlacemark &placemark = static_cast<const GeoDataPlacemark&>(node); writer.writeStartElement( kml::kmlTag_Placemark ); if( !placemark.name().isEmpty() ) { writer.writeStartElement( "name" ); writer.writeCharacters( placemark.name() ); writer.writeEndElement(); } if( !placemark.description().isEmpty() ) { writer.writeStartElement( "description" ); if( placemark.descriptionIsCDATA() ) { writer.writeCDATA( placemark.description() ); } else { writer.writeCharacters( placemark.description() ); } writer.writeEndElement(); } if( !placemark.extendedData().isEmpty() ){ writeElement( placemark.extendedData(), writer ); } if( placemark.geometry() ) { writeElement( *placemark.geometry(), writer ); } if( placemark.lookAt() ){ writeElement( *placemark.lookAt(), writer ); } writer.writeEndElement(); return true; } } <|endoftext|>
<commit_before><commit_msg>remove debug msg<commit_after><|endoftext|>
<commit_before>#include "util/bitmap.h" #include "network_character.h" #include "object.h" #include "object_messages.h" #include "animation.h" #include "util/font.h" #include "util/funcs.h" #include "factory/font_render.h" #include "nameplacer.h" #include "globals.h" #include "world.h" #include <vector> #include <math.h> using namespace std; NetworkCharacter::NetworkCharacter( int alliance ): Character( alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const char * filename, int alliance ) throw( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const string & filename, int alliance ) throw ( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const Character & chr ) throw( LoadException ): Character( chr ), name_id(-1), show_name_time(0){ } NetworkCharacter::~NetworkCharacter(){ } Object * NetworkCharacter::copy(){ return new NetworkCharacter( *this ); } /* player will send a grab message, network character should send a bogus message */ Network::Message NetworkCharacter::grabMessage( unsigned int from, unsigned int who ){ Network::Message message; message.id = 0; message << World::IGNORE_MESSAGE; return message; } void NetworkCharacter::interpretMessage( Network::Message & message ){ int type; message >> type; switch ( type ){ case CharacterMessages::ShowName : { int amount; message >> amount; setNameTime( amount ); break; } default : { message.reset(); Character::interpretMessage( message ); break; } } } void NetworkCharacter::setNameTime( int d ){ show_name_time = d; } void NetworkCharacter::alwaysShowName(){ setNameTime( -1 ); Global::debug( 1 ) << getId() << " name time is " << show_name_time << endl; } void NetworkCharacter::drawFront(Bitmap * work, int rel_x){ if ( show_name_time > 0 || show_name_time == -1 ){ int x1, y1; NamePlacer::getPlacement( x1, y1, name_id ); if ( icon ) icon->draw( x1, y1, *work ); int hasIcon = icon ? icon->getWidth() : 0; const Font & player_font = Font::getFont( Util::getDataPath() + Global::DEFAULT_FONT, 20, 20 ); const string & name = getName(); int nameHeight = player_font.getHeight( name ) / 2; nameHeight = 20 / 2; FontRender * render = FontRender::getInstance(); render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name ); drawLifeBar( hasIcon + x1, y1 + nameHeight, work ); if ( show_name_time > 0 ){ show_name_time -= 1; } } else { Global::debug( 2 ) << "Show name time for " << getId() << " is " << show_name_time << endl; } } /* void NetworkCharacter::draw( Bitmap * work, int rel_x ){ Character::draw( work, rel_x ); } */ /* just performs the current animation */ void NetworkCharacter::act( vector< Object * > * others, World * world, vector< Object * > * add ){ Global::debug( 2 ) << getId() << " status is " << getStatus() << endl; Character::act( others, world, add ); if ( (getStatus() == Status_Ground || getStatus() == Status_Jumping) && animation_current->Act() ){ // Global::debug( 0 ) << "Reset animation" << endl; if ( animation_current->getName() != "idle" && animation_current->getName() != "walk" ){ animation_current = getMovement( "idle" ); } animation_current->reset(); } } void NetworkCharacter::landed( World * world ){ setThrown( false ); switch( getStatus() ){ case Status_Falling : { if ( landed_sound ){ landed_sound->play(); } world->Quake( (int)fabs(getYVelocity()) ); break; } case Status_Fell : { world->Quake( (int)fabs(getYVelocity()) ); break; } } } void NetworkCharacter::deathReset(){ setY( 200 ); setMoving( true ); setStatus( Status_Falling ); setHealth( getMaxHealth() ); setInvincibility( 400 ); setDeath( 0 ); animation_current = getMovement( "idle" ); } <commit_msg>fix white space<commit_after>#include "util/bitmap.h" #include "network_character.h" #include "object.h" #include "object_messages.h" #include "animation.h" #include "util/font.h" #include "util/funcs.h" #include "factory/font_render.h" #include "nameplacer.h" #include "globals.h" #include "world.h" #include <vector> #include <math.h> using namespace std; NetworkCharacter::NetworkCharacter( int alliance ): Character( alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const char * filename, int alliance ) throw( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const string & filename, int alliance ) throw ( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const Character & chr ) throw( LoadException ): Character( chr ), name_id(-1), show_name_time(0){ } NetworkCharacter::~NetworkCharacter(){ } Object * NetworkCharacter::copy(){ return new NetworkCharacter( *this ); } /* player will send a grab message, network character should send a bogus message */ Network::Message NetworkCharacter::grabMessage( unsigned int from, unsigned int who ){ Network::Message message; message.id = 0; message << World::IGNORE_MESSAGE; return message; } void NetworkCharacter::interpretMessage( Network::Message & message ){ int type; message >> type; switch ( type ){ case CharacterMessages::ShowName : { int amount; message >> amount; setNameTime( amount ); break; } default : { message.reset(); Character::interpretMessage( message ); break; } } } void NetworkCharacter::setNameTime( int d ){ show_name_time = d; } void NetworkCharacter::alwaysShowName(){ setNameTime( -1 ); Global::debug( 1 ) << getId() << " name time is " << show_name_time << endl; } void NetworkCharacter::drawFront(Bitmap * work, int rel_x){ if ( show_name_time > 0 || show_name_time == -1 ){ int x1, y1; NamePlacer::getPlacement( x1, y1, name_id ); if ( icon ) icon->draw( x1, y1, *work ); int hasIcon = icon ? icon->getWidth() : 0; const Font & player_font = Font::getFont( Util::getDataPath() + Global::DEFAULT_FONT, 20, 20 ); const string & name = getName(); int nameHeight = player_font.getHeight( name ) / 2; nameHeight = 20 / 2; FontRender * render = FontRender::getInstance(); render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name ); drawLifeBar( hasIcon + x1, y1 + nameHeight, work ); if ( show_name_time > 0 ){ show_name_time -= 1; } } else { Global::debug( 2 ) << "Show name time for " << getId() << " is " << show_name_time << endl; } } /* void NetworkCharacter::draw( Bitmap * work, int rel_x ){ Character::draw( work, rel_x ); } */ /* just performs the current animation */ void NetworkCharacter::act( vector< Object * > * others, World * world, vector< Object * > * add ){ Global::debug( 2 ) << getId() << " status is " << getStatus() << endl; Character::act( others, world, add ); if ( (getStatus() == Status_Ground || getStatus() == Status_Jumping) && animation_current->Act() ){ // Global::debug( 0 ) << "Reset animation" << endl; if ( animation_current->getName() != "idle" && animation_current->getName() != "walk" ){ animation_current = getMovement( "idle" ); } animation_current->reset(); } } void NetworkCharacter::landed( World * world ){ setThrown( false ); switch( getStatus() ){ case Status_Falling : { if ( landed_sound ){ landed_sound->play(); } world->Quake( (int)fabs(getYVelocity()) ); break; } case Status_Fell : { world->Quake( (int)fabs(getYVelocity()) ); break; } } } void NetworkCharacter::deathReset(){ setY( 200 ); setMoving( true ); setStatus( Status_Falling ); setHealth( getMaxHealth() ); setInvincibility( 400 ); setDeath( 0 ); animation_current = getMovement( "idle" ); } <|endoftext|>
<commit_before>#include "parameters_dealii_handler.h" #include <deal.II/base/parameter_handler.h> #include <algorithm> #include <sstream> namespace bart { namespace problem { ParametersDealiiHandler::ParametersDealiiHandler() {} void ParametersDealiiHandler::Parse(const dealii::ParameterHandler &handler) { // Parse parameters // Basic Parameters discretization_ = kDiscretizationTypeMap_.at( handler.get(key_words_.kDiscretization_)); is_eigenvalue_problem_ = handler.get_bool(key_words_.kEigenvalueProblem_); have_reflective_bc_ = handler.get_bool(key_words_.kHaveReflectiveBC_); fe_polynomial_degree_ = handler.get_integer(key_words_.kFEPolynomialDegree_); first_thermal_group_ = handler.get_integer(key_words_.kFirstThermalGroup_); n_cells_ = ParseDealiiIntList(handler.get(key_words_.kNCells_)); n_groups_ = handler.get_integer(key_words_.kNEnergyGroups_); n_materials_ = handler.get_integer(key_words_.kNumberOfMaterials_); output_filename_base_ = handler.get(key_words_.kOutputFilenameBase_); reflective_boundary_ = ParseDealiiMultiple( handler.get(key_words_.kReflectiveBoundary_), kBoundaryMap_); spatial_dimension_ = handler.get_integer(key_words_.kSpatialDimension_); spatial_max = ParseDealiiList(handler.get(key_words_.kSpatialMax_)); transport_model_ = kEquationTypeMap_.at( handler.get(key_words_.kTransportModel_)); // Acceleration preconditioner_ = kPreconditionerTypeMap_.at( handler.get(key_words_.kPreconditioner_)); block_ssor_factor_ = handler.get_double(key_words_.kBSSOR_Factor_); do_nda_ = handler.get_bool(key_words_.kDoNDA_); nda_discretization_ = kDiscretizationTypeMap_.at(handler.get(key_words_.kNDA_Discretization_)); nda_linear_solver_ = kLinearSolverTypeMap_.at(handler.get(key_words_.kNDALinearSolver_)); nda_preconditioner_ = kPreconditionerTypeMap_.at( handler.get(key_words_.kNDAPreconditioner_)); nda_block_ssor_factor_ = handler.get_double(key_words_.kNDA_BSSOR_Factor_); // Solvers eigen_solver_ = kEigenSolverTypeMap_.at(handler.get(key_words_.kEigenSolver_)); in_group_solver_ = kInGroupSolverTypeMap_.at(handler.get(key_words_.kInGroupSolver_)); linear_solver_ = kLinearSolverTypeMap_.at(handler.get(key_words_.kLinearSolver_)); multi_group_solver_ = kMultiGroupSolverTypeMap_.at(handler.get(key_words_.kMultiGroupSolver_)); // Angular Quadrature parameters angular_quad_ = kAngularQuadTypeMap_.at(handler.get(key_words_.kAngularQuad_)); angular_quad_order_ = handler.get_integer(key_words_.kAngularQuadOrder_); } void ParametersDealiiHandler::SetUp(dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; /* Set parameters. A try and catch wrapper is required for some. For these, * we are using the build-in validity checking for the parameter, but the * default values are not valid themselves. Mostly this means that there is * no default value. */ SetUpBasicParameters(handler); SetUpAccelerationParameters(handler); SetUpSolverParameters(handler); SetUpAngularQuadratureParameters(handler); } /* ============================================================================= * PARAMETER SET UP * * This section declares all the entries in the parameter handler that we expect * to see in our input file. We use the validation checking that comes with * dealii; sometimes default parameters do not meet the validation (if no default * parameter makes sense) so a try/catch is needed to ignore the thrown error. * The entry is still made. SetUp is divided up to make it a little easier, but * it's still a lot of hard to read code. * ===========================================================================*/ void ParametersDealiiHandler::SetUpBasicParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; handler.declare_entry(key_words_.kDiscretization_, "cfem", Pattern::Selection( GetOptionString(kDiscretizationTypeMap_)), "HO equation spatial discretization"); handler.declare_entry(key_words_.kEigenvalueProblem_, "false", Pattern::Bool(), "is problem an eigenvalue problem"); handler.declare_entry(key_words_.kFEPolynomialDegree_, "1", Pattern::Integer(1), "polynomial degree p for finite element"); handler.declare_entry ("have reflective boundary", "false", Pattern::Bool(), "Does the problem have reflective boundaries"); handler.declare_entry(key_words_.kFirstThermalGroup_, "0", Pattern::Integer(0), "group number for the first thermal group"); try { handler.declare_entry(key_words_.kNCells_ , "", Pattern::List (Pattern::Integer (0), 1, 3), "Geometry is hyper rectangle defined by how many cells exist per direction"); } catch (const dealii::ParameterHandler::ExcValueDoesNotMatchPattern &e) {} handler.declare_entry(key_words_.kNEnergyGroups_, "1", Pattern::Integer(0), "number of energy groups in the problem"); handler.declare_entry(key_words_.kNumberOfMaterials_, "1", Pattern::Integer(0), "number of materials in the problem"); handler.declare_entry(key_words_.kOutputFilenameBase_, "bart_output",Pattern::Anything(), "name base of the output file"); std::string boundary_options{GetOptionString(kBoundaryMap_)}; handler.declare_entry(key_words_.kReflectiveBoundary_, "", Pattern::MultipleSelection(boundary_options), "lower case boundary names (xmin, ymax) etc)"); handler.declare_entry(key_words_.kSpatialDimension_, "2", Pattern::Integer(1, 3), ""); try { handler.declare_entry(key_words_.kSpatialMax_, "", Pattern::List(Pattern::Double(), 1, 3), "xmax, ymax, zmax of the boundaries, mins are zero"); } catch (const dealii::ParameterHandler::ExcValueDoesNotMatchPattern &e) {} std::string equation_options{GetOptionString(kEquationTypeMap_)}; handler.declare_entry(key_words_.kTransportModel_, "none", Pattern::Selection(equation_options), "valid names such as ep"); } // ACCELERATION PARAMETERS ===================================================== void ParametersDealiiHandler::SetUpAccelerationParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; std::string preconditioner_options{GetOptionString(kPreconditionerTypeMap_)}; handler.declare_entry(key_words_.kPreconditioner_, "amg", Pattern::Selection(preconditioner_options), "Preconditioner"); handler.declare_entry(key_words_.kBSSOR_Factor_, "1.0", Pattern::Double(0), "damping factor of block SSOR"); handler.declare_entry(key_words_.kDoNDA_, "false", Pattern::Bool(), "Boolean to determine NDA or not"); handler.declare_entry(key_words_.kNDA_Discretization_, "cfem", Pattern::Selection( GetOptionString(kDiscretizationTypeMap_)), "NDA equation spatial discretization"); // Remove Conjugate Gradient from options for NDA linear solver std::string nda_linear_solver_options{GetOptionString( kLinearSolverTypeMap_, LinearSolverType::kConjugateGradient),}; handler.declare_entry(key_words_.kNDALinearSolver_, "none", Pattern::Selection(nda_linear_solver_options), "NDA linear solver"); handler.declare_entry(key_words_.kNDAPreconditioner_, "jacobi", Pattern::Selection(preconditioner_options), "NDA Preconditioner"); handler.declare_entry(key_words_.kNDA_BSSOR_Factor_, "1.0", Pattern::Double(0), "damping factor of NDA block SSOR"); } // SOLVER PARAMETERS =========================================================== void ParametersDealiiHandler::SetUpSolverParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; std::string eigen_solver_options{GetOptionString(kEigenSolverTypeMap_)}; handler.declare_entry(key_words_.kEigenSolver_, "pi", Pattern::Selection(eigen_solver_options), "eigenvalue solvers"); std::string in_group_solver_options{GetOptionString(kInGroupSolverTypeMap_)}; handler.declare_entry(key_words_.kInGroupSolver_, "si", Pattern::Selection(in_group_solver_options), "in-group solvers"); std::string linear_solver_options{GetOptionString(kLinearSolverTypeMap_)}; handler.declare_entry(key_words_.kLinearSolver_, "cg", Pattern::Selection(linear_solver_options), "linear solvers"); std::string multigroup_solver_options{GetOptionString(kMultiGroupSolverTypeMap_)}; handler.declare_entry(key_words_.kMultiGroupSolver_, "gs", Pattern::Selection(multigroup_solver_options), "Multi-group solvers"); } void ParametersDealiiHandler::SetUpAngularQuadratureParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; std::string angular_quad_options{GetOptionString(kAngularQuadTypeMap_)}; handler.declare_entry(key_words_.kAngularQuad_, "none", Pattern::Selection (angular_quad_options), "angular quadrature types. only LS-GC for multi-D and GL for 1D implemented for now."); handler.declare_entry(key_words_.kAngularQuadOrder_, "4", Pattern::Integer(), "Gauss-Chebyshev level-symmetric-like quadrature"); } template<typename Key> std::map<Key, bool> ParametersDealiiHandler::ParseDealiiMultiple( const std::string to_parse, const std::unordered_map<std::string, Key> enum_map) const { std::map<Key, bool> return_map; for (auto const entry : enum_map) return_map[entry.second] = false; std::stringstream iss{to_parse}; std::string read_value; while(iss >> read_value) { // strip commas read_value.erase(std::remove(read_value.begin(), read_value.end(), ','), read_value.end()); auto const it = enum_map.find(read_value); if (it != enum_map.cend()) return_map[enum_map.at(read_value)] = true; // Ignore next if comma or space if (iss.peek() == ' ') iss.ignore(); } return return_map; } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map, const std::vector<T> to_ignore) const { std::ostringstream oss; std::string return_string; for (auto const &entry : enum_map) { if (std::find(to_ignore.begin(), to_ignore.end(), entry.second) == to_ignore.end()) oss << entry.first << "|"; } return_string = oss.str(); if (return_string.size() > 0) return_string.pop_back(); return return_string; } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map) const { std::vector<T> to_ignore; return GetOptionString(enum_map, to_ignore); } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map, const T to_ignore) const { std::vector<T> ignore_vector{to_ignore}; return GetOptionString(enum_map, ignore_vector); } std::vector<double> ParametersDealiiHandler::ParseDealiiList( std::string to_parse) { std::vector<double> return_vector; double read_value; std::stringstream iss{to_parse}; while(iss >> read_value) { return_vector.push_back(read_value); // Ignore next if comma or space if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); } return return_vector; } std::vector<int> ParametersDealiiHandler::ParseDealiiIntList( std::string to_parse) { std::vector<double> double_vector(ParseDealiiList(to_parse)); std::vector<int> return_vector(double_vector.cbegin(), double_vector.cend()); return return_vector; } } // namespace problem } // namespace bart <commit_msg>removed extraneous string declarations in ParametersDealiiHandler implementation<commit_after>#include "parameters_dealii_handler.h" #include <deal.II/base/parameter_handler.h> #include <algorithm> #include <sstream> namespace bart { namespace problem { ParametersDealiiHandler::ParametersDealiiHandler() {} void ParametersDealiiHandler::Parse(const dealii::ParameterHandler &handler) { // Parse parameters // Basic Parameters discretization_ = kDiscretizationTypeMap_.at( handler.get(key_words_.kDiscretization_)); is_eigenvalue_problem_ = handler.get_bool(key_words_.kEigenvalueProblem_); have_reflective_bc_ = handler.get_bool(key_words_.kHaveReflectiveBC_); fe_polynomial_degree_ = handler.get_integer(key_words_.kFEPolynomialDegree_); first_thermal_group_ = handler.get_integer(key_words_.kFirstThermalGroup_); n_cells_ = ParseDealiiIntList(handler.get(key_words_.kNCells_)); n_groups_ = handler.get_integer(key_words_.kNEnergyGroups_); n_materials_ = handler.get_integer(key_words_.kNumberOfMaterials_); output_filename_base_ = handler.get(key_words_.kOutputFilenameBase_); reflective_boundary_ = ParseDealiiMultiple( handler.get(key_words_.kReflectiveBoundary_), kBoundaryMap_); spatial_dimension_ = handler.get_integer(key_words_.kSpatialDimension_); spatial_max = ParseDealiiList(handler.get(key_words_.kSpatialMax_)); transport_model_ = kEquationTypeMap_.at( handler.get(key_words_.kTransportModel_)); // Acceleration preconditioner_ = kPreconditionerTypeMap_.at( handler.get(key_words_.kPreconditioner_)); block_ssor_factor_ = handler.get_double(key_words_.kBSSOR_Factor_); do_nda_ = handler.get_bool(key_words_.kDoNDA_); nda_discretization_ = kDiscretizationTypeMap_.at( handler.get(key_words_.kNDA_Discretization_)); nda_linear_solver_ = kLinearSolverTypeMap_.at( handler.get(key_words_.kNDALinearSolver_)); nda_preconditioner_ = kPreconditionerTypeMap_.at( handler.get(key_words_.kNDAPreconditioner_)); nda_block_ssor_factor_ = handler.get_double(key_words_.kNDA_BSSOR_Factor_); // Solvers eigen_solver_ = kEigenSolverTypeMap_.at( handler.get(key_words_.kEigenSolver_)); in_group_solver_ = kInGroupSolverTypeMap_.at( handler.get(key_words_.kInGroupSolver_)); linear_solver_ = kLinearSolverTypeMap_.at( handler.get(key_words_.kLinearSolver_)); multi_group_solver_ = kMultiGroupSolverTypeMap_.at(handler.get(key_words_.kMultiGroupSolver_)); // Angular Quadrature parameters angular_quad_ = kAngularQuadTypeMap_.at(handler.get(key_words_.kAngularQuad_)); angular_quad_order_ = handler.get_integer(key_words_.kAngularQuadOrder_); } void ParametersDealiiHandler::SetUp(dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; /* Set parameters. A try and catch wrapper is required for some. For these, * we are using the build-in validity checking for the parameter, but the * default values are not valid themselves. Mostly this means that there is * no default value. */ SetUpBasicParameters(handler); SetUpAccelerationParameters(handler); SetUpSolverParameters(handler); SetUpAngularQuadratureParameters(handler); } /* ============================================================================= * PARAMETER SET UP * * This section declares all the entries in the parameter handler that we expect * to see in our input file. We use the validation checking that comes with * dealii; sometimes default parameters do not meet the validation (if no default * parameter makes sense) so a try/catch is needed to ignore the thrown error. * The entry is still made. SetUp is divided up to make it a little easier, but * it's still a lot of hard to read code. * ===========================================================================*/ void ParametersDealiiHandler::SetUpBasicParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; handler.declare_entry(key_words_.kDiscretization_, "cfem", Pattern::Selection( GetOptionString(kDiscretizationTypeMap_)), "HO equation spatial discretization"); handler.declare_entry(key_words_.kEigenvalueProblem_, "false", Pattern::Bool(), "is problem an eigenvalue problem"); handler.declare_entry(key_words_.kFEPolynomialDegree_, "1", Pattern::Integer(1), "polynomial degree p for finite element"); handler.declare_entry ("have reflective boundary", "false", Pattern::Bool(), "Does the problem have reflective boundaries"); handler.declare_entry(key_words_.kFirstThermalGroup_, "0", Pattern::Integer(0), "group number for the first thermal group"); try { handler.declare_entry(key_words_.kNCells_ , "", Pattern::List (Pattern::Integer (0), 1, 3), "Geometry is hyper rectangle defined by how many cells exist per direction"); } catch (const dealii::ParameterHandler::ExcValueDoesNotMatchPattern &e) {} handler.declare_entry(key_words_.kNEnergyGroups_, "1", Pattern::Integer(0), "number of energy groups in the problem"); handler.declare_entry(key_words_.kNumberOfMaterials_, "1", Pattern::Integer(0), "number of materials in the problem"); handler.declare_entry(key_words_.kOutputFilenameBase_, "bart_output",Pattern::Anything(), "name base of the output file"); handler.declare_entry(key_words_.kReflectiveBoundary_, "", Pattern::MultipleSelection( GetOptionString(kBoundaryMap_)), "lower case boundary names (xmin, ymax) etc)"); handler.declare_entry(key_words_.kSpatialDimension_, "2", Pattern::Integer(1, 3), ""); try { handler.declare_entry(key_words_.kSpatialMax_, "", Pattern::List(Pattern::Double(), 1, 3), "xmax, ymax, zmax of the boundaries, mins are zero"); } catch (const dealii::ParameterHandler::ExcValueDoesNotMatchPattern &e) {} handler.declare_entry(key_words_.kTransportModel_, "none", Pattern::Selection(GetOptionString(kEquationTypeMap_)), "valid names such as ep"); } // ACCELERATION PARAMETERS ===================================================== void ParametersDealiiHandler::SetUpAccelerationParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; std::string preconditioner_options{GetOptionString(kPreconditionerTypeMap_)}; handler.declare_entry(key_words_.kPreconditioner_, "amg", Pattern::Selection(preconditioner_options), "Preconditioner"); handler.declare_entry(key_words_.kBSSOR_Factor_, "1.0", Pattern::Double(0), "damping factor of block SSOR"); handler.declare_entry(key_words_.kDoNDA_, "false", Pattern::Bool(), "Boolean to determine NDA or not"); handler.declare_entry(key_words_.kNDA_Discretization_, "cfem", Pattern::Selection( GetOptionString(kDiscretizationTypeMap_)), "NDA equation spatial discretization"); // Remove Conjugate Gradient from options for NDA linear solver handler.declare_entry(key_words_.kNDALinearSolver_, "none", Pattern::Selection( GetOptionString( kLinearSolverTypeMap_, LinearSolverType::kConjugateGradient)), "NDA linear solver"); handler.declare_entry(key_words_.kNDAPreconditioner_, "jacobi", Pattern::Selection(preconditioner_options), "NDA Preconditioner"); handler.declare_entry(key_words_.kNDA_BSSOR_Factor_, "1.0", Pattern::Double(0), "damping factor of NDA block SSOR"); } // SOLVER PARAMETERS =========================================================== void ParametersDealiiHandler::SetUpSolverParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; handler.declare_entry(key_words_.kEigenSolver_, "pi", Pattern::Selection( GetOptionString(kEigenSolverTypeMap_)), "eigenvalue solvers"); handler.declare_entry(key_words_.kInGroupSolver_, "si", Pattern::Selection( GetOptionString(kInGroupSolverTypeMap_)), "in-group solvers"); handler.declare_entry(key_words_.kLinearSolver_, "cg", Pattern::Selection( GetOptionString(kLinearSolverTypeMap_)), "linear solvers"); handler.declare_entry(key_words_.kMultiGroupSolver_, "gs", Pattern::Selection( GetOptionString(kMultiGroupSolverTypeMap_)), "Multi-group solvers"); } void ParametersDealiiHandler::SetUpAngularQuadratureParameters( dealii::ParameterHandler &handler) { namespace Pattern = dealii::Patterns; handler.declare_entry(key_words_.kAngularQuad_, "none", Pattern::Selection( GetOptionString(kAngularQuadTypeMap_)), "angular quadrature types. only LS-GC for multi-D and GL for 1D implemented for now."); handler.declare_entry(key_words_.kAngularQuadOrder_, "4", Pattern::Integer(), "Gauss-Chebyshev level-symmetric-like quadrature"); } template<typename Key> std::map<Key, bool> ParametersDealiiHandler::ParseDealiiMultiple( const std::string to_parse, const std::unordered_map<std::string, Key> enum_map) const { std::map<Key, bool> return_map; for (auto const entry : enum_map) return_map[entry.second] = false; std::stringstream iss{to_parse}; std::string read_value; while(iss >> read_value) { // strip commas read_value.erase(std::remove(read_value.begin(), read_value.end(), ','), read_value.end()); auto const it = enum_map.find(read_value); if (it != enum_map.cend()) return_map[enum_map.at(read_value)] = true; // Ignore next if comma or space if (iss.peek() == ' ') iss.ignore(); } return return_map; } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map, const std::vector<T> to_ignore) const { std::ostringstream oss; std::string return_string; for (auto const &entry : enum_map) { if (std::find(to_ignore.begin(), to_ignore.end(), entry.second) == to_ignore.end()) oss << entry.first << "|"; } return_string = oss.str(); if (return_string.size() > 0) return_string.pop_back(); return return_string; } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map) const { std::vector<T> to_ignore; return GetOptionString(enum_map, to_ignore); } template<typename T> std::string ParametersDealiiHandler::GetOptionString( const std::unordered_map<std::string, T> enum_map, const T to_ignore) const { std::vector<T> ignore_vector{to_ignore}; return GetOptionString(enum_map, ignore_vector); } std::vector<double> ParametersDealiiHandler::ParseDealiiList( std::string to_parse) { std::vector<double> return_vector; double read_value; std::stringstream iss{to_parse}; while(iss >> read_value) { return_vector.push_back(read_value); // Ignore next if comma or space if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); } return return_vector; } std::vector<int> ParametersDealiiHandler::ParseDealiiIntList( std::string to_parse) { std::vector<double> double_vector(ParseDealiiList(to_parse)); std::vector<int> return_vector(double_vector.cbegin(), double_vector.cend()); return return_vector; } } // namespace problem } // namespace bart <|endoftext|>
<commit_before>#include "TwitchIrcServer.hpp" #include <IrcCommand> #include <cassert> #include "Application.hpp" #include "common/Common.hpp" #include "controllers/accounts/AccountController.hpp" #include "controllers/highlights/HighlightController.hpp" #include "messages/Message.hpp" #include "messages/MessageBuilder.hpp" #include "providers/twitch/ChatroomChannel.hpp" #include "providers/twitch/IrcMessageHandler.hpp" #include "providers/twitch/PubsubClient.hpp" #include "providers/twitch/TwitchAccount.hpp" #include "providers/twitch/TwitchChannel.hpp" #include "providers/twitch/TwitchHelpers.hpp" #include "providers/twitch/TwitchMessageBuilder.hpp" #include "util/PostToThread.hpp" // using namespace Communi; using namespace std::chrono_literals; namespace chatterino { namespace { bool isChatroom(const QString &channel) { if (channel.left(10) == "chatrooms:") { auto reflist = channel.splitRef(':'); if (reflist.size() == 3) { return true; } } return false; } } // namespace TwitchIrcServer::TwitchIrcServer() : whispersChannel(new Channel("/whispers", Channel::Type::TwitchWhispers)) , mentionsChannel(new Channel("/mentions", Channel::Type::TwitchMentions)) , watchingChannel(Channel::getEmpty(), Channel::Type::TwitchWatching) { this->pubsub = new PubSub; // getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { // this->connect(); }, // this->signalHolder_, // false); } void TwitchIrcServer::initialize(Settings &settings, Paths &paths) { getApp()->accounts->twitch.currentUserChanged.connect( [this]() { postToThread([this] { this->connect(); }); }); this->twitchBadges.loadTwitchBadges(); this->bttv.loadEmotes(); this->ffz.loadEmotes(); } void TwitchIrcServer::initializeConnection(IrcConnection *connection, ConnectionType type) { std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent(); qDebug() << "logging in as" << account->getUserName(); QString username = account->getUserName(); QString oauthToken = account->getOAuthToken(); if (!oauthToken.startsWith("oauth:")) { oauthToken.prepend("oauth:"); } connection->setUserName(username); connection->setNickName(username); connection->setRealName(username); if (!account->isAnon()) { connection->setPassword(oauthToken); } connection->setSecure(true); // https://dev.twitch.tv/docs/irc/guide/#connecting-to-twitch-irc // SSL disabled: irc://irc.chat.twitch.tv:6667 (or port 80) // SSL enabled: irc://irc.chat.twitch.tv:6697 (or port 443) connection->setHost("irc.chat.twitch.tv"); connection->setPort(6697); this->open(type); } std::shared_ptr<Channel> TwitchIrcServer::createChannel( const QString &channelName) { std::shared_ptr<TwitchChannel> channel; if (isChatroom(channelName)) { channel = std::static_pointer_cast<TwitchChannel>( std::shared_ptr<ChatroomChannel>(new ChatroomChannel( channelName, this->twitchBadges, this->bttv, this->ffz))); } else { channel = std::shared_ptr<TwitchChannel>(new TwitchChannel( channelName, this->twitchBadges, this->bttv, this->ffz)); } channel->initialize(); channel->sendMessageSignal.connect( [this, channel = channel.get()](auto &chan, auto &msg, bool &sent) { this->onMessageSendRequested(channel, msg, sent); }); return std::shared_ptr<Channel>(channel); } void TwitchIrcServer::privateMessageReceived( Communi::IrcPrivateMessage *message) { IrcMessageHandler::getInstance().handlePrivMessage(message, *this); } void TwitchIrcServer::readConnectionMessageReceived( Communi::IrcMessage *message) { AbstractIrcServer::readConnectionMessageReceived(message); if (message->type() == Communi::IrcMessage::Type::Private) { // We already have a handler for private messages return; } const QString &command = message->command(); auto &handler = IrcMessageHandler::getInstance(); // Below commands enabled through the twitch.tv/membership CAP REQ if (command == "MODE") { handler.handleModeMessage(message); } else if (command == "JOIN") { handler.handleJoinMessage(message); } else if (command == "PART") { handler.handlePartMessage(message); } else if (command == "USERSTATE") { // Received USERSTATE upon JOINing a channel handler.handleUserStateMessage(message); } else if (command == "ROOMSTATE") { // Received ROOMSTATE upon JOINing a channel handler.handleRoomStateMessage(message); } else if (command == "CLEARCHAT") { handler.handleClearChatMessage(message); } else if (command == "CLEARMSG") { handler.handleClearMessageMessage(message); } else if (command == "USERNOTICE") { handler.handleUserNoticeMessage(message, *this); } else if (command == "NOTICE") { handler.handleNoticeMessage( static_cast<Communi::IrcNoticeMessage *>(message)); } else if (command == "WHISPER") { handler.handleWhisperMessage(message); } } void TwitchIrcServer::writeConnectionMessageReceived( Communi::IrcMessage *message) { const QString &command = message->command(); auto &handler = IrcMessageHandler::getInstance(); // Below commands enabled through the twitch.tv/commands CAP REQ if (command == "USERSTATE") { // Received USERSTATE upon PRIVMSGing handler.handleUserStateMessage(message); } else if (command == "NOTICE") { static std::unordered_set<std::string> readConnectionOnlyIDs{ "host_on", "host_off", "host_target_went_offline", "emote_only_on", "emote_only_off", "slow_on", "slow_off", "subs_on", "subs_off", "r9k_on", "r9k_off", // Display for user who times someone out. This implies you're a // moderator, at which point you will be connected to PubSub and receive // a better message from there. "timeout_success", "ban_success", // Channel suspended notices "msg_channel_suspended", }; handler.handleNoticeMessage( static_cast<Communi::IrcNoticeMessage *>(message)); } } void TwitchIrcServer::onReadConnected(IrcConnection *connection) { // twitch.tv/tags enables IRCv3 tags on messages. See https://dev.twitch.tv/docs/irc/tags/ // twitch.tv/membership enables the JOIN/PART/MODE/NAMES commands. See https://dev.twitch.tv/docs/irc/membership/ // twitch.tv/commands enables a bunch of miscellaneous command capabilities. See https://dev.twitch.tv/docs/irc/commands/ // This is enabled here so we receive USERSTATE messages when joining channels connection->sendRaw( "CAP REQ :twitch.tv/tags twitch.tv/membership twitch.tv/commands"); AbstractIrcServer::onReadConnected(connection); } void TwitchIrcServer::onWriteConnected(IrcConnection *connection) { // twitch.tv/tags enables IRCv3 tags on messages. See https://dev.twitch.tv/docs/irc/tags/ // twitch.tv/commands enables a bunch of miscellaneous command capabilities. See https://dev.twitch.tv/docs/irc/commands/ // This is enabled here so we receive USERSTATE messages when typing messages, along with the other command capabilities connection->sendRaw("CAP REQ :twitch.tv/tags twitch.tv/commands"); AbstractIrcServer::onWriteConnected(connection); } std::shared_ptr<Channel> TwitchIrcServer::getCustomChannel( const QString &channelName) { if (channelName == "/whispers") { return this->whispersChannel; } if (channelName == "/mentions") { return this->mentionsChannel; } if (channelName == "$$$") { static auto channel = std::make_shared<Channel>("$$$", chatterino::Channel::Type::Misc); static auto getTimer = [&] { for (auto i = 0; i < 1000; i++) { channel->addMessage(makeSystemMessage(QString::number(i + 1))); } auto timer = new QTimer; QObject::connect(timer, &QTimer::timeout, [] { channel->addMessage( makeSystemMessage(QTime::currentTime().toString())); }); timer->start(500); return timer; }(); return channel; } return nullptr; } void TwitchIrcServer::forEachChannelAndSpecialChannels( std::function<void(ChannelPtr)> func) { this->forEachChannel(func); func(this->whispersChannel); func(this->mentionsChannel); } std::shared_ptr<Channel> TwitchIrcServer::getChannelOrEmptyByID( const QString &channelId) { std::lock_guard<std::mutex> lock(this->channelMutex); for (const auto &weakChannel : this->channels) { auto channel = weakChannel.lock(); if (!channel) continue; auto twitchChannel = std::dynamic_pointer_cast<TwitchChannel>(channel); if (!twitchChannel) continue; if (twitchChannel->roomId() == channelId && twitchChannel->getName().splitRef(":").size() < 3) { return twitchChannel; } } return Channel::getEmpty(); } QString TwitchIrcServer::cleanChannelName(const QString &dirtyChannelName) { if (dirtyChannelName.startsWith('#')) return dirtyChannelName.mid(1).toLower(); else return dirtyChannelName.toLower(); } bool TwitchIrcServer::hasSeparateWriteConnection() const { return true; // return getSettings()->twitchSeperateWriteConnection; } void TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent) { sent = false; { std::lock_guard<std::mutex> guard(this->lastMessageMutex_); // std::queue<std::chrono::steady_clock::time_point> auto &lastMessage = channel->hasHighRateLimit() ? this->lastMessageMod_ : this->lastMessagePleb_; size_t maxMessageCount = channel->hasHighRateLimit() ? 99 : 19; auto minMessageOffset = (channel->hasHighRateLimit() ? 100ms : 1100ms); auto now = std::chrono::steady_clock::now(); // check if you are sending messages too fast if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) { if (this->lastErrorTimeSpeed_ + 30s < now) { auto errorMessage = makeSystemMessage("sending messages too fast"); channel->addMessage(errorMessage); this->lastErrorTimeSpeed_ = now; } return; } // remove messages older than 30 seconds while (!lastMessage.empty() && lastMessage.front() + 32s < now) { lastMessage.pop(); } // check if you are sending too many messages if (lastMessage.size() >= maxMessageCount) { if (this->lastErrorTimeAmount_ + 30s < now) { auto errorMessage = makeSystemMessage("sending too many messages"); channel->addMessage(errorMessage); this->lastErrorTimeAmount_ = now; } return; } lastMessage.push(now); } this->sendMessage(channel->getName(), message); sent = true; } const BttvEmotes &TwitchIrcServer::getBttvEmotes() const { return this->bttv; } const FfzEmotes &TwitchIrcServer::getFfzEmotes() const { return this->ffz; } } // namespace chatterino <commit_msg>Revert "changed default port from 443 to 6697" It doens't appear to be the issue that builds aren't working<commit_after>#include "TwitchIrcServer.hpp" #include <IrcCommand> #include <cassert> #include "Application.hpp" #include "common/Common.hpp" #include "controllers/accounts/AccountController.hpp" #include "controllers/highlights/HighlightController.hpp" #include "messages/Message.hpp" #include "messages/MessageBuilder.hpp" #include "providers/twitch/ChatroomChannel.hpp" #include "providers/twitch/IrcMessageHandler.hpp" #include "providers/twitch/PubsubClient.hpp" #include "providers/twitch/TwitchAccount.hpp" #include "providers/twitch/TwitchChannel.hpp" #include "providers/twitch/TwitchHelpers.hpp" #include "providers/twitch/TwitchMessageBuilder.hpp" #include "util/PostToThread.hpp" // using namespace Communi; using namespace std::chrono_literals; namespace chatterino { namespace { bool isChatroom(const QString &channel) { if (channel.left(10) == "chatrooms:") { auto reflist = channel.splitRef(':'); if (reflist.size() == 3) { return true; } } return false; } } // namespace TwitchIrcServer::TwitchIrcServer() : whispersChannel(new Channel("/whispers", Channel::Type::TwitchWhispers)) , mentionsChannel(new Channel("/mentions", Channel::Type::TwitchMentions)) , watchingChannel(Channel::getEmpty(), Channel::Type::TwitchWatching) { this->pubsub = new PubSub; // getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { // this->connect(); }, // this->signalHolder_, // false); } void TwitchIrcServer::initialize(Settings &settings, Paths &paths) { getApp()->accounts->twitch.currentUserChanged.connect( [this]() { postToThread([this] { this->connect(); }); }); this->twitchBadges.loadTwitchBadges(); this->bttv.loadEmotes(); this->ffz.loadEmotes(); } void TwitchIrcServer::initializeConnection(IrcConnection *connection, ConnectionType type) { std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent(); qDebug() << "logging in as" << account->getUserName(); QString username = account->getUserName(); QString oauthToken = account->getOAuthToken(); if (!oauthToken.startsWith("oauth:")) { oauthToken.prepend("oauth:"); } connection->setUserName(username); connection->setNickName(username); connection->setRealName(username); if (!account->isAnon()) { connection->setPassword(oauthToken); } connection->setSecure(true); // https://dev.twitch.tv/docs/irc/guide/#connecting-to-twitch-irc // SSL disabled: irc://irc.chat.twitch.tv:6667 (or port 80) // SSL enabled: irc://irc.chat.twitch.tv:6697 (or port 443) connection->setHost("irc.chat.twitch.tv"); connection->setPort(443); this->open(type); } std::shared_ptr<Channel> TwitchIrcServer::createChannel( const QString &channelName) { std::shared_ptr<TwitchChannel> channel; if (isChatroom(channelName)) { channel = std::static_pointer_cast<TwitchChannel>( std::shared_ptr<ChatroomChannel>(new ChatroomChannel( channelName, this->twitchBadges, this->bttv, this->ffz))); } else { channel = std::shared_ptr<TwitchChannel>(new TwitchChannel( channelName, this->twitchBadges, this->bttv, this->ffz)); } channel->initialize(); channel->sendMessageSignal.connect( [this, channel = channel.get()](auto &chan, auto &msg, bool &sent) { this->onMessageSendRequested(channel, msg, sent); }); return std::shared_ptr<Channel>(channel); } void TwitchIrcServer::privateMessageReceived( Communi::IrcPrivateMessage *message) { IrcMessageHandler::getInstance().handlePrivMessage(message, *this); } void TwitchIrcServer::readConnectionMessageReceived( Communi::IrcMessage *message) { AbstractIrcServer::readConnectionMessageReceived(message); if (message->type() == Communi::IrcMessage::Type::Private) { // We already have a handler for private messages return; } const QString &command = message->command(); auto &handler = IrcMessageHandler::getInstance(); // Below commands enabled through the twitch.tv/membership CAP REQ if (command == "MODE") { handler.handleModeMessage(message); } else if (command == "JOIN") { handler.handleJoinMessage(message); } else if (command == "PART") { handler.handlePartMessage(message); } else if (command == "USERSTATE") { // Received USERSTATE upon JOINing a channel handler.handleUserStateMessage(message); } else if (command == "ROOMSTATE") { // Received ROOMSTATE upon JOINing a channel handler.handleRoomStateMessage(message); } else if (command == "CLEARCHAT") { handler.handleClearChatMessage(message); } else if (command == "CLEARMSG") { handler.handleClearMessageMessage(message); } else if (command == "USERNOTICE") { handler.handleUserNoticeMessage(message, *this); } else if (command == "NOTICE") { handler.handleNoticeMessage( static_cast<Communi::IrcNoticeMessage *>(message)); } else if (command == "WHISPER") { handler.handleWhisperMessage(message); } } void TwitchIrcServer::writeConnectionMessageReceived( Communi::IrcMessage *message) { const QString &command = message->command(); auto &handler = IrcMessageHandler::getInstance(); // Below commands enabled through the twitch.tv/commands CAP REQ if (command == "USERSTATE") { // Received USERSTATE upon PRIVMSGing handler.handleUserStateMessage(message); } else if (command == "NOTICE") { static std::unordered_set<std::string> readConnectionOnlyIDs{ "host_on", "host_off", "host_target_went_offline", "emote_only_on", "emote_only_off", "slow_on", "slow_off", "subs_on", "subs_off", "r9k_on", "r9k_off", // Display for user who times someone out. This implies you're a // moderator, at which point you will be connected to PubSub and receive // a better message from there. "timeout_success", "ban_success", // Channel suspended notices "msg_channel_suspended", }; handler.handleNoticeMessage( static_cast<Communi::IrcNoticeMessage *>(message)); } } void TwitchIrcServer::onReadConnected(IrcConnection *connection) { // twitch.tv/tags enables IRCv3 tags on messages. See https://dev.twitch.tv/docs/irc/tags/ // twitch.tv/membership enables the JOIN/PART/MODE/NAMES commands. See https://dev.twitch.tv/docs/irc/membership/ // twitch.tv/commands enables a bunch of miscellaneous command capabilities. See https://dev.twitch.tv/docs/irc/commands/ // This is enabled here so we receive USERSTATE messages when joining channels connection->sendRaw( "CAP REQ :twitch.tv/tags twitch.tv/membership twitch.tv/commands"); AbstractIrcServer::onReadConnected(connection); } void TwitchIrcServer::onWriteConnected(IrcConnection *connection) { // twitch.tv/tags enables IRCv3 tags on messages. See https://dev.twitch.tv/docs/irc/tags/ // twitch.tv/commands enables a bunch of miscellaneous command capabilities. See https://dev.twitch.tv/docs/irc/commands/ // This is enabled here so we receive USERSTATE messages when typing messages, along with the other command capabilities connection->sendRaw("CAP REQ :twitch.tv/tags twitch.tv/commands"); AbstractIrcServer::onWriteConnected(connection); } std::shared_ptr<Channel> TwitchIrcServer::getCustomChannel( const QString &channelName) { if (channelName == "/whispers") { return this->whispersChannel; } if (channelName == "/mentions") { return this->mentionsChannel; } if (channelName == "$$$") { static auto channel = std::make_shared<Channel>("$$$", chatterino::Channel::Type::Misc); static auto getTimer = [&] { for (auto i = 0; i < 1000; i++) { channel->addMessage(makeSystemMessage(QString::number(i + 1))); } auto timer = new QTimer; QObject::connect(timer, &QTimer::timeout, [] { channel->addMessage( makeSystemMessage(QTime::currentTime().toString())); }); timer->start(500); return timer; }(); return channel; } return nullptr; } void TwitchIrcServer::forEachChannelAndSpecialChannels( std::function<void(ChannelPtr)> func) { this->forEachChannel(func); func(this->whispersChannel); func(this->mentionsChannel); } std::shared_ptr<Channel> TwitchIrcServer::getChannelOrEmptyByID( const QString &channelId) { std::lock_guard<std::mutex> lock(this->channelMutex); for (const auto &weakChannel : this->channels) { auto channel = weakChannel.lock(); if (!channel) continue; auto twitchChannel = std::dynamic_pointer_cast<TwitchChannel>(channel); if (!twitchChannel) continue; if (twitchChannel->roomId() == channelId && twitchChannel->getName().splitRef(":").size() < 3) { return twitchChannel; } } return Channel::getEmpty(); } QString TwitchIrcServer::cleanChannelName(const QString &dirtyChannelName) { if (dirtyChannelName.startsWith('#')) return dirtyChannelName.mid(1).toLower(); else return dirtyChannelName.toLower(); } bool TwitchIrcServer::hasSeparateWriteConnection() const { return true; // return getSettings()->twitchSeperateWriteConnection; } void TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent) { sent = false; { std::lock_guard<std::mutex> guard(this->lastMessageMutex_); // std::queue<std::chrono::steady_clock::time_point> auto &lastMessage = channel->hasHighRateLimit() ? this->lastMessageMod_ : this->lastMessagePleb_; size_t maxMessageCount = channel->hasHighRateLimit() ? 99 : 19; auto minMessageOffset = (channel->hasHighRateLimit() ? 100ms : 1100ms); auto now = std::chrono::steady_clock::now(); // check if you are sending messages too fast if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) { if (this->lastErrorTimeSpeed_ + 30s < now) { auto errorMessage = makeSystemMessage("sending messages too fast"); channel->addMessage(errorMessage); this->lastErrorTimeSpeed_ = now; } return; } // remove messages older than 30 seconds while (!lastMessage.empty() && lastMessage.front() + 32s < now) { lastMessage.pop(); } // check if you are sending too many messages if (lastMessage.size() >= maxMessageCount) { if (this->lastErrorTimeAmount_ + 30s < now) { auto errorMessage = makeSystemMessage("sending too many messages"); channel->addMessage(errorMessage); this->lastErrorTimeAmount_ = now; } return; } lastMessage.push(now); } this->sendMessage(channel->getName(), message); sent = true; } const BttvEmotes &TwitchIrcServer::getBttvEmotes() const { return this->bttv; } const FfzEmotes &TwitchIrcServer::getFfzEmotes() const { return this->ffz; } } // namespace chatterino <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. 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/>. */ #include "pushnotification.hh" #include <string.h> #include <stdexcept> #include <boost/asio.hpp> #include <common.hh> #include <iostream> using namespace ::std; const unsigned int ApplePushNotificationRequest::MAXPAYLOAD_SIZE = 256; const unsigned int ApplePushNotificationRequest::DEVICE_BINARY_SIZE = 32; ApplePushNotificationRequest::ApplePushNotificationRequest(const string &appId, const string &deviceToken, const string &msg_id, const string &arg, const string &sound, const string &callid) : PushNotificationRequest(appId, "apple") { ostringstream payload; int ret = formatDeviceToken(deviceToken); if ((ret != 0) || (mDeviceToken.size() != DEVICE_BINARY_SIZE)) { throw runtime_error("ApplePushNotification: Invalid deviceToken"); return; } payload << "{\"aps\":{\"content-available\":1,\"alert\":{\"loc-key\":\"" << msg_id << "\",\"loc-args\":[\"" << arg << "\"]},\"sound\":\"" << sound << "\"},\"call-id\":\"" << callid << "\",\"pn_ttl\":60}"; // PN expiration set to 60 seconds. if (payload.str().length() > MAXPAYLOAD_SIZE) { return; } mPayload = payload.str(); LOGD("Push notification payload is %s", mPayload.c_str()); } GooglePushNotificationRequest::GooglePushNotificationRequest(const string &appId, const string &deviceToken, const string &apiKey, const string &arg, const string &callid) : PushNotificationRequest(appId, "google") { ostringstream httpBody; httpBody << "{\"registration_ids\":[\"" << deviceToken << "\"],\"data\":{\"loc-args\":\"" << arg << "\"}" ",\"call-id\":\"" <<callid<< "\"}"; mHttpBody = httpBody.str(); LOGD("Push notification https post body is %s", mHttpBody.c_str()); ostringstream httpHeader; httpHeader << "POST /gcm/send HTTP/1.1\r\nHost:android.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key=" << apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; mHttpHeader = httpHeader.str(); LOGD("Push notification https post header is %s", mHttpHeader.c_str()); } WindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest(const string &host, const string &query, bool is_message, const std::string &message, const std::string &sender_name, const std::string &sender_uri) : PushNotificationRequest(host, "wp") { ostringstream httpBody; if (is_message) { // We have to send the content of the message and the name of the sender. // We also need the sender address to be able to display the full chat view in case the receiver click the toast. httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>" << sender_name << "</wp:Text1><wp:Text2>" << message << "</wp:Text2><wp:Param>" << "/Views/Chat.xaml?sip=" << sender_uri << "</wp:Param></wp:Toast></wp:Notification>"; } else { // No need to specify name or number, this PN will only wake up linphone. httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><IncomingCall><Name></Name><Number></Number></IncomingCall>"; } mHttpBody = httpBody.str(); LOGD("Push notification https post body is %s", mHttpBody.c_str()); ostringstream httpHeader; if (is_message) { // Notification class 2 is the type for toast notifitcation. httpHeader << "POST " << query << " HTTP/1.1\r\nHost:" << host <<"\r\nX-WindowsPhone-Target:toast\r\nX-NotificationClass:2\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; } else { // Notification class 4 is the type for VoIP incoming call. httpHeader << "POST " << query << " HTTP/1.1\r\nHost:" << host <<"\r\nX-NotificationClass:4\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; } mHttpHeader = httpHeader.str(); LOGD("Push notification https post header is %s", mHttpHeader.c_str()); } const vector<char> & ApplePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } int ApplePushNotificationRequest::formatDeviceToken(const string &deviceToken) { char car = 0; char oct = 0; char val; mDeviceToken.clear(); for (unsigned int i = 0; i < deviceToken.length(); ++i) { char tokenCar = deviceToken[i]; if (tokenCar >= '0' && tokenCar <= '9') { val = tokenCar - '0'; } else if (tokenCar >= 'a' && tokenCar <= 'f') { val = tokenCar - 'a' + 10; } else if (tokenCar >= 'A' && tokenCar <= 'F') { val = tokenCar - 'A' + 10; } else if (tokenCar == ' ' || tokenCar == '\t') { continue; } else { return -1; } if (oct) { car |= val & 0x0f; } else { car = val << 4; } oct = 1 - oct; if (oct == 0) { mDeviceToken.push_back(car); } } return 0; } void ApplePushNotificationRequest::createPushNotification() { unsigned int payloadLength = mPayload.length(); /* Init */ mBuffer.clear(); /* message format is, |COMMAND|TOKENLEN|TOKEN|PAYLOADLEN|PAYLOAD| */ mBuffer.resize(sizeof(uint8_t) + sizeof(uint16_t) + DEVICE_BINARY_SIZE + sizeof(uint16_t) + payloadLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; /* Compute PushNotification */ uint8_t command = 0; /* command number */ uint16_t networkOrderTokenLength = htons(DEVICE_BINARY_SIZE); uint16_t networkOrderPayloadLength = htons(payloadLength); /* command */ *binaryMessagePt++ = command; /* token length network order */ memcpy(binaryMessagePt, &networkOrderTokenLength, sizeof(uint16_t)); binaryMessagePt += sizeof(uint16_t); /* device token */ memcpy(binaryMessagePt, &mDeviceToken[0], DEVICE_BINARY_SIZE); binaryMessagePt += DEVICE_BINARY_SIZE; /* payload length network order */ memcpy(binaryMessagePt, &networkOrderPayloadLength, sizeof(uint16_t)); binaryMessagePt += sizeof(uint16_t); /* payload */ memcpy(binaryMessagePt, &mPayload[0], payloadLength); binaryMessagePt += payloadLength; } void GooglePushNotificationRequest::createPushNotification() { int headerLength = mHttpHeader.length(); int bodyLength = mHttpBody.length(); mBuffer.clear(); mBuffer.resize(headerLength + bodyLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; memcpy(binaryMessagePt, &mHttpHeader[0], headerLength); binaryMessagePt += headerLength; memcpy(binaryMessagePt, &mHttpBody[0], bodyLength); binaryMessagePt += bodyLength; } void WindowsPhonePushNotificationRequest::createPushNotification() { int headerLength = mHttpHeader.length(); int bodyLength = mHttpBody.length(); mBuffer.clear(); mBuffer.resize(headerLength + bodyLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; memcpy(binaryMessagePt, &mHttpHeader[0], headerLength); binaryMessagePt += headerLength; memcpy(binaryMessagePt, &mHttpBody[0], bodyLength); binaryMessagePt += bodyLength; } const vector<char> & GooglePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } const vector<char> & WindowsPhonePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } bool ApplePushNotificationRequest::isValidResponse(const string &str) { return true; } bool WindowsPhonePushNotificationRequest::isValidResponse(const string &str) { string line; istringstream iss(str); bool connect, notif, subscr = notif = connect = false; while (getline(iss, line)) { if (!connect) connect = line.find("X-DeviceConnectionStatus: Connected") != string::npos; if (!notif) notif = line.find("X-NotificationStatus: Received") != string::npos; if (!subscr) subscr = line.find("X-SubscriptionStatus: Active") != string::npos; } return connect && notif && subscr; } bool GooglePushNotificationRequest::isValidResponse(const string &str) { static const char expected[] = "HTTP/1.1 200"; return strncmp(expected, str.c_str(), sizeof(expected)) == 0; } bool ErrorPushNotificationRequest::isValidResponse(const string &str) { return false; } <commit_msg>Fix Google push response comparison.<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2012 Belledonne Communications SARL. 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/>. */ #include "pushnotification.hh" #include <string.h> #include <stdexcept> #include <boost/asio.hpp> #include <common.hh> #include <iostream> using namespace ::std; const unsigned int ApplePushNotificationRequest::MAXPAYLOAD_SIZE = 256; const unsigned int ApplePushNotificationRequest::DEVICE_BINARY_SIZE = 32; ApplePushNotificationRequest::ApplePushNotificationRequest(const string &appId, const string &deviceToken, const string &msg_id, const string &arg, const string &sound, const string &callid) : PushNotificationRequest(appId, "apple") { ostringstream payload; int ret = formatDeviceToken(deviceToken); if ((ret != 0) || (mDeviceToken.size() != DEVICE_BINARY_SIZE)) { throw runtime_error("ApplePushNotification: Invalid deviceToken"); return; } payload << "{\"aps\":{\"content-available\":1,\"alert\":{\"loc-key\":\"" << msg_id << "\",\"loc-args\":[\"" << arg << "\"]},\"sound\":\"" << sound << "\"},\"call-id\":\"" << callid << "\",\"pn_ttl\":60}"; // PN expiration set to 60 seconds. if (payload.str().length() > MAXPAYLOAD_SIZE) { return; } mPayload = payload.str(); LOGD("Push notification payload is %s", mPayload.c_str()); } GooglePushNotificationRequest::GooglePushNotificationRequest(const string &appId, const string &deviceToken, const string &apiKey, const string &arg, const string &callid) : PushNotificationRequest(appId, "google") { ostringstream httpBody; httpBody << "{\"registration_ids\":[\"" << deviceToken << "\"],\"data\":{\"loc-args\":\"" << arg << "\"}" ",\"call-id\":\"" <<callid<< "\"}"; mHttpBody = httpBody.str(); LOGD("Push notification https post body is %s", mHttpBody.c_str()); ostringstream httpHeader; httpHeader << "POST /gcm/send HTTP/1.1\r\nHost:android.googleapis.com\r\nContent-Type:application/json\r\nAuthorization:key=" << apiKey << "\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; mHttpHeader = httpHeader.str(); SLOGD << "PNR " << this << " https post header is " << mHttpHeader; } WindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest(const string &host, const string &query, bool is_message, const std::string &message, const std::string &sender_name, const std::string &sender_uri) : PushNotificationRequest(host, "wp") { ostringstream httpBody; if (is_message) { // We have to send the content of the message and the name of the sender. // We also need the sender address to be able to display the full chat view in case the receiver click the toast. httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>" << sender_name << "</wp:Text1><wp:Text2>" << message << "</wp:Text2><wp:Param>" << "/Views/Chat.xaml?sip=" << sender_uri << "</wp:Param></wp:Toast></wp:Notification>"; } else { // No need to specify name or number, this PN will only wake up linphone. httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><IncomingCall><Name></Name><Number></Number></IncomingCall>"; } mHttpBody = httpBody.str(); LOGD("Push notification https post body is %s", mHttpBody.c_str()); ostringstream httpHeader; if (is_message) { // Notification class 2 is the type for toast notifitcation. httpHeader << "POST " << query << " HTTP/1.1\r\nHost:" << host <<"\r\nX-WindowsPhone-Target:toast\r\nX-NotificationClass:2\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; } else { // Notification class 4 is the type for VoIP incoming call. httpHeader << "POST " << query << " HTTP/1.1\r\nHost:" << host <<"\r\nX-NotificationClass:4\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size() << "\r\n\r\n"; } mHttpHeader = httpHeader.str(); SLOGD << "PNR " << this << " https post header is " << mHttpHeader; } const vector<char> & ApplePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } int ApplePushNotificationRequest::formatDeviceToken(const string &deviceToken) { char car = 0; char oct = 0; char val; mDeviceToken.clear(); for (unsigned int i = 0; i < deviceToken.length(); ++i) { char tokenCar = deviceToken[i]; if (tokenCar >= '0' && tokenCar <= '9') { val = tokenCar - '0'; } else if (tokenCar >= 'a' && tokenCar <= 'f') { val = tokenCar - 'a' + 10; } else if (tokenCar >= 'A' && tokenCar <= 'F') { val = tokenCar - 'A' + 10; } else if (tokenCar == ' ' || tokenCar == '\t') { continue; } else { return -1; } if (oct) { car |= val & 0x0f; } else { car = val << 4; } oct = 1 - oct; if (oct == 0) { mDeviceToken.push_back(car); } } return 0; } void ApplePushNotificationRequest::createPushNotification() { unsigned int payloadLength = mPayload.length(); /* Init */ mBuffer.clear(); /* message format is, |COMMAND|TOKENLEN|TOKEN|PAYLOADLEN|PAYLOAD| */ mBuffer.resize(sizeof(uint8_t) + sizeof(uint16_t) + DEVICE_BINARY_SIZE + sizeof(uint16_t) + payloadLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; /* Compute PushNotification */ uint8_t command = 0; /* command number */ uint16_t networkOrderTokenLength = htons(DEVICE_BINARY_SIZE); uint16_t networkOrderPayloadLength = htons(payloadLength); /* command */ *binaryMessagePt++ = command; /* token length network order */ memcpy(binaryMessagePt, &networkOrderTokenLength, sizeof(uint16_t)); binaryMessagePt += sizeof(uint16_t); /* device token */ memcpy(binaryMessagePt, &mDeviceToken[0], DEVICE_BINARY_SIZE); binaryMessagePt += DEVICE_BINARY_SIZE; /* payload length network order */ memcpy(binaryMessagePt, &networkOrderPayloadLength, sizeof(uint16_t)); binaryMessagePt += sizeof(uint16_t); /* payload */ memcpy(binaryMessagePt, &mPayload[0], payloadLength); binaryMessagePt += payloadLength; } void GooglePushNotificationRequest::createPushNotification() { int headerLength = mHttpHeader.length(); int bodyLength = mHttpBody.length(); mBuffer.clear(); mBuffer.resize(headerLength + bodyLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; memcpy(binaryMessagePt, &mHttpHeader[0], headerLength); binaryMessagePt += headerLength; memcpy(binaryMessagePt, &mHttpBody[0], bodyLength); binaryMessagePt += bodyLength; } void WindowsPhonePushNotificationRequest::createPushNotification() { int headerLength = mHttpHeader.length(); int bodyLength = mHttpBody.length(); mBuffer.clear(); mBuffer.resize(headerLength + bodyLength); char *binaryMessageBuff = &mBuffer[0]; char *binaryMessagePt = binaryMessageBuff; memcpy(binaryMessagePt, &mHttpHeader[0], headerLength); binaryMessagePt += headerLength; memcpy(binaryMessagePt, &mHttpBody[0], bodyLength); binaryMessagePt += bodyLength; } const vector<char> & GooglePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } const vector<char> & WindowsPhonePushNotificationRequest::getData() { createPushNotification(); return mBuffer; } bool ApplePushNotificationRequest::isValidResponse(const string &str) { return true; } bool WindowsPhonePushNotificationRequest::isValidResponse(const string &str) { string line; istringstream iss(str); bool connect, notif, subscr = notif = connect = false; while (getline(iss, line)) { if (!connect) connect = line.find("X-DeviceConnectionStatus: Connected") != string::npos; if (!notif) notif = line.find("X-NotificationStatus: Received") != string::npos; if (!subscr) subscr = line.find("X-SubscriptionStatus: Active") != string::npos; } return connect && notif && subscr; } bool GooglePushNotificationRequest::isValidResponse(const string &str) { static const char expected[] = "HTTP/1.1 200"; return strncmp(expected, str.c_str(), sizeof(expected) -1) == 0; } bool ErrorPushNotificationRequest::isValidResponse(const string &str) { return false; } <|endoftext|>
<commit_before>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "MockMavlinkFileServer.h" const MockMavlinkFileServer::FileTestCase MockMavlinkFileServer::rgFileTestCases[MockMavlinkFileServer::cFileTestCases] = { // File fits one Read Ack packet, partially filling data { "partial.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) - 1 }, // File fits one Read Ack packet, exactly filling all data { "exact.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) }, // File is larger than a single Read Ack packets, requires multiple Reads { "multi.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) + 1 }, }; // We only support a single fixed session const uint8_t MockMavlinkFileServer::_sessionId = 1; MockMavlinkFileServer::MockMavlinkFileServer(void) { } /// @brief Handles List command requests. Only supports root folder paths. /// File list returned is set using the setFileList method. void MockMavlinkFileServer::_listCommand(QGCUASFileManager::Request* request) { // FIXME: Does not support directories that span multiple packets QGCUASFileManager::Request ackResponse; QString path; // We only support root path path = (char *)&request->data[0]; if (!path.isEmpty() && path != "/") { _sendNak(QGCUASFileManager::kErrNotDir); return; } // Offset requested is past the end of the list if (request->hdr.offset > (uint32_t)_fileList.size()) { _sendNak(QGCUASFileManager::kErrEOF); return; } ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.offset = request->hdr.offset; ackResponse.hdr.size = 0; if (request->hdr.offset == 0) { // Requesting first batch of file names Q_ASSERT(_fileList.size()); char *bufPtr = (char *)&ackResponse.data[0]; for (int i=0; i<_fileList.size(); i++) { strcpy(bufPtr, _fileList[i].toStdString().c_str()); size_t cchFilename = strlen(bufPtr); Q_ASSERT(cchFilename); ackResponse.hdr.size += cchFilename + 1; bufPtr += cchFilename + 1; } _emitResponse(&ackResponse); } else { // FIXME: Does not support directories that span multiple packets _sendNak(QGCUASFileManager::kErrEOF); } } /// @brief Handles Open command requests. void MockMavlinkFileServer::_openCommand(QGCUASFileManager::Request* request) { QGCUASFileManager::Request response; QString path; size_t cchPath = strnlen((char *)request->data, sizeof(request->data)); Q_ASSERT(cchPath != sizeof(request->data)); path = (char *)request->data; // Check path against one of our known test cases bool found = false; for (size_t i=0; i<cFileTestCases; i++) { if (path == rgFileTestCases[i].filename) { found = true; _readFileLength = rgFileTestCases[i].length; break; } } if (!found) { _sendNak(QGCUASFileManager::kErrNotFile); return; } response.hdr.magic = 'f'; response.hdr.opcode = QGCUASFileManager::kRspAck; response.hdr.session = _sessionId; response.hdr.size = 0; _emitResponse(&response); } /// @brief Handles Read command requests. void MockMavlinkFileServer::_readCommand(QGCUASFileManager::Request* request) { QGCUASFileManager::Request response; if (request->hdr.session != _sessionId) { _sendNak(QGCUASFileManager::kErrNoSession); return; } uint32_t readOffset = request->hdr.offset; // offset into file for reading uint8_t cDataBytes = 0; // current number of data bytes used if (readOffset >= _readFileLength) { _sendNak(QGCUASFileManager::kErrEOF); return; } // Write length byte if needed if (readOffset == 0) { response.data[0] = _readFileLength; readOffset++; cDataBytes++; } // Write file bytes. Data is a repeating sequence of 0x00, 0x01, .. 0xFF. for (; cDataBytes < sizeof(response.data) && readOffset < _readFileLength; readOffset++, cDataBytes++) { // Subtract one from readOffset to take into account length byte and start file data a 0x00 response.data[cDataBytes] = (readOffset - 1) & 0xFF; } // We should always have written something, otherwise there is something wrong with the code above Q_ASSERT(cDataBytes); response.hdr.magic = 'f'; response.hdr.session = _sessionId; response.hdr.size = cDataBytes; response.hdr.offset = request->hdr.offset; response.hdr.opcode = QGCUASFileManager::kRspAck; _emitResponse(&response); } /// @brief Handles Terminate commands void MockMavlinkFileServer::_terminateCommand(QGCUASFileManager::Request* request) { if (request->hdr.session != _sessionId) { _sendNak(QGCUASFileManager::kErrNoSession); return; } _sendAck(); // Let our test harness know that we got a terminate command. This is used to validate the a Terminate is correctly // sent after an Open. emit terminateCommandReceived(); } /// @brief Handles messages sent to the FTP server. void MockMavlinkFileServer::sendMessage(mavlink_message_t message) { QGCUASFileManager::Request ackResponse; Q_ASSERT(message.msgid == MAVLINK_MSG_ID_ENCAPSULATED_DATA); mavlink_encapsulated_data_t requestEncapsulatedData; mavlink_msg_encapsulated_data_decode(&message, &requestEncapsulatedData); QGCUASFileManager::Request* request = (QGCUASFileManager::Request*)&requestEncapsulatedData.data[0]; // Validate CRC if (request->hdr.crc32 != QGCUASFileManager::crc32(request)) { _sendNak(QGCUASFileManager::kErrCrc); } switch (request->hdr.opcode) { case QGCUASFileManager::kCmdTestNoAck: // ignored, ack not sent back, for testing only break; case QGCUASFileManager::kCmdReset: // terminates all sessions // Fall through to send back Ack case QGCUASFileManager::kCmdNone: // ignored, always acked ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.crc32 = 0; ackResponse.hdr.size = 0; _emitResponse(&ackResponse); break; case QGCUASFileManager::kCmdList: _listCommand(request); break; case QGCUASFileManager::kCmdOpen: _openCommand(request); break; case QGCUASFileManager::kCmdRead: _readCommand(request); break; case QGCUASFileManager::kCmdTerminate: _terminateCommand(request); break; // Remainder of commands are NYI case QGCUASFileManager::kCmdCreate: // creates <path> for writing, returns <session> case QGCUASFileManager::kCmdWrite: // appends <size> bytes at <offset> in <session> case QGCUASFileManager::kCmdRemove: // remove file (only if created by server?) default: // nack for all NYI opcodes _sendNak(QGCUASFileManager::kErrUnknownCommand); break; } } /// @brief Sends an Ack void MockMavlinkFileServer::_sendAck(void) { QGCUASFileManager::Request ackResponse; ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.size = 0; _emitResponse(&ackResponse); } /// @brief Sends a Nak with the specified error code. void MockMavlinkFileServer::_sendNak(QGCUASFileManager::ErrorCode error) { QGCUASFileManager::Request nakResponse; nakResponse.hdr.magic = 'f'; nakResponse.hdr.opcode = QGCUASFileManager::kRspNak; nakResponse.hdr.session = 0; nakResponse.hdr.size = 1; nakResponse.data[0] = error; _emitResponse(&nakResponse); } /// @brief Emits a Request through the messageReceived signal. void MockMavlinkFileServer::_emitResponse(QGCUASFileManager::Request* request) { mavlink_message_t mavlinkMessage; request->hdr.crc32 = QGCUASFileManager::crc32(request); mavlink_msg_encapsulated_data_pack(250, 0, &mavlinkMessage, 0 /*_encdata_seq*/, (uint8_t*)request); emit messageReceived(NULL, mavlinkMessage); } <commit_msg>Corrected copy/paste error resulting in unused variable warning.<commit_after>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "MockMavlinkFileServer.h" const MockMavlinkFileServer::FileTestCase MockMavlinkFileServer::rgFileTestCases[MockMavlinkFileServer::cFileTestCases] = { // File fits one Read Ack packet, partially filling data { "partial.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) - 1 }, // File fits one Read Ack packet, exactly filling all data { "exact.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) }, // File is larger than a single Read Ack packets, requires multiple Reads { "multi.qgc", sizeof(((QGCUASFileManager::Request*)0)->data) + 1 }, }; // We only support a single fixed session const uint8_t MockMavlinkFileServer::_sessionId = 1; MockMavlinkFileServer::MockMavlinkFileServer(void) { } /// @brief Handles List command requests. Only supports root folder paths. /// File list returned is set using the setFileList method. void MockMavlinkFileServer::_listCommand(QGCUASFileManager::Request* request) { // FIXME: Does not support directories that span multiple packets QGCUASFileManager::Request ackResponse; QString path; // We only support root path path = (char *)&request->data[0]; if (!path.isEmpty() && path != "/") { _sendNak(QGCUASFileManager::kErrNotDir); return; } // Offset requested is past the end of the list if (request->hdr.offset > (uint32_t)_fileList.size()) { _sendNak(QGCUASFileManager::kErrEOF); return; } ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.offset = request->hdr.offset; ackResponse.hdr.size = 0; if (request->hdr.offset == 0) { // Requesting first batch of file names Q_ASSERT(_fileList.size()); char *bufPtr = (char *)&ackResponse.data[0]; for (int i=0; i<_fileList.size(); i++) { strcpy(bufPtr, _fileList[i].toStdString().c_str()); size_t cchFilename = strlen(bufPtr); Q_ASSERT(cchFilename); ackResponse.hdr.size += cchFilename + 1; bufPtr += cchFilename + 1; } _emitResponse(&ackResponse); } else { // FIXME: Does not support directories that span multiple packets _sendNak(QGCUASFileManager::kErrEOF); } } /// @brief Handles Open command requests. void MockMavlinkFileServer::_openCommand(QGCUASFileManager::Request* request) { QGCUASFileManager::Request response; QString path; size_t cchPath = strnlen((char *)request->data, sizeof(request->data)); Q_ASSERT(cchPath != sizeof(request->data)); Q_UNUSED(cchPath); // Fix initialized-but-not-referenced warning on release builds path = (char *)request->data; // Check path against one of our known test cases bool found = false; for (size_t i=0; i<cFileTestCases; i++) { if (path == rgFileTestCases[i].filename) { found = true; _readFileLength = rgFileTestCases[i].length; break; } } if (!found) { _sendNak(QGCUASFileManager::kErrNotFile); return; } response.hdr.magic = 'f'; response.hdr.opcode = QGCUASFileManager::kRspAck; response.hdr.session = _sessionId; response.hdr.size = 0; _emitResponse(&response); } /// @brief Handles Read command requests. void MockMavlinkFileServer::_readCommand(QGCUASFileManager::Request* request) { QGCUASFileManager::Request response; if (request->hdr.session != _sessionId) { _sendNak(QGCUASFileManager::kErrNoSession); return; } uint32_t readOffset = request->hdr.offset; // offset into file for reading uint8_t cDataBytes = 0; // current number of data bytes used if (readOffset >= _readFileLength) { _sendNak(QGCUASFileManager::kErrEOF); return; } // Write length byte if needed if (readOffset == 0) { response.data[0] = _readFileLength; readOffset++; cDataBytes++; } // Write file bytes. Data is a repeating sequence of 0x00, 0x01, .. 0xFF. for (; cDataBytes < sizeof(response.data) && readOffset < _readFileLength; readOffset++, cDataBytes++) { // Subtract one from readOffset to take into account length byte and start file data a 0x00 response.data[cDataBytes] = (readOffset - 1) & 0xFF; } // We should always have written something, otherwise there is something wrong with the code above Q_ASSERT(cDataBytes); response.hdr.magic = 'f'; response.hdr.session = _sessionId; response.hdr.size = cDataBytes; response.hdr.offset = request->hdr.offset; response.hdr.opcode = QGCUASFileManager::kRspAck; _emitResponse(&response); } /// @brief Handles Terminate commands void MockMavlinkFileServer::_terminateCommand(QGCUASFileManager::Request* request) { if (request->hdr.session != _sessionId) { _sendNak(QGCUASFileManager::kErrNoSession); return; } _sendAck(); // Let our test harness know that we got a terminate command. This is used to validate the a Terminate is correctly // sent after an Open. emit terminateCommandReceived(); } /// @brief Handles messages sent to the FTP server. void MockMavlinkFileServer::sendMessage(mavlink_message_t message) { QGCUASFileManager::Request ackResponse; Q_ASSERT(message.msgid == MAVLINK_MSG_ID_ENCAPSULATED_DATA); mavlink_encapsulated_data_t requestEncapsulatedData; mavlink_msg_encapsulated_data_decode(&message, &requestEncapsulatedData); QGCUASFileManager::Request* request = (QGCUASFileManager::Request*)&requestEncapsulatedData.data[0]; // Validate CRC if (request->hdr.crc32 != QGCUASFileManager::crc32(request)) { _sendNak(QGCUASFileManager::kErrCrc); } switch (request->hdr.opcode) { case QGCUASFileManager::kCmdTestNoAck: // ignored, ack not sent back, for testing only break; case QGCUASFileManager::kCmdReset: // terminates all sessions // Fall through to send back Ack case QGCUASFileManager::kCmdNone: // ignored, always acked ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.crc32 = 0; ackResponse.hdr.size = 0; _emitResponse(&ackResponse); break; case QGCUASFileManager::kCmdList: _listCommand(request); break; case QGCUASFileManager::kCmdOpen: _openCommand(request); break; case QGCUASFileManager::kCmdRead: _readCommand(request); break; case QGCUASFileManager::kCmdTerminate: _terminateCommand(request); break; // Remainder of commands are NYI case QGCUASFileManager::kCmdCreate: // creates <path> for writing, returns <session> case QGCUASFileManager::kCmdWrite: // appends <size> bytes at <offset> in <session> case QGCUASFileManager::kCmdRemove: // remove file (only if created by server?) default: // nack for all NYI opcodes _sendNak(QGCUASFileManager::kErrUnknownCommand); break; } } /// @brief Sends an Ack void MockMavlinkFileServer::_sendAck(void) { QGCUASFileManager::Request ackResponse; ackResponse.hdr.magic = 'f'; ackResponse.hdr.opcode = QGCUASFileManager::kRspAck; ackResponse.hdr.session = 0; ackResponse.hdr.size = 0; _emitResponse(&ackResponse); } /// @brief Sends a Nak with the specified error code. void MockMavlinkFileServer::_sendNak(QGCUASFileManager::ErrorCode error) { QGCUASFileManager::Request nakResponse; nakResponse.hdr.magic = 'f'; nakResponse.hdr.opcode = QGCUASFileManager::kRspNak; nakResponse.hdr.session = 0; nakResponse.hdr.size = 1; nakResponse.data[0] = error; _emitResponse(&nakResponse); } /// @brief Emits a Request through the messageReceived signal. void MockMavlinkFileServer::_emitResponse(QGCUASFileManager::Request* request) { mavlink_message_t mavlinkMessage; request->hdr.crc32 = QGCUASFileManager::crc32(request); mavlink_msg_encapsulated_data_pack(250, 0, &mavlinkMessage, 0 /*_encdata_seq*/, (uint8_t*)request); emit messageReceived(NULL, mavlinkMessage); } <|endoftext|>