text
stringlengths
54
60.6k
<commit_before>c10af5da-2e4e-11e5-9284-b827eb9e62be<commit_msg>c10feaea-2e4e-11e5-9284-b827eb9e62be<commit_after>c10feaea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0a58f250-2e4f-11e5-9284-b827eb9e62be<commit_msg>0a5e063c-2e4f-11e5-9284-b827eb9e62be<commit_after>0a5e063c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6a9b7842-2e4d-11e5-9284-b827eb9e62be<commit_msg>6aa07cd4-2e4d-11e5-9284-b827eb9e62be<commit_after>6aa07cd4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d8db27ea-2e4c-11e5-9284-b827eb9e62be<commit_msg>d8e036a4-2e4c-11e5-9284-b827eb9e62be<commit_after>d8e036a4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1c441834-2e4d-11e5-9284-b827eb9e62be<commit_msg>1c4a2f6c-2e4d-11e5-9284-b827eb9e62be<commit_after>1c4a2f6c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dd9473e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>dd996e0c-2e4e-11e5-9284-b827eb9e62be<commit_after>dd996e0c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3d10b360-2e4d-11e5-9284-b827eb9e62be<commit_msg>3d15bd56-2e4d-11e5-9284-b827eb9e62be<commit_after>3d15bd56-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1fdddd16-2e4f-11e5-9284-b827eb9e62be<commit_msg>1fe2d8b6-2e4f-11e5-9284-b827eb9e62be<commit_after>1fe2d8b6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8251f780-2e4e-11e5-9284-b827eb9e62be<commit_msg>825700d6-2e4e-11e5-9284-b827eb9e62be<commit_after>825700d6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f5364706-2e4e-11e5-9284-b827eb9e62be<commit_msg>f53b3e6e-2e4e-11e5-9284-b827eb9e62be<commit_after>f53b3e6e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fc890b74-2e4e-11e5-9284-b827eb9e62be<commit_msg>fc8e1c5e-2e4e-11e5-9284-b827eb9e62be<commit_after>fc8e1c5e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fa25c6ec-2e4e-11e5-9284-b827eb9e62be<commit_msg>fa2ad25e-2e4e-11e5-9284-b827eb9e62be<commit_after>fa2ad25e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c2b0850e-2e4d-11e5-9284-b827eb9e62be<commit_msg>c2b59710-2e4d-11e5-9284-b827eb9e62be<commit_after>c2b59710-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b30ab6ec-2e4d-11e5-9284-b827eb9e62be<commit_msg>b30fa79c-2e4d-11e5-9284-b827eb9e62be<commit_after>b30fa79c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aaac43e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>aab146a4-2e4e-11e5-9284-b827eb9e62be<commit_after>aab146a4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>49ad1e5a-2e4e-11e5-9284-b827eb9e62be<commit_msg>49b21f22-2e4e-11e5-9284-b827eb9e62be<commit_after>49b21f22-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>569290c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>56979b8c-2e4d-11e5-9284-b827eb9e62be<commit_after>56979b8c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8140737c-2e4d-11e5-9284-b827eb9e62be<commit_msg>8145663e-2e4d-11e5-9284-b827eb9e62be<commit_after>8145663e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4348b10a-2e4e-11e5-9284-b827eb9e62be<commit_msg>434db998-2e4e-11e5-9284-b827eb9e62be<commit_after>434db998-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2d2cb570-2e4d-11e5-9284-b827eb9e62be<commit_msg>2d31a8d2-2e4d-11e5-9284-b827eb9e62be<commit_after>2d31a8d2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0b0e18f6-2e4f-11e5-9284-b827eb9e62be<commit_msg>0b1311c6-2e4f-11e5-9284-b827eb9e62be<commit_after>0b1311c6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>94e997fe-2e4e-11e5-9284-b827eb9e62be<commit_msg>94ee936c-2e4e-11e5-9284-b827eb9e62be<commit_after>94ee936c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2bf81b5e-2e4d-11e5-9284-b827eb9e62be<commit_msg>2bfd0966-2e4d-11e5-9284-b827eb9e62be<commit_after>2bfd0966-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f7fb94b6-2e4c-11e5-9284-b827eb9e62be<commit_msg>f8009d12-2e4c-11e5-9284-b827eb9e62be<commit_after>f8009d12-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3138fb6e-2e4e-11e5-9284-b827eb9e62be<commit_msg>313df790-2e4e-11e5-9284-b827eb9e62be<commit_after>313df790-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f3079cfc-2e4c-11e5-9284-b827eb9e62be<commit_msg>f30cad6e-2e4c-11e5-9284-b827eb9e62be<commit_after>f30cad6e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a9495306-2e4e-11e5-9284-b827eb9e62be<commit_msg>a94e5248-2e4e-11e5-9284-b827eb9e62be<commit_after>a94e5248-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8109d3f2-2e4e-11e5-9284-b827eb9e62be<commit_msg>810edadc-2e4e-11e5-9284-b827eb9e62be<commit_after>810edadc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>64917014-2e4d-11e5-9284-b827eb9e62be<commit_msg>64967bcc-2e4d-11e5-9284-b827eb9e62be<commit_after>64967bcc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ede6e8e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>edebe0a0-2e4e-11e5-9284-b827eb9e62be<commit_after>edebe0a0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0062fa5c-2e4f-11e5-9284-b827eb9e62be<commit_msg>0067fb24-2e4f-11e5-9284-b827eb9e62be<commit_after>0067fb24-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>72522284-2e4d-11e5-9284-b827eb9e62be<commit_msg>725710dc-2e4d-11e5-9284-b827eb9e62be<commit_after>725710dc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4d93653e-2e4d-11e5-9284-b827eb9e62be<commit_msg>4d987434-2e4d-11e5-9284-b827eb9e62be<commit_after>4d987434-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>28adc546-2e4f-11e5-9284-b827eb9e62be<commit_msg>28b2c38e-2e4f-11e5-9284-b827eb9e62be<commit_after>28b2c38e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>64f7890c-2e4e-11e5-9284-b827eb9e62be<commit_msg>64fc949c-2e4e-11e5-9284-b827eb9e62be<commit_after>64fc949c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3ecadd60-2e4e-11e5-9284-b827eb9e62be<commit_msg>3ecfecce-2e4e-11e5-9284-b827eb9e62be<commit_after>3ecfecce-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ecab1c26-2e4c-11e5-9284-b827eb9e62be<commit_msg>ecb01244-2e4c-11e5-9284-b827eb9e62be<commit_after>ecb01244-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3231b88-2e4c-11e5-9284-b827eb9e62be<commit_msg>c3280b48-2e4c-11e5-9284-b827eb9e62be<commit_after>c3280b48-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f6a52b4e-2e4d-11e5-9284-b827eb9e62be<commit_msg>f6aa1f32-2e4d-11e5-9284-b827eb9e62be<commit_after>f6aa1f32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d815266c-2e4c-11e5-9284-b827eb9e62be<commit_msg>d81a3044-2e4c-11e5-9284-b827eb9e62be<commit_after>d81a3044-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5f93299e-2e4e-11e5-9284-b827eb9e62be<commit_msg>5f984578-2e4e-11e5-9284-b827eb9e62be<commit_after>5f984578-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>101e9e3e-2e4e-11e5-9284-b827eb9e62be<commit_msg>10239ef2-2e4e-11e5-9284-b827eb9e62be<commit_after>10239ef2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7e80c898-2e4e-11e5-9284-b827eb9e62be<commit_msg>7e85ccbc-2e4e-11e5-9284-b827eb9e62be<commit_after>7e85ccbc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>43eab5b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>43efbf86-2e4e-11e5-9284-b827eb9e62be<commit_after>43efbf86-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>36f04828-2e4e-11e5-9284-b827eb9e62be<commit_msg>36f540e4-2e4e-11e5-9284-b827eb9e62be<commit_after>36f540e4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>abfafc12-2e4e-11e5-9284-b827eb9e62be<commit_msg>ac00460e-2e4e-11e5-9284-b827eb9e62be<commit_after>ac00460e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2d093f22-2e4e-11e5-9284-b827eb9e62be<commit_msg>2d0e8748-2e4e-11e5-9284-b827eb9e62be<commit_after>2d0e8748-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6fb7be70-2e4e-11e5-9284-b827eb9e62be<commit_msg>6fbccbf4-2e4e-11e5-9284-b827eb9e62be<commit_after>6fbccbf4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>// g++ j.cc -o j -L/usr/local/lib -lroaring #include <vector> #include <string> #include <array> #include <map> #include "roaring.hh" enum FieldType { TIMESTAMP, DIMENSION, BOOL, METRIC_INT, METRIC_FLOAT }; class FieldBase {}; template <FieldType, typename T> class Field : FieldBase { private: std::string name; std::vector<T> vals; std::vector< std::vector<T> > mvals; std::map<T, Roaring *> dict_; Roaring *roar_; int count_; FieldType type_; public: Field(std::string name); void insert(T &val); std::map<std::string, Roaring *> &dict(); Roaring *roar() { return roar_; } }; template <FieldType type, typename T> Field<type, T>::Field(std::string name): type_(type), name(name) { switch (type) { case METRIC_INT: case METRIC_FLOAT: { } break; default: throw std::runtime_error("invalid field type for Field<>"); } } template <> Field<DIMENSION, std::string>::Field(std::string name): type_(DIMENSION), name(name) { // switch (type) { // case DIMENSION: { // } break; // default: // throw std::runtime_error("invalid field type for string"); // } } template <> Field<TIMESTAMP, int64_t>::Field(std::string name): type_(TIMESTAMP), name(name) { // switch (type) { // case TIMESTAMP: { // } break; // default: // throw std::runtime_error("invalid field type for int64"); // } } template <> Field<BOOL, bool>::Field(std::string name): type_(BOOL), name(name) { roar_ = new Roaring(); // switch (type) { // case BOOL: { // roar_ = new Roaring(); // } break; // default: // throw std::runtime_error("invalid field type for bool"); // } } template <FieldType type, typename T> void Field<type, T>::insert(T &val) { switch (type_) { case TIMESTAMP: case METRIC_INT: case METRIC_FLOAT: { vals.push_back(val); } break; case DIMENSION: { Roaring *roar; if (dict_.count(val) > 0) { roar = dict_[val]; } else { roar = new Roaring(); dict_[val] = roar; } roar->add(count_); } break; default: throw std::runtime_error("can not insert val to field with unknown type"); } count_++; } template<> std::map<std::string, Roaring *> &Field<DIMENSION, std::string>::dict() { return dict_; } class DimensionField { public: Field<DIMENSION, std::string> *strdim; Field<BOOL, bool> *booldim; bool isBoolDim; DimensionField(Field<DIMENSION, std::string> *strdim_): strdim(strdim_), isBoolDim(false) {} DimensionField(Field<BOOL, bool> *booldim_): booldim(booldim_), isBoolDim(true) {} }; class Query { private: public: Query(); ~Query(); }; struct GroupByResult { std::vector<std::string> key; Roaring roaring; }; static void genGroups(std::vector<GroupByResult> &groups, std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields, std::vector<std::string> currKey, int index) { bool genGroup = index == (groupByKeys.size() - 1); std::string key = groupByKeys[index]; FieldBase *fieldRef = fields[key]; Field<DIMENSION, std::string> *field = (Field<DIMENSION, std::string> *)fieldRef; std::map<std::string, Roaring *> &dict = field->dict(); for (std::map<std::string, Roaring *>::iterator it = dict.begin(); it != dict.end(); it++) { std::vector<std::string> groupKey = currKey; groupKey.push_back(it->first); if (genGroup) { GroupByResult gres; gres.key = groupKey; groups.push_back(gres); } else { genGroups(groups, groupByKeys, fields, groupKey, index + 1); } } } std::vector<GroupByResult> genGroupByResult(std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields) { std::vector<GroupByResult> groups; genGroups(groups, groupByKeys, fields, std::vector<std::string>(), 0); return groups; } int main(int argc, char *argv[]) { Field<TIMESTAMP, int64_t> *timestamp = new Field<TIMESTAMP, int64_t>("timestamp"); Field<DIMENSION, std::string> *publisher = new Field<DIMENSION, std::string>("publisher"); Field<DIMENSION, std::string> *advertiser = new Field<DIMENSION, std::string>("advertiser"); Field<DIMENSION, std::string> *gender = new Field<DIMENSION, std::string>("gender"); Field<DIMENSION, std::string> *country = new Field<DIMENSION, std::string>("country"); Field<BOOL, bool> *click = new Field<BOOL, bool>("click"); Field<METRIC_FLOAT, float> *price = new Field<METRIC_FLOAT, float>("price"); std::map<std::string, FieldBase*> fields; fields["timestamp"] = (FieldBase*)timestamp; fields["publisher"] = (FieldBase*)publisher; fields["advertiser"] = (FieldBase*)advertiser; fields["gender"] = (FieldBase*)gender; fields["country"] = (FieldBase*)country; fields["click"] = (FieldBase*)click; fields["price"] = (FieldBase*)price; // select count(*) from logs where click = 1 group by country,gender { // generate new bitmap of all elements. so we need segment wide count variable int count = 3; Roaring roar(roaring_bitmap_from_range(0, count, 1)); ////////////////////////////////////////////////////////////////////// /////////// FILTERING STATE ////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // do bitwise AND with click = 1 // roar.printf(); roar &= click->roar(); // roar.printf(); ////////////////////////////////////////////////////////////////////// /////////// GROUPING STATE /////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // generate groups for every group by term std::vector< GroupByResult > groups; std::vector<std::string> groupByKeys; groupByKeys.push_back("advertiser"); groupByKeys.push_back("gender"); groupByKeys.push_back("country"); } return 0; } <commit_msg>log group by keys<commit_after>// g++ j.cc -o j -L/usr/local/lib -lroaring #include <iostream> #include <vector> #include <string> #include <array> #include <map> #include "roaring.hh" enum FieldType { TIMESTAMP, DIMENSION, BOOL, METRIC_INT, METRIC_FLOAT }; class FieldBase {}; template <FieldType, typename T> class Field : FieldBase { private: std::string name; std::vector<T> vals; std::vector< std::vector<T> > mvals; std::map<T, Roaring *> dict_; Roaring *roar_; int count_; FieldType type_; public: Field(std::string name); void insert(T &val); std::map<std::string, Roaring *> &dict(); Roaring *roar() { return roar_; } }; template <FieldType type, typename T> Field<type, T>::Field(std::string name): type_(type), name(name) { switch (type) { case METRIC_INT: case METRIC_FLOAT: { } break; default: throw std::runtime_error("invalid field type for Field<>"); } } template <> Field<DIMENSION, std::string>::Field(std::string name): type_(DIMENSION), name(name) { // switch (type) { // case DIMENSION: { // } break; // default: // throw std::runtime_error("invalid field type for string"); // } } template <> Field<TIMESTAMP, int64_t>::Field(std::string name): type_(TIMESTAMP), name(name) { // switch (type) { // case TIMESTAMP: { // } break; // default: // throw std::runtime_error("invalid field type for int64"); // } } template <> Field<BOOL, bool>::Field(std::string name): type_(BOOL), name(name) { roar_ = new Roaring(); // switch (type) { // case BOOL: { // roar_ = new Roaring(); // } break; // default: // throw std::runtime_error("invalid field type for bool"); // } } template <FieldType type, typename T> void Field<type, T>::insert(T &val) { switch (type_) { case TIMESTAMP: case METRIC_INT: case METRIC_FLOAT: { vals.push_back(val); } break; case DIMENSION: { Roaring *roar; if (dict_.count(val) > 0) { roar = dict_[val]; } else { roar = new Roaring(); dict_[val] = roar; } roar->add(count_); } break; default: throw std::runtime_error("can not insert val to field with unknown type"); } count_++; } template<> std::map<std::string, Roaring *> &Field<DIMENSION, std::string>::dict() { return dict_; } class DimensionField { public: Field<DIMENSION, std::string> *strdim; Field<BOOL, bool> *booldim; bool isBoolDim; DimensionField(Field<DIMENSION, std::string> *strdim_): strdim(strdim_), isBoolDim(false) {} DimensionField(Field<BOOL, bool> *booldim_): booldim(booldim_), isBoolDim(true) {} }; class Query { private: public: Query(); ~Query(); }; struct GroupByResult { std::vector<std::string> key; Roaring roaring; }; static void genGroups(std::vector<GroupByResult> &groups, std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields, std::vector<std::string> currKey, int index) { bool genGroup = index == (groupByKeys.size() - 1); std::string key = groupByKeys[index]; FieldBase *fieldRef = fields[key]; Field<DIMENSION, std::string> *field = (Field<DIMENSION, std::string> *)fieldRef; std::map<std::string, Roaring *> &dict = field->dict(); for (std::map<std::string, Roaring *>::iterator it = dict.begin(); it != dict.end(); it++) { std::vector<std::string> groupKey = currKey; groupKey.push_back(it->first); if (genGroup) { GroupByResult gres; gres.key = groupKey; groups.push_back(gres); } else { genGroups(groups, groupByKeys, fields, groupKey, index + 1); } } } std::vector<GroupByResult> genGroupByResult(std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields) { std::vector<GroupByResult> groups; genGroups(groups, groupByKeys, fields, std::vector<std::string>(), 0); return groups; } int main(int argc, char *argv[]) { Field<TIMESTAMP, int64_t> *timestamp = new Field<TIMESTAMP, int64_t>("timestamp"); Field<DIMENSION, std::string> *publisher = new Field<DIMENSION, std::string>("publisher"); Field<DIMENSION, std::string> *advertiser = new Field<DIMENSION, std::string>("advertiser"); Field<DIMENSION, std::string> *gender = new Field<DIMENSION, std::string>("gender"); Field<DIMENSION, std::string> *country = new Field<DIMENSION, std::string>("country"); Field<BOOL, bool> *click = new Field<BOOL, bool>("click"); Field<METRIC_FLOAT, float> *price = new Field<METRIC_FLOAT, float>("price"); std::map<std::string, FieldBase*> fields; fields["timestamp"] = (FieldBase*)timestamp; fields["publisher"] = (FieldBase*)publisher; fields["advertiser"] = (FieldBase*)advertiser; fields["gender"] = (FieldBase*)gender; fields["country"] = (FieldBase*)country; fields["click"] = (FieldBase*)click; fields["price"] = (FieldBase*)price; // select count(*) from logs where click = 1 group by country,gender { // generate new bitmap of all elements. so we need segment wide count variable int count = 3; Roaring roar(roaring_bitmap_from_range(0, count, 1)); ////////////////////////////////////////////////////////////////////// /////////// FILTERING STATE ////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // do bitwise AND with click = 1 // roar.printf(); roar &= click->roar(); // roar.printf(); ////////////////////////////////////////////////////////////////////// /////////// GROUPING STATE /////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // generate groups for every group by term std::vector< GroupByResult > groups; std::vector<std::string> groupByKeys; groupByKeys.push_back("advertiser"); groupByKeys.push_back("gender"); groupByKeys.push_back("country"); groups = genGroupByResult(groupByKeys, fields); for (std::vector< GroupByResult >::iterator it = groups.begin(); it != groups.end(); it++) { const GroupByResult &gres = *it; std::vector<std::string> key = gres.key; for (std::vector<std::string>::iterator it2 = key.begin(); it2 != key.end(); it2++) { std::cout << *it2; if (it2 != key.end()) { std::cout << ", "; } } std::cout << std::endl; } } return 0; } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { int numEntries = 0; cin >> numEntries; cin.ignore(); while (numEntries--) { } return 0; } <commit_msg>Shit be broke, yo<commit_after>#include <iostream> #include <list> using namespace std; struct word { int x; int y; int length; string word; list<word*> conflicts; }; int main() { int numEntries = 0; cin >> numEntries; cin.ignore(); while (numEntries--) { int H, V; cin >> H >> V; map<int, word> horizontal; map<int, word> vertical; for (int i = 0; i < H; i++) { int x, y; cin >> x >> y; horizontal[y].x = x; horizontal[y].y = y; cin >> horizontal[y].word; horizontal[y].length = horizontal[y].word.size(); } for (int i = 0; i < V; i++) { int x, y; cin >> x >> y; vertical[x].x = x; vertical[x].y = y; cin >> vertical[x].word; vertical[x].length = vertical[x].word.size(); for (int y = y; y < vertical[x].y + vertical[x].length; y++) { if (horizontal.count(y)) { } } } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlTable.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-08-03 09:58:22 $ * * 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 * ************************************************************************/ #include "precompiled_reportdesign.hxx" #ifndef RPT_XMLTABLE_HXX #include "xmlTable.hxx" #endif #ifndef RPT_XMLFILTER_HXX #include "xmlfilter.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _REPORT_RPTUIDEF_HXX #include "RptDef.hxx" #endif #ifndef RPT_XMLHELPER_HXX #include "xmlHelper.hxx" #endif #ifndef RPT_XMLENUMS_HXX #include "xmlEnums.hxx" #endif #ifndef RPT_XMLCOLUMN_HXX #include "xmlColumn.hxx" #endif #ifndef _COM_SUN_STAR_REPORT_FORCENEWPAGE_HPP_ #include <com/sun/star/report/ForceNewPage.hpp> #endif #ifndef RPT_XMLCONDPRTEXPR_HXX #include "xmlCondPrtExpr.hxx" #endif #ifndef RPT_XMLSTYLEIMPORT_HXX #include "xmlStyleImport.hxx" #endif #include "xmlstrings.hrc" #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC #include "xmlstrings.hrc" #endif #include <com/sun/star/report/XShape.hpp> #include <com/sun/star/report/XFixedLine.hpp> namespace rptxml { using namespace ::rtl; using namespace ::xmloff; using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using namespace ::com::sun::star::xml::sax; using ::com::sun::star::xml::sax::XAttributeList; sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue) { sal_uInt16 nRet = report::ForceNewPage::NONE; const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions(); SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap ); return nRet; } DBG_NAME( rpt_OXMLTable ) OXMLTable::OXMLTable( ORptFilter& rImport ,sal_uInt16 nPrfx ,const OUString& _sLocalName ,const Reference< XAttributeList > & _xAttrList ,const uno::Reference< report::XSection >& _xSection ) :SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xSection(_xSection) ,m_nColSpan(1) ,m_nRowSpan(0) ,m_nRowIndex(0) ,m_nColumnIndex(0) { DBG_CTOR( rpt_OXMLTable,NULL); OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!"); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap(); const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0; static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE); try { for(sal_Int16 i = 0; i < nLength; ++i) { rtl::OUString sLocalName; const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_VISIBLE: m_xSection->setVisible(sValue == s_sTRUE); break; case XML_TOK_FORCE_NEW_PAGE: m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue)); break; case XML_TOK_FORCE_NEW_COLUMN: m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue)); break; case XML_TOK_KEEP_TOGETHER: m_xSection->setKeepTogether(sValue == s_sTRUE); break; case XML_TOK_SECTION_NAME: m_xSection->setName(sValue); break; case XML_TOK_SECT_STYLE_NAME: m_sStyleName = sValue; break; default: break; } } } catch(Exception&) { OSL_ENSURE(0,"Exception catched while filling the section props"); } } // ----------------------------------------------------------------------------- OXMLTable::~OXMLTable() { DBG_DTOR( rpt_OXMLTable,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLTable::CreateChildContext( sal_uInt16 _nPrefix, const OUString& _rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; ORptFilter& rImport = GetOwnImport(); const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap(); Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory(); switch( rTokenMap.Get( _nPrefix, _rLocalName ) ) { case XML_TOK_TABLE_COLUMNS: case XML_TOK_TABLE_ROWS: pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this); break; case XML_TOK_ROW: incrementRowIndex(); rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this); break; case XML_TOK_COLUMN: rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this); break; default: break; } if( !pContext ) pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName ); return pContext; } // ----------------------------------------------------------------------------- ORptFilter& OXMLTable::GetOwnImport() { return static_cast<ORptFilter&>(GetImport()); } // ----------------------------------------------------------------------------- void OXMLTable::EndElement() { try { if ( m_xSection.is() ) { if ( m_sStyleName.getLength() ) { const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles(); if ( pAutoStyles ) { XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName)); if ( pAutoStyle ) { pAutoStyle->FillPropertySet(m_xSection.get()); } } } // if ( m_sStyleName.getLength() ) // set height ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin(); ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end(); sal_Int32 nHeight = 0; for (; aIter != aEnd; ++aIter) nHeight += *aIter; m_xSection->setHeight( nHeight ); // set positions, widths, and heights sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN); sal_Int32 nPosY = 0; ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin(); ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end(); for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i) { sal_Int32 nPosX = nLeftMargin; ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin(); ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end(); for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j) { TCell& rCell = *aColIter; if ( !rCell.xElements.empty()) { ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin(); const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end(); for (;aCellIter != aCellEnd ; ++aCellIter) { uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY); if ( xShape.is() ) { xShape->setPositionX(xShape->getPositionX() + nLeftMargin); } else { sal_Int32 nWidth = rCell.nWidth; sal_Int32 nColSpan = rCell.nColSpan; if ( nColSpan > 1 ) { ::std::vector<TCell>::iterator aWidthIter = aColIter + 1; while ( nColSpan > 1 ) { nWidth += (aWidthIter++)->nWidth; --nColSpan; } } nHeight = rCell.nHeight; sal_Int32 nRowSpan = rCell.nRowSpan; if ( nRowSpan > 1 ) { ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1; while( nRowSpan > 1) { nHeight += (*aHeightIter)[j].nHeight; ++aHeightIter; --nRowSpan; } } Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY); if ( xFixedLine.is() && xFixedLine->getOrientation() == 1 ) // vertical { OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part."); nWidth += m_aWidth[j+1]; } try { (*aCellIter)->setSize(awt::Size(nWidth,nHeight)); (*aCellIter)->setPosition(awt::Point(nPosX,nPosY)); } catch(beans::PropertyVetoException) { OSL_ENSURE(0,"Could set the correct positions!"); } } } } nPosX += m_aWidth[j]; } nPosY += m_aHeight[i]; } } // if ( m_xComponent.is() ) } catch(Exception&) { OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched"); } } // ----------------------------------------------------------------------------- void OXMLTable::addCell(const Reference<XReportComponent>& _xElement) { uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY); OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(), "OXMLTable::addCell: Invalid column and row index"); if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() ) { TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1]; if ( _xElement.is() ) rCell.xElements.push_back( _xElement ); if ( !xShape.is() ) { rCell.nWidth = m_aWidth[m_nColumnIndex-1]; rCell.nHeight = m_aHeight[m_nRowIndex-1]; rCell.nColSpan = m_nColSpan; rCell.nRowSpan = m_nRowSpan; } } if ( !xShape.is() ) m_nColSpan = m_nRowSpan = 1; } // ----------------------------------------------------------------------------- void OXMLTable::incrementRowIndex() { ++m_nRowIndex; m_nColumnIndex = 0; m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size())); } //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba24a (1.2.10); FILE MERGED 2007/08/13 05:36:13 oj 1.2.10.2: RESYNC: (1.2-1.3); FILE MERGED 2007/08/08 11:24:56 oj 1.2.10.1: #i80308# remove using rtl<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlTable.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-09-26 14:24:40 $ * * 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 * ************************************************************************/ #include "precompiled_reportdesign.hxx" #ifndef RPT_XMLTABLE_HXX #include "xmlTable.hxx" #endif #ifndef RPT_XMLFILTER_HXX #include "xmlfilter.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _REPORT_RPTUIDEF_HXX #include "RptDef.hxx" #endif #ifndef RPT_XMLHELPER_HXX #include "xmlHelper.hxx" #endif #ifndef RPT_XMLENUMS_HXX #include "xmlEnums.hxx" #endif #ifndef RPT_XMLCOLUMN_HXX #include "xmlColumn.hxx" #endif #ifndef _COM_SUN_STAR_REPORT_FORCENEWPAGE_HPP_ #include <com/sun/star/report/ForceNewPage.hpp> #endif #ifndef RPT_XMLCONDPRTEXPR_HXX #include "xmlCondPrtExpr.hxx" #endif #ifndef RPT_XMLSTYLEIMPORT_HXX #include "xmlStyleImport.hxx" #endif #include "xmlstrings.hrc" #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC #include "xmlstrings.hrc" #endif #include <com/sun/star/report/XShape.hpp> #include <com/sun/star/report/XFixedLine.hpp> namespace rptxml { using namespace ::xmloff; using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using namespace ::com::sun::star::xml::sax; using ::com::sun::star::xml::sax::XAttributeList; sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue) { sal_uInt16 nRet = report::ForceNewPage::NONE; const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions(); SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap ); return nRet; } DBG_NAME( rpt_OXMLTable ) OXMLTable::OXMLTable( ORptFilter& rImport ,sal_uInt16 nPrfx ,const ::rtl::OUString& _sLocalName ,const Reference< XAttributeList > & _xAttrList ,const uno::Reference< report::XSection >& _xSection ) :SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xSection(_xSection) ,m_nColSpan(1) ,m_nRowSpan(0) ,m_nRowIndex(0) ,m_nColumnIndex(0) { DBG_CTOR( rpt_OXMLTable,NULL); OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!"); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap(); const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0; static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE); try { for(sal_Int16 i = 0; i < nLength; ++i) { rtl::OUString sLocalName; const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_VISIBLE: m_xSection->setVisible(sValue == s_sTRUE); break; case XML_TOK_FORCE_NEW_PAGE: m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue)); break; case XML_TOK_FORCE_NEW_COLUMN: m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue)); break; case XML_TOK_KEEP_TOGETHER: m_xSection->setKeepTogether(sValue == s_sTRUE); break; case XML_TOK_SECTION_NAME: m_xSection->setName(sValue); break; case XML_TOK_SECT_STYLE_NAME: m_sStyleName = sValue; break; default: break; } } } catch(Exception&) { OSL_ENSURE(0,"Exception catched while filling the section props"); } } // ----------------------------------------------------------------------------- OXMLTable::~OXMLTable() { DBG_DTOR( rpt_OXMLTable,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLTable::CreateChildContext( sal_uInt16 _nPrefix, const ::rtl::OUString& _rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; ORptFilter& rImport = GetOwnImport(); const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap(); Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory(); switch( rTokenMap.Get( _nPrefix, _rLocalName ) ) { case XML_TOK_TABLE_COLUMNS: case XML_TOK_TABLE_ROWS: pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this); break; case XML_TOK_ROW: incrementRowIndex(); rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this); break; case XML_TOK_COLUMN: rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this); break; default: break; } if( !pContext ) pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName ); return pContext; } // ----------------------------------------------------------------------------- ORptFilter& OXMLTable::GetOwnImport() { return static_cast<ORptFilter&>(GetImport()); } // ----------------------------------------------------------------------------- void OXMLTable::EndElement() { try { if ( m_xSection.is() ) { if ( m_sStyleName.getLength() ) { const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles(); if ( pAutoStyles ) { XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName)); if ( pAutoStyle ) { pAutoStyle->FillPropertySet(m_xSection.get()); } } } // if ( m_sStyleName.getLength() ) // set height ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin(); ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end(); sal_Int32 nHeight = 0; for (; aIter != aEnd; ++aIter) nHeight += *aIter; m_xSection->setHeight( nHeight ); // set positions, widths, and heights sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN); sal_Int32 nPosY = 0; ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin(); ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end(); for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i) { sal_Int32 nPosX = nLeftMargin; ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin(); ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end(); for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j) { TCell& rCell = *aColIter; if ( !rCell.xElements.empty()) { ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin(); const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end(); for (;aCellIter != aCellEnd ; ++aCellIter) { uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY); if ( xShape.is() ) { xShape->setPositionX(xShape->getPositionX() + nLeftMargin); } else { sal_Int32 nWidth = rCell.nWidth; sal_Int32 nColSpan = rCell.nColSpan; if ( nColSpan > 1 ) { ::std::vector<TCell>::iterator aWidthIter = aColIter + 1; while ( nColSpan > 1 ) { nWidth += (aWidthIter++)->nWidth; --nColSpan; } } nHeight = rCell.nHeight; sal_Int32 nRowSpan = rCell.nRowSpan; if ( nRowSpan > 1 ) { ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1; while( nRowSpan > 1) { nHeight += (*aHeightIter)[j].nHeight; ++aHeightIter; --nRowSpan; } } Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY); if ( xFixedLine.is() && xFixedLine->getOrientation() == 1 ) // vertical { OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part."); nWidth += m_aWidth[j+1]; } try { (*aCellIter)->setSize(awt::Size(nWidth,nHeight)); (*aCellIter)->setPosition(awt::Point(nPosX,nPosY)); } catch(beans::PropertyVetoException) { OSL_ENSURE(0,"Could set the correct positions!"); } } } } nPosX += m_aWidth[j]; } nPosY += m_aHeight[i]; } } // if ( m_xComponent.is() ) } catch(Exception&) { OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched"); } } // ----------------------------------------------------------------------------- void OXMLTable::addCell(const Reference<XReportComponent>& _xElement) { uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY); OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(), "OXMLTable::addCell: Invalid column and row index"); if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() ) { TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1]; if ( _xElement.is() ) rCell.xElements.push_back( _xElement ); if ( !xShape.is() ) { rCell.nWidth = m_aWidth[m_nColumnIndex-1]; rCell.nHeight = m_aHeight[m_nRowIndex-1]; rCell.nColSpan = m_nColSpan; rCell.nRowSpan = m_nRowSpan; } } if ( !xShape.is() ) m_nColSpan = m_nRowSpan = 1; } // ----------------------------------------------------------------------------- void OXMLTable::incrementRowIndex() { ++m_nRowIndex; m_nColumnIndex = 0; m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size())); } //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- <|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. ===================================================================*/ #include "QmitkTransferFunctionGeneratorWidget.h" #include <mitkTransferFunctionProperty.h> #include <mitkRenderingManager.h> #include <mitkTransferFunctionInitializer.h> #include <mitkUnstructuredGrid.h> #include <QFileDialog> #include <MitkSceneSerializationExports.h> #include <mitkTransferFunctionPropertySerializer.h> #include <vtkUnstructuredGrid.h> QmitkTransferFunctionGeneratorWidget::QmitkTransferFunctionGeneratorWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), deltaScale(1.0), deltaMax(1024), deltaMin(1) { histoGramm = NULL; this->setupUi(this); // LevelWindow Tab { connect( m_CrossLevelWindow, SIGNAL( SignalDeltaMove( int, int ) ), this, SLOT( OnDeltaLevelWindow( int, int ) ) ); } // Threshold Tab { connect( m_CrossThreshold, SIGNAL( SignalDeltaMove( int, int ) ), this, SLOT( OnDeltaThreshold( int, int ) ) ); thDelta = 100; } // Presets Tab { m_TransferFunctionComboBox->setVisible(false); connect( m_TransferFunctionComboBox, SIGNAL( activated( int ) ), this, SIGNAL(SignalTransferFunctionModeChanged(int)) ); connect( m_TransferFunctionComboBox, SIGNAL( activated( int ) ), this, SLOT(OnPreset(int)) ); connect( m_SavePreset, SIGNAL( clicked() ), this, SLOT( OnSavePreset() ) ); connect( m_LoadPreset, SIGNAL( clicked() ), this, SLOT( OnLoadPreset() ) ); } presetFileName = "."; } int QmitkTransferFunctionGeneratorWidget::AddPreset(const QString &presetName) { m_TransferFunctionComboBox->setVisible(true); m_TransferFunctionComboBox->addItem( presetName); return m_TransferFunctionComboBox->count()-1; } void QmitkTransferFunctionGeneratorWidget::SetPresetsTabEnabled(bool enable) { m_PresetTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::SetThresholdTabEnabled(bool enable) { m_ThresholdTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::SetBellTabEnabled(bool enable) { m_BellTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::OnSavePreset( ) { if(tfpToChange.IsNull()) return; mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); std::string fileName; std::string fileNameOutput; presetFileName = QFileDialog::getSaveFileName( this,"Choose a filename to save the transferfunction",presetFileName, "Transferfunction (*.xml)" ); fileName=presetFileName.toLocal8Bit().constData(); MITK_INFO << "Saving Transferfunction under path: " << fileName; fileNameOutput= ReduceFileName(fileName); if ( mitk::TransferFunctionPropertySerializer::SerializeTransferFunction( fileName.c_str(), tf )) m_InfoPreset->setText( QString( (std::string("saved ")+ fileNameOutput).c_str() ) ); else m_InfoPreset->setText( QString( std::string("saving failed").c_str() ) ); } void QmitkTransferFunctionGeneratorWidget::OnLoadPreset( ) { if(tfpToChange.IsNull()) return; std::string fileName; std::string fileNameOutput; presetFileName = QFileDialog::getOpenFileName( this,"Choose a file to open the transferfunction from",presetFileName, "Transferfunction (*.xml)" ); fileName=presetFileName.toLocal8Bit().constData(); MITK_INFO << "Loading Transferfunction from path: " << fileName; fileNameOutput= ReduceFileName(fileName); mitk::TransferFunction::Pointer tf = mitk::TransferFunctionPropertySerializer::DeserializeTransferFunction(fileName.c_str()); if(tf.IsNotNull()) { tfpToChange->SetValue( tf ); m_InfoPreset->setText( QString( (std::string("loaded ")+ fileNameOutput).c_str() ) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } } void QmitkTransferFunctionGeneratorWidget::OnPreset(int mode) { //first item is only information if( --mode == -1 ) return; m_InfoPreset->setText(QString("selected ") + m_TransferFunctionComboBox->currentText()); //revert to first item m_TransferFunctionComboBox->setCurrentIndex( 0 ); } static double transformationGlocke ( double x ) { double z = 0.1; double a = 2 - 2 * z; double b = 2 * z - 1; x = a * x + b; return x; } static double stepFunctionGlocke ( double x ) { x = 1-(2*x -1.0); // map [0.5;1] to [0,1] x = x * ( 3*x - 2*x*x ); // apply smoothing function x = x * x; return x; } double QmitkTransferFunctionGeneratorWidget::ScaleDelta(int d) const { return deltaScale*(double)d; } void QmitkTransferFunctionGeneratorWidget::OnDeltaLevelWindow(int dx, int dy) // bell { if(tfpToChange.IsNull()) return; thPos += ScaleDelta(dx); thDelta -= ScaleDelta(dy); if(thDelta < deltaMin) thDelta = deltaMin; if(thDelta > deltaMax) thDelta = deltaMax; if(thPos < histoMinimum) thPos = histoMinimum; if(thPos > histoMaximum) thPos = histoMaximum; std::stringstream ss; ss << "Click on the cross and move the mouse"<<"\n" <<"\n" << "center at " << thPos << "\n" << "width " << thDelta * 2; m_InfoLevelWindow->setText( QString( ss.str().c_str() ) ); mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemoveAllPoints(); for( int r = 0; r<= 6; r++) { double relPos = (r / 6.0) * 0.5 + 0.5; f->AddPoint(thPos+thDelta*(-transformationGlocke(relPos)),stepFunctionGlocke(relPos)); f->AddPoint(thPos+thDelta*( transformationGlocke(relPos)),stepFunctionGlocke(relPos)); } f->Modified(); } // gradient at grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetGradientOpacityFunction(); f->RemoveAllPoints(); f->AddPoint( 0, 1.0 ); f->Modified(); } tf->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } static double stepFunctionThreshold ( double x ) { x = 0.5*x + 0.5; // map [-1;1] to [0,1] x = x * ( 3*x - 2*x*x ); // apply smoothing function x = x * x; return x; } void QmitkTransferFunctionGeneratorWidget::OnDeltaThreshold(int dx, int dy) // LEVELWINDOW { if(tfpToChange.IsNull()) return; thPos += ScaleDelta(dx); thDelta += ScaleDelta(dy); if(thDelta < deltaMin) thDelta = deltaMin; if(thDelta > deltaMax) thDelta = deltaMax; if(thPos < histoMinimum) thPos = histoMinimum; if(thPos > histoMaximum) thPos = histoMaximum; std::stringstream ss; ss << "Click on the cross and move the mouse"<<"\n" <<"\n" << "threshold at " << thPos << "\n" << "width " << thDelta * 2; m_InfoThreshold->setText( QString( ss.str().c_str() ) ); mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemoveAllPoints(); for( int r = 1; r<= 4; r++) { double relPos = r / 4.0; f->AddPoint(thPos+thDelta*(-relPos),stepFunctionThreshold(-relPos)); f->AddPoint(thPos+thDelta*( relPos),stepFunctionThreshold( relPos)); } f->Modified(); } // gradient at grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetGradientOpacityFunction(); f->RemoveAllPoints(); f->AddPoint( 0, 1.0 ); f->Modified(); } tf->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } std::string QmitkTransferFunctionGeneratorWidget::ReduceFileName(std::string fileNameLong ) { if (fileNameLong.length()< 40) return fileNameLong; std::string fileNameShort; std::string fileNameRevert; for(unsigned int i=0; i< fileNameLong.length(); i++) { if(i<3) { char x= fileNameLong[i]; fileNameShort= fileNameShort+x; } if(i==3) { fileNameShort= fileNameShort+"..."; break; } } unsigned int len( fileNameLong.length() ); for(unsigned int i=len-1; i <= len; i--) { std::string x=std::string("")+fileNameLong[i]; if ( x.compare("/")==0 || x.compare("\\")==0) { fileNameRevert= "/" + fileNameRevert; break; } if (i>=fileNameLong.length()-24) { fileNameRevert= x+ fileNameRevert; } else { fileNameRevert= "/..." + fileNameRevert; break; } } return fileNameShort+fileNameRevert; } QmitkTransferFunctionGeneratorWidget::~QmitkTransferFunctionGeneratorWidget() { } void QmitkTransferFunctionGeneratorWidget::SetDataNode(mitk::DataNode* node) { histoGramm = NULL; if (node) { tfpToChange = dynamic_cast<mitk::TransferFunctionProperty*>(node->GetProperty("TransferFunction")); if(!tfpToChange) { node->SetProperty("TransferFunction", tfpToChange = mitk::TransferFunctionProperty::New() ); dynamic_cast<mitk::TransferFunctionProperty*>(node->GetProperty("TransferFunction")); } mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); if( mitk::Image* image = dynamic_cast<mitk::Image*>( node->GetData() ) ) { histoMinimum= image->GetScalarValueMin(); histoMaximum= image->GetScalarValueMax(); } else if (mitk::UnstructuredGrid* grid = dynamic_cast<mitk::UnstructuredGrid*>( node->GetData() ) ) { double* range = grid->GetVtkUnstructuredGrid()->GetScalarRange(); histoMinimum = range[0]; histoMaximum = range[1]; double histoRange = histoMaximum - histoMinimum; deltaMax = histoRange/4.0; deltaMin = histoRange/400.0; deltaScale = histoRange/1024.0; } else { MITK_WARN << "QmitkTransferFunctonGeneratorWidget does not support " << node->GetData()->GetNameOfClass() << " instances"; } thPos = ( histoMinimum + histoMaximum ) / 2.0; } else { tfpToChange = 0; m_InfoPreset->setText( QString( "" ) ); } } <commit_msg>COMP: Replaced deprecated functionalities.<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. ===================================================================*/ #include "QmitkTransferFunctionGeneratorWidget.h" #include <mitkImageStatisticsHolder.h> #include <mitkTransferFunctionProperty.h> #include <mitkRenderingManager.h> #include <mitkTransferFunctionInitializer.h> #include <mitkUnstructuredGrid.h> #include <QFileDialog> #include <MitkSceneSerializationExports.h> #include <mitkTransferFunctionPropertySerializer.h> #include <vtkUnstructuredGrid.h> QmitkTransferFunctionGeneratorWidget::QmitkTransferFunctionGeneratorWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), deltaScale(1.0), deltaMax(1024), deltaMin(1) { histoGramm = NULL; this->setupUi(this); // LevelWindow Tab { connect( m_CrossLevelWindow, SIGNAL( SignalDeltaMove( int, int ) ), this, SLOT( OnDeltaLevelWindow( int, int ) ) ); } // Threshold Tab { connect( m_CrossThreshold, SIGNAL( SignalDeltaMove( int, int ) ), this, SLOT( OnDeltaThreshold( int, int ) ) ); thDelta = 100; } // Presets Tab { m_TransferFunctionComboBox->setVisible(false); connect( m_TransferFunctionComboBox, SIGNAL( activated( int ) ), this, SIGNAL(SignalTransferFunctionModeChanged(int)) ); connect( m_TransferFunctionComboBox, SIGNAL( activated( int ) ), this, SLOT(OnPreset(int)) ); connect( m_SavePreset, SIGNAL( clicked() ), this, SLOT( OnSavePreset() ) ); connect( m_LoadPreset, SIGNAL( clicked() ), this, SLOT( OnLoadPreset() ) ); } presetFileName = "."; } int QmitkTransferFunctionGeneratorWidget::AddPreset(const QString &presetName) { m_TransferFunctionComboBox->setVisible(true); m_TransferFunctionComboBox->addItem( presetName); return m_TransferFunctionComboBox->count()-1; } void QmitkTransferFunctionGeneratorWidget::SetPresetsTabEnabled(bool enable) { m_PresetTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::SetThresholdTabEnabled(bool enable) { m_ThresholdTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::SetBellTabEnabled(bool enable) { m_BellTab->setEnabled(enable); } void QmitkTransferFunctionGeneratorWidget::OnSavePreset( ) { if(tfpToChange.IsNull()) return; mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); std::string fileName; std::string fileNameOutput; presetFileName = QFileDialog::getSaveFileName( this,"Choose a filename to save the transferfunction",presetFileName, "Transferfunction (*.xml)" ); fileName=presetFileName.toLocal8Bit().constData(); MITK_INFO << "Saving Transferfunction under path: " << fileName; fileNameOutput= ReduceFileName(fileName); if ( mitk::TransferFunctionPropertySerializer::SerializeTransferFunction( fileName.c_str(), tf )) m_InfoPreset->setText( QString( (std::string("saved ")+ fileNameOutput).c_str() ) ); else m_InfoPreset->setText( QString( std::string("saving failed").c_str() ) ); } void QmitkTransferFunctionGeneratorWidget::OnLoadPreset( ) { if(tfpToChange.IsNull()) return; std::string fileName; std::string fileNameOutput; presetFileName = QFileDialog::getOpenFileName( this,"Choose a file to open the transferfunction from",presetFileName, "Transferfunction (*.xml)" ); fileName=presetFileName.toLocal8Bit().constData(); MITK_INFO << "Loading Transferfunction from path: " << fileName; fileNameOutput= ReduceFileName(fileName); mitk::TransferFunction::Pointer tf = mitk::TransferFunctionPropertySerializer::DeserializeTransferFunction(fileName.c_str()); if(tf.IsNotNull()) { tfpToChange->SetValue( tf ); m_InfoPreset->setText( QString( (std::string("loaded ")+ fileNameOutput).c_str() ) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } } void QmitkTransferFunctionGeneratorWidget::OnPreset(int mode) { //first item is only information if( --mode == -1 ) return; m_InfoPreset->setText(QString("selected ") + m_TransferFunctionComboBox->currentText()); //revert to first item m_TransferFunctionComboBox->setCurrentIndex( 0 ); } static double transformationGlocke ( double x ) { double z = 0.1; double a = 2 - 2 * z; double b = 2 * z - 1; x = a * x + b; return x; } static double stepFunctionGlocke ( double x ) { x = 1-(2*x -1.0); // map [0.5;1] to [0,1] x = x * ( 3*x - 2*x*x ); // apply smoothing function x = x * x; return x; } double QmitkTransferFunctionGeneratorWidget::ScaleDelta(int d) const { return deltaScale*(double)d; } void QmitkTransferFunctionGeneratorWidget::OnDeltaLevelWindow(int dx, int dy) // bell { if(tfpToChange.IsNull()) return; thPos += ScaleDelta(dx); thDelta -= ScaleDelta(dy); if(thDelta < deltaMin) thDelta = deltaMin; if(thDelta > deltaMax) thDelta = deltaMax; if(thPos < histoMinimum) thPos = histoMinimum; if(thPos > histoMaximum) thPos = histoMaximum; std::stringstream ss; ss << "Click on the cross and move the mouse"<<"\n" <<"\n" << "center at " << thPos << "\n" << "width " << thDelta * 2; m_InfoLevelWindow->setText( QString( ss.str().c_str() ) ); mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemoveAllPoints(); for( int r = 0; r<= 6; r++) { double relPos = (r / 6.0) * 0.5 + 0.5; f->AddPoint(thPos+thDelta*(-transformationGlocke(relPos)),stepFunctionGlocke(relPos)); f->AddPoint(thPos+thDelta*( transformationGlocke(relPos)),stepFunctionGlocke(relPos)); } f->Modified(); } // gradient at grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetGradientOpacityFunction(); f->RemoveAllPoints(); f->AddPoint( 0, 1.0 ); f->Modified(); } tf->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } static double stepFunctionThreshold ( double x ) { x = 0.5*x + 0.5; // map [-1;1] to [0,1] x = x * ( 3*x - 2*x*x ); // apply smoothing function x = x * x; return x; } void QmitkTransferFunctionGeneratorWidget::OnDeltaThreshold(int dx, int dy) // LEVELWINDOW { if(tfpToChange.IsNull()) return; thPos += ScaleDelta(dx); thDelta += ScaleDelta(dy); if(thDelta < deltaMin) thDelta = deltaMin; if(thDelta > deltaMax) thDelta = deltaMax; if(thPos < histoMinimum) thPos = histoMinimum; if(thPos > histoMaximum) thPos = histoMaximum; std::stringstream ss; ss << "Click on the cross and move the mouse"<<"\n" <<"\n" << "threshold at " << thPos << "\n" << "width " << thDelta * 2; m_InfoThreshold->setText( QString( ss.str().c_str() ) ); mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); // grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetScalarOpacityFunction(); f->RemoveAllPoints(); for( int r = 1; r<= 4; r++) { double relPos = r / 4.0; f->AddPoint(thPos+thDelta*(-relPos),stepFunctionThreshold(-relPos)); f->AddPoint(thPos+thDelta*( relPos),stepFunctionThreshold( relPos)); } f->Modified(); } // gradient at grayvalue->opacity { vtkPiecewiseFunction *f=tf->GetGradientOpacityFunction(); f->RemoveAllPoints(); f->AddPoint( 0, 1.0 ); f->Modified(); } tf->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); emit SignalUpdateCanvas(); } std::string QmitkTransferFunctionGeneratorWidget::ReduceFileName(std::string fileNameLong ) { if (fileNameLong.length()< 40) return fileNameLong; std::string fileNameShort; std::string fileNameRevert; for(unsigned int i=0; i< fileNameLong.length(); i++) { if(i<3) { char x= fileNameLong[i]; fileNameShort= fileNameShort+x; } if(i==3) { fileNameShort= fileNameShort+"..."; break; } } unsigned int len( fileNameLong.length() ); for(unsigned int i=len-1; i <= len; i--) { std::string x=std::string("")+fileNameLong[i]; if ( x.compare("/")==0 || x.compare("\\")==0) { fileNameRevert= "/" + fileNameRevert; break; } if (i>=fileNameLong.length()-24) { fileNameRevert= x+ fileNameRevert; } else { fileNameRevert= "/..." + fileNameRevert; break; } } return fileNameShort+fileNameRevert; } QmitkTransferFunctionGeneratorWidget::~QmitkTransferFunctionGeneratorWidget() { } void QmitkTransferFunctionGeneratorWidget::SetDataNode(mitk::DataNode* node) { histoGramm = NULL; if (node) { tfpToChange = dynamic_cast<mitk::TransferFunctionProperty*>(node->GetProperty("TransferFunction")); if(!tfpToChange) { node->SetProperty("TransferFunction", tfpToChange = mitk::TransferFunctionProperty::New() ); dynamic_cast<mitk::TransferFunctionProperty*>(node->GetProperty("TransferFunction")); } mitk::TransferFunction::Pointer tf = tfpToChange->GetValue(); if( mitk::Image* image = dynamic_cast<mitk::Image*>( node->GetData() ) ) { mitk::ImageStatisticsHolder* statistics = image->GetStatistics(); histoMinimum= statistics->GetScalarValueMin(); histoMaximum= statistics->GetScalarValueMax(); } else if (mitk::UnstructuredGrid* grid = dynamic_cast<mitk::UnstructuredGrid*>( node->GetData() ) ) { double* range = grid->GetVtkUnstructuredGrid()->GetScalarRange(); histoMinimum = range[0]; histoMaximum = range[1]; double histoRange = histoMaximum - histoMinimum; deltaMax = histoRange/4.0; deltaMin = histoRange/400.0; deltaScale = histoRange/1024.0; } else { MITK_WARN << "QmitkTransferFunctonGeneratorWidget does not support " << node->GetData()->GetNameOfClass() << " instances"; } thPos = ( histoMinimum + histoMaximum ) / 2.0; } else { tfpToChange = 0; m_InfoPreset->setText( QString( "" ) ); } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCLoginNet_ServerModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCLoginNet_ServerModule // @Desc : // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCLoginNet_ServerModule.h" #include "NFLoginNet_ServerPlugin.h" const std::string PROPERTY_ACCOUNT = "Account"; const std::string PROPERTY_VERIFIED = "Verified"; bool NFCLoginNet_ServerModule::Init() { return true; } bool NFCLoginNet_ServerModule::Shut() { return true; } bool NFCLoginNet_ServerModule::BeforeShut() { return true; } bool NFCLoginNet_ServerModule::AfterInit() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pLoginLogicModule = dynamic_cast<NFILoginLogicModule*>(pPluginManager->FindModule("NFCLoginLogicModule")); m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); m_pLoginToMasterModule = dynamic_cast<NFILoginToMasterModule*>(pPluginManager->FindModule("NFCLoginToMasterModule")); m_pUUIDModule = dynamic_cast<NFIUUIDModule*>(pPluginManager->FindModule("NFCUUIDModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pKernelModule); assert(NULL != m_pLoginLogicModule); assert(NULL != m_pLogModule); assert(NULL != m_pLogicClassModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLoginToMasterModule); assert(NULL != m_pUUIDModule); m_pEventProcessModule->AddEventCallBack(NFIDENTID(), NFED_ON_CLIENT_LOGIN_RESULTS, this, &NFCLoginNet_ServerModule::OnLoginResultsEvent); m_pEventProcessModule->AddEventCallBack(NFIDENTID(), NFED_ON_CLIENT_SELECT_SERVER_RESULTS, this, &NFCLoginNet_ServerModule::OnSelectWorldResultsEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_LOGIN && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); m_pUUIDModule->SetIdentID(nServerID); Initialization(NFIMsgHead::NF_Head::NF_HEAD_LENGTH, this, &NFCLoginNet_ServerModule::OnReciveClientPack, &NFCLoginNet_ServerModule::OnSocketClientEvent, nMaxConnect, nPort, nCpus); } } } return true; } int NFCLoginNet_ServerModule::OnLoginResultsEvent(const NFIDENTID& object, const int nEventID, const NFIDataList& var) { if (3 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } const int nState = var.Int(0); const NFIDENTID xIdent = var.Object(1); const std::string& strAccount = var.String(2); NF_SHARE_PTR<int> xFD = mxClientIdent.GetElement(xIdent); if (xFD) { if (0 != nState) { //ʺ߱ //¼ʧ NFMsg::AckEventResult xMsg; xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, *xFD); return 0; } NetObject* pNetObject = GetNet()->GetNetObject(*xFD); if (pNetObject) { //¼¼ pNetObject->SetConnectKeyState(1); pNetObject->SetAccount(strAccount); } //ѷб㲥ȥ NFMsg::AckEventResult xData; xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, *xFD); //SynWorldToClient(unAddress); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, *xFD), "Login successed :", strAccount.c_str()); } return 0; } int NFCLoginNet_ServerModule::OnSelectWorldResultsEvent(const NFIDENTID& object, const int nEventID, const NFIDataList& var) { if (7 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } const int nWorldID = var.Int(0); const NFIDENTID xClientIdent = var.Object(1); const int nLoginID = var.Int(2); const std::string& strAccount = var.String(3); const std::string& strWorldAddress = var.String(4); int nPort = var.Int(5); const std::string& strWorldKey = var.String(6); NF_SHARE_PTR<int> xFD = mxClientIdent.GetElement(xClientIdent); if (xFD) { NFMsg::AckConnectWorldResult xMsg; xMsg.set_world_id(nWorldID); xMsg.mutable_sender()->CopyFrom(NFToPB(xClientIdent)); xMsg.set_login_id(nLoginID); xMsg.set_account(strAccount); xMsg.set_world_ip(strWorldAddress); xMsg.set_world_port(nPort); xMsg.set_world_key(strWorldKey); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_CONNECT_WORLD, xMsg, *xFD); } return 0; } bool NFCLoginNet_ServerModule::Execute(const float fLasFrametime, const float fStartedTime) { return NFINetModule::Execute(fLasFrametime, fStartedTime); } void NFCLoginNet_ServerModule::OnClientConnected(const int nAddress) { NetObject* pObject = GetNet()->GetNetObject(nAddress); if (pObject) { NFIDENTID xIdent =m_pUUIDModule->CreateGUID(); pObject->SetClientID(xIdent); mxClientIdent.AddElement(xIdent, NF_SHARE_PTR<int> (NF_NEW int(nAddress)) ); } } void NFCLoginNet_ServerModule::OnClientDisconnect(const int nAddress) { NetObject* pObject = GetNet()->GetNetObject(nAddress); if (pObject) { NFIDENTID xIdent = pObject->GetClientID(); mxClientIdent.RemoveElement(xIdent); } } int NFCLoginNet_ServerModule::OnLoginProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqAccountLogin xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } NetObject* pNetObject = GetNet()->GetNetObject(msg.GetFd()); if (pNetObject) { //ûе¼ if (pNetObject->GetConnectKeyState() == 0) { NFCDataList val; val << pNetObject->GetClientID()<< xMsg.account() << xMsg.password(); m_pEventProcessModule->DoEvent(NFIDENTID(), NFED_ON_CLIENT_LOGIN, val); } } return 0; } int NFCLoginNet_ServerModule::OnSelectWorldProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqConnectWorld xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } NetObject* pNetObject = GetNet()->GetNetObject(msg.GetFd()); if (!pNetObject) { return 0; } //û¼ if (pNetObject->GetConnectKeyState() <= 0) { return 0; } NFCDataList val; val << xMsg.world_id() << pNetObject->GetClientID() << pPluginManager->AppID() << pNetObject->GetAccount(); m_pEventProcessModule->DoEvent(NFIDENTID(), NFED_ON_CLIENT_SELECT_SERVER, val); return 0; } int NFCLoginNet_ServerModule::OnReciveClientPack(const NFIPacket& msg ) { //ͳһ int nMsgID = msg.GetMsgHead()->GetMsgID(); switch (nMsgID) { case NFMsg::EGameMsgID::EGMI_REQ_LOGIN: OnLoginProcess(msg); break; case NFMsg::EGameMsgID::EGMI_REQ_LOGOUT: break; case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD: OnSelectWorldProcess(msg); break; case NFMsg::EGameMsgID::EGMI_REQ_WORLD_LIST: OnViewWorldProcess(msg); break; // case NFMsg::EGameMsgID::EGMI_ACK_CONNECT_WORLD: // OnObjectPropertyIntProcess(msg); // break; default: printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID); break; } return 0; } int NFCLoginNet_ServerModule::OnSocketClientEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent & NF_NET_EVENT_ERROR) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent & NF_NET_EVENT_TIMEOUT) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); OnClientConnected(nSockIndex); } return 0; } void NFCLoginNet_ServerModule::SynWorldToClient( const int nFD ) { NFMsg::AckServerList xData; xData.set_type(NFMsg::RSLT_WORLD_SERVER); NFMapEx<int, NFMsg::ServerInfoReport>& xWorldMap = m_pLoginToMasterModule->GetWorldMap(); NFMsg::ServerInfoReport* pWorldData = xWorldMap.FirstNude(); while (pWorldData) { NFMsg::ServerInfo* pServerInfo = xData.add_info(); pServerInfo->set_name(pWorldData->server_name()); pServerInfo->set_status(pWorldData->server_state()); pServerInfo->set_server_id(pWorldData->server_id()); pServerInfo->set_wait_count(0); pWorldData = xWorldMap.NextNude(); } SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_WORLD_LIST, xData, nFD); } int NFCLoginNet_ServerModule::OnViewWorldProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqServerList xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } if (xMsg.type() == NFMsg::RSLT_WORLD_SERVER) { SynWorldToClient(msg.GetFd()); } return 0; } <commit_msg>handle heart beat msg<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCLoginNet_ServerModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCLoginNet_ServerModule // @Desc : // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCLoginNet_ServerModule.h" #include "NFLoginNet_ServerPlugin.h" const std::string PROPERTY_ACCOUNT = "Account"; const std::string PROPERTY_VERIFIED = "Verified"; bool NFCLoginNet_ServerModule::Init() { return true; } bool NFCLoginNet_ServerModule::Shut() { return true; } bool NFCLoginNet_ServerModule::BeforeShut() { return true; } bool NFCLoginNet_ServerModule::AfterInit() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pLoginLogicModule = dynamic_cast<NFILoginLogicModule*>(pPluginManager->FindModule("NFCLoginLogicModule")); m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); m_pLoginToMasterModule = dynamic_cast<NFILoginToMasterModule*>(pPluginManager->FindModule("NFCLoginToMasterModule")); m_pUUIDModule = dynamic_cast<NFIUUIDModule*>(pPluginManager->FindModule("NFCUUIDModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pKernelModule); assert(NULL != m_pLoginLogicModule); assert(NULL != m_pLogModule); assert(NULL != m_pLogicClassModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLoginToMasterModule); assert(NULL != m_pUUIDModule); m_pEventProcessModule->AddEventCallBack(NFIDENTID(), NFED_ON_CLIENT_LOGIN_RESULTS, this, &NFCLoginNet_ServerModule::OnLoginResultsEvent); m_pEventProcessModule->AddEventCallBack(NFIDENTID(), NFED_ON_CLIENT_SELECT_SERVER_RESULTS, this, &NFCLoginNet_ServerModule::OnSelectWorldResultsEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_LOGIN && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); m_pUUIDModule->SetIdentID(nServerID); Initialization(NFIMsgHead::NF_Head::NF_HEAD_LENGTH, this, &NFCLoginNet_ServerModule::OnReciveClientPack, &NFCLoginNet_ServerModule::OnSocketClientEvent, nMaxConnect, nPort, nCpus); } } } return true; } int NFCLoginNet_ServerModule::OnLoginResultsEvent(const NFIDENTID& object, const int nEventID, const NFIDataList& var) { if (3 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } const int nState = var.Int(0); const NFIDENTID xIdent = var.Object(1); const std::string& strAccount = var.String(2); NF_SHARE_PTR<int> xFD = mxClientIdent.GetElement(xIdent); if (xFD) { if (0 != nState) { //ʺ߱ //¼ʧ NFMsg::AckEventResult xMsg; xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, *xFD); return 0; } NetObject* pNetObject = GetNet()->GetNetObject(*xFD); if (pNetObject) { //¼¼ pNetObject->SetConnectKeyState(1); pNetObject->SetAccount(strAccount); } //ѷб㲥ȥ NFMsg::AckEventResult xData; xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, *xFD); //SynWorldToClient(unAddress); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, *xFD), "Login successed :", strAccount.c_str()); } return 0; } int NFCLoginNet_ServerModule::OnSelectWorldResultsEvent(const NFIDENTID& object, const int nEventID, const NFIDataList& var) { if (7 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_STRING, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } const int nWorldID = var.Int(0); const NFIDENTID xClientIdent = var.Object(1); const int nLoginID = var.Int(2); const std::string& strAccount = var.String(3); const std::string& strWorldAddress = var.String(4); int nPort = var.Int(5); const std::string& strWorldKey = var.String(6); NF_SHARE_PTR<int> xFD = mxClientIdent.GetElement(xClientIdent); if (xFD) { NFMsg::AckConnectWorldResult xMsg; xMsg.set_world_id(nWorldID); xMsg.mutable_sender()->CopyFrom(NFToPB(xClientIdent)); xMsg.set_login_id(nLoginID); xMsg.set_account(strAccount); xMsg.set_world_ip(strWorldAddress); xMsg.set_world_port(nPort); xMsg.set_world_key(strWorldKey); SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_CONNECT_WORLD, xMsg, *xFD); } return 0; } bool NFCLoginNet_ServerModule::Execute(const float fLasFrametime, const float fStartedTime) { return NFINetModule::Execute(fLasFrametime, fStartedTime); } void NFCLoginNet_ServerModule::OnClientConnected(const int nAddress) { NetObject* pObject = GetNet()->GetNetObject(nAddress); if (pObject) { NFIDENTID xIdent =m_pUUIDModule->CreateGUID(); pObject->SetClientID(xIdent); mxClientIdent.AddElement(xIdent, NF_SHARE_PTR<int> (NF_NEW int(nAddress)) ); } } void NFCLoginNet_ServerModule::OnClientDisconnect(const int nAddress) { NetObject* pObject = GetNet()->GetNetObject(nAddress); if (pObject) { NFIDENTID xIdent = pObject->GetClientID(); mxClientIdent.RemoveElement(xIdent); } } int NFCLoginNet_ServerModule::OnLoginProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqAccountLogin xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } NetObject* pNetObject = GetNet()->GetNetObject(msg.GetFd()); if (pNetObject) { //ûе¼ if (pNetObject->GetConnectKeyState() == 0) { NFCDataList val; val << pNetObject->GetClientID()<< xMsg.account() << xMsg.password(); m_pEventProcessModule->DoEvent(NFIDENTID(), NFED_ON_CLIENT_LOGIN, val); } } return 0; } int NFCLoginNet_ServerModule::OnSelectWorldProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqConnectWorld xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } NetObject* pNetObject = GetNet()->GetNetObject(msg.GetFd()); if (!pNetObject) { return 0; } //û¼ if (pNetObject->GetConnectKeyState() <= 0) { return 0; } NFCDataList val; val << xMsg.world_id() << pNetObject->GetClientID() << pPluginManager->AppID() << pNetObject->GetAccount(); m_pEventProcessModule->DoEvent(NFIDENTID(), NFED_ON_CLIENT_SELECT_SERVER, val); return 0; } int NFCLoginNet_ServerModule::OnReciveClientPack(const NFIPacket& msg ) { //ͳһ int nMsgID = msg.GetMsgHead()->GetMsgID(); switch (nMsgID) { case NFMsg::EGameMsgID::EGMI_STS_HEART_BEAT: break; case NFMsg::EGameMsgID::EGMI_REQ_LOGIN: OnLoginProcess(msg); break; case NFMsg::EGameMsgID::EGMI_REQ_LOGOUT: break; case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD: OnSelectWorldProcess(msg); break; case NFMsg::EGameMsgID::EGMI_REQ_WORLD_LIST: OnViewWorldProcess(msg); break; // case NFMsg::EGameMsgID::EGMI_ACK_CONNECT_WORLD: // OnObjectPropertyIntProcess(msg); // break; default: printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID); break; } return 0; } int NFCLoginNet_ServerModule::OnSocketClientEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent & NF_NET_EVENT_ERROR) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent & NF_NET_EVENT_TIMEOUT) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__); OnClientDisconnect(nSockIndex); } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); OnClientConnected(nSockIndex); } return 0; } void NFCLoginNet_ServerModule::SynWorldToClient( const int nFD ) { NFMsg::AckServerList xData; xData.set_type(NFMsg::RSLT_WORLD_SERVER); NFMapEx<int, NFMsg::ServerInfoReport>& xWorldMap = m_pLoginToMasterModule->GetWorldMap(); NFMsg::ServerInfoReport* pWorldData = xWorldMap.FirstNude(); while (pWorldData) { NFMsg::ServerInfo* pServerInfo = xData.add_info(); pServerInfo->set_name(pWorldData->server_name()); pServerInfo->set_status(pWorldData->server_state()); pServerInfo->set_server_id(pWorldData->server_id()); pServerInfo->set_wait_count(0); pWorldData = xWorldMap.NextNude(); } SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_WORLD_LIST, xData, nFD); } int NFCLoginNet_ServerModule::OnViewWorldProcess( const NFIPacket& msg ) { NFIDENTID nPlayerID; NFMsg::ReqServerList xMsg; if (!RecivePB(msg, xMsg, nPlayerID)) { return 0; } if (xMsg.type() == NFMsg::RSLT_WORLD_SERVER) { SynWorldToClient(msg.GetFd()); } return 0; } <|endoftext|>
<commit_before><commit_msg>[HF] Add test of gamma parameters to testHistFactory.<commit_after><|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <vpp/vpp.hh> #include <vpp/utils/opencv_bridge.hh> #include <vpp/algorithms/FAST_detector/FAST.hh> // #include <vpp/algorithms/FAST_detector/FAST2.hh> // #include <vpp/algorithms/FAST_detector/FAST3.hh> #include "get_time.hh" int main(int argc, char* argv[]) { using namespace vpp; ::sched_param sc_params; sc_params.sched_priority = 10; if (::sched_setscheduler(::getpid(), SCHED_FIFO, &sc_params)) ::fprintf(stderr, "sched_setscheduler(): %s\n", ::strerror(errno)); if (argc != 4) { std::cerr << "Usage : " << argv[0] << " image threshold local_maxima_only" << std::endl; return 1; } int K = 40; typedef image2d<vuchar3> I; I A = clone_with_border(from_opencv<vuchar3>(cv::imread(argv[1])), 3); I B(A.domain(), 1); image2d<unsigned char> big_image(10000,10000); image2d<unsigned char> Agl(A.domain(), 3); image2d<unsigned char> Bgl(A.domain()); image2d<int> tmp(A.domain(), 1); pixel_wise(Agl, A) << [] (unsigned char& gl, vuchar3& c) { gl = (c[0] + c[1] + c[2]) / 3; }; int lm = atoi(argv[3]); int th = atoi(argv[2]); auto time = get_time_in_seconds(); std::vector<vint2> keypoints_vpp; for (unsigned i = 0; i < K; i++) { keypoints_vpp.clear(); fast_detector9(Agl, tmp, th, lm, false); make_keypoint_vector(tmp, keypoints_vpp); } double vpp_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K; time = get_time_in_seconds(); cv::Mat cv_Agl = to_opencv(Agl); cv::Mat cv_B = to_opencv(B); std::vector<cv::KeyPoint> keypoints; double vpp_time = 0, opencv_time = 0; for (unsigned i = 0; i < K; i++) { keypoints.clear(); FAST(cv_Agl, keypoints, th, lm); } double opencv_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K; std::cout << "vpp: " << keypoints_vpp.size() << " keypoints" << std::endl; std::cout << "openmp: " << keypoints.size() << " keypoints" << std::endl; std::cout << "Time per iterations: " << std::endl << "OpenCV: " << opencv_ms_per_iter << "ms" << std::endl << "VPP: " << vpp_ms_per_iter << "ms" << std::endl; image2d<vuchar3> vpp_out(A.domain()); image2d<vuchar3> opencv_out = clone(A); pixel_wise(vpp_out, tmp, A) << [] (vuchar3& o, int& k, vuchar3& in) { if (!k) o = k ? in : vuchar3(0,0, 255); }; for (int i = 0; i < keypoints.size(); i++) opencv_out(keypoints[i].pt.y, keypoints[i].pt.x) = vuchar3(0, 0, 255); cv::imwrite("opencv.ppm", to_opencv(opencv_out)); cv::imwrite("vpp.ppm", to_opencv(vpp_out)); } <commit_msg>Fix fast benchmark.<commit_after>#include <chrono> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <vpp/vpp.hh> #include <vpp/utils/opencv_bridge.hh> #include <vpp/algorithms/FAST_detector/FAST.hh> // #include <vpp/algorithms/FAST_detector/FAST2.hh> // #include <vpp/algorithms/FAST_detector/FAST3.hh> #include "get_time.hh" int main(int argc, char* argv[]) { using namespace vpp; ::sched_param sc_params; sc_params.sched_priority = 10; if (::sched_setscheduler(::getpid(), SCHED_FIFO, &sc_params)) ::fprintf(stderr, "sched_setscheduler(): %s\n", ::strerror(errno)); if (argc != 4) { std::cerr << "Usage : " << argv[0] << " image threshold local_maxima_only" << std::endl; return 1; } int K = 40; typedef image2d<vuchar3> I; I A = clone_with_border(from_opencv<vuchar3>(cv::imread(argv[1])), 3); I B(A.domain(), 1); image2d<unsigned char> big_image(10000,10000); image2d<unsigned char> Agl(A.domain(), 3); image2d<unsigned char> Bgl(A.domain()); image2d<int> tmp(A.domain(), 1); pixel_wise(Agl, A) << [] (unsigned char& gl, vuchar3& c) { gl = (c[0] + c[1] + c[2]) / 3; }; int lm = atoi(argv[3]); int th = atoi(argv[2]); auto time = get_time_in_seconds(); std::vector<vint2> keypoints_vpp; for (unsigned i = 0; i < K; i++) { keypoints_vpp.clear(); fast_detector9(Agl, tmp, th, lm, false); make_keypoint_vector(tmp, keypoints_vpp); } double vpp_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K; time = get_time_in_seconds(); cv::Mat cv_Agl = to_opencv(Agl); cv::Mat cv_B = to_opencv(B); std::vector<cv::KeyPoint> keypoints; double vpp_time = 0, opencv_time = 0; for (unsigned i = 0; i < K; i++) { keypoints.clear(); FAST(cv_Agl, keypoints, th, lm); } double opencv_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K; std::cout << "vpp: " << keypoints_vpp.size() << " keypoints" << std::endl; std::cout << "openmp: " << keypoints.size() << " keypoints" << std::endl; std::cout << "Time per iterations: " << std::endl << "OpenCV: " << opencv_ms_per_iter << "ms" << std::endl << "VPP: " << vpp_ms_per_iter << "ms" << std::endl; image2d<vuchar3> vpp_out(A.domain()); image2d<vuchar3> opencv_out = clone(A); pixel_wise(vpp_out, tmp, A) << [] (vuchar3& o, int& k, vuchar3& in) { o = k ? vuchar3(0,0, 255) : in; }; for (int i = 0; i < keypoints.size(); i++) opencv_out(keypoints[i].pt.y, keypoints[i].pt.x) = vuchar3(0, 0, 255); cv::imwrite("opencv.ppm", to_opencv(opencv_out)); cv::imwrite("vpp.ppm", to_opencv(vpp_out)); } <|endoftext|>
<commit_before>//===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements the execution engine for MLIR modules based on LLVM Orc // JIT engine. // //===----------------------------------------------------------------------===// #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/IR/Function.h" #include "mlir/IR/Module.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Target/LLVMIR.h" #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/ExecutionEngine/ObjectCache.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/ToolOutputFile.h" using namespace mlir; using llvm::dbgs; using llvm::Error; using llvm::errs; using llvm::Expected; using llvm::LLVMContext; using llvm::MemoryBuffer; using llvm::MemoryBufferRef; using llvm::Module; using llvm::SectionMemoryManager; using llvm::StringError; using llvm::Triple; using llvm::orc::DynamicLibrarySearchGenerator; using llvm::orc::ExecutionSession; using llvm::orc::IRCompileLayer; using llvm::orc::JITTargetMachineBuilder; using llvm::orc::RTDyldObjectLinkingLayer; using llvm::orc::ThreadSafeModule; using llvm::orc::TMOwningSimpleCompiler; // Wrap a string into an llvm::StringError. static inline Error make_string_error(const llvm::Twine &message) { return llvm::make_error<StringError>(message.str(), llvm::inconvertibleErrorCode()); } namespace mlir { void SimpleObjectCache::notifyObjectCompiled(const Module *M, MemoryBufferRef ObjBuffer) { cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy( ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier()); } std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) { auto I = cachedObjects.find(M->getModuleIdentifier()); if (I == cachedObjects.end()) { dbgs() << "No object for " << M->getModuleIdentifier() << " in cache. Compiling.\n"; return nullptr; } dbgs() << "Object for " << M->getModuleIdentifier() << " loaded from cache.\n"; return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef()); } void SimpleObjectCache::dumpToObjectFile(llvm::StringRef outputFilename) { // Set up the output file. std::string errorMessage; auto file = openOutputFile(outputFilename, &errorMessage); if (!file) { llvm::errs() << errorMessage << "\n"; return; } // Dump the object generated for a single module to the output file. assert(cachedObjects.size() == 1 && "Expected only one object entry."); auto &cachedObject = cachedObjects.begin()->second; file->os() << cachedObject->getBuffer(); file->keep(); } void ExecutionEngine::dumpToObjectFile(llvm::StringRef filename) { cache->dumpToObjectFile(filename); } // Setup LLVM target triple from the current machine. bool ExecutionEngine::setupTargetTriple(Module *llvmModule) { // Setup the machine properties from the current architecture. auto targetTriple = llvm::sys::getDefaultTargetTriple(); std::string errorMessage; auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); if (!target) { errs() << "NO target: " << errorMessage << "\n"; return true; } auto machine = target->createTargetMachine(targetTriple, "generic", "", {}, {}); llvmModule->setDataLayout(machine->createDataLayout()); llvmModule->setTargetTriple(targetTriple); return false; } static std::string makePackedFunctionName(StringRef name) { return "_mlir_" + name.str(); } // For each function in the LLVM module, define an interface function that wraps // all the arguments of the original function and all its results into an i8** // pointer to provide a unified invocation interface. void packFunctionArguments(Module *module) { auto &ctx = module->getContext(); llvm::IRBuilder<> builder(ctx); llvm::DenseSet<llvm::Function *> interfaceFunctions; for (auto &func : module->getFunctionList()) { if (func.isDeclaration()) { continue; } if (interfaceFunctions.count(&func)) { continue; } // Given a function `foo(<...>)`, define the interface function // `mlir_foo(i8**)`. auto newType = llvm::FunctionType::get( builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), /*isVarArg=*/false); auto newName = makePackedFunctionName(func.getName()); auto funcCst = module->getOrInsertFunction(newName, newType); llvm::Function *interfaceFunc = llvm::cast<llvm::Function>(funcCst.getCallee()); interfaceFunctions.insert(interfaceFunc); // Extract the arguments from the type-erased argument list and cast them to // the proper types. auto bb = llvm::BasicBlock::Create(ctx); bb->insertInto(interfaceFunc); builder.SetInsertPoint(bb); llvm::Value *argList = interfaceFunc->arg_begin(); llvm::SmallVector<llvm::Value *, 8> args; args.reserve(llvm::size(func.args())); for (auto &indexedArg : llvm::enumerate(func.args())) { llvm::Value *argIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); argPtr = builder.CreateBitCast( argPtr, indexedArg.value().getType()->getPointerTo()); llvm::Value *arg = builder.CreateLoad(argPtr); args.push_back(arg); } // Call the implementation function with the extracted arguments. llvm::Value *result = builder.CreateCall(&func, args); // Assuming the result is one value, potentially of type `void`. if (!result->getType()->isVoidTy()) { llvm::Value *retIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); builder.CreateStore(result, retPtr); } // The interface function returns void. builder.CreateRetVoid(); } } ExecutionEngine::ExecutionEngine(bool enableObjectCache) : cache(enableObjectCache ? nullptr : new SimpleObjectCache()) {} Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( ModuleOp m, std::function<Error(llvm::Module *)> transformer, ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache) { auto engine = std::make_unique<ExecutionEngine>(enableObjectCache); std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); auto llvmModule = translateModuleToLLVMIR(m); if (!llvmModule) return make_string_error("could not convert to LLVM IR"); // FIXME: the triple should be passed to the translation or dialect conversion // instead of this. Currently, the LLVM module created above has no triple // associated with it. setupTargetTriple(llvmModule.get()); packFunctionArguments(llvmModule.get()); // Clone module in a new LLVMContext since translateModuleToLLVMIR buries // ownership too deeply. // TODO(zinenko): Reevaluate model of ownership of LLVMContext in LLVMDialect. SmallVector<char, 1> buffer; { llvm::raw_svector_ostream os(buffer); WriteBitcodeToFile(*llvmModule, os); } llvm::MemoryBufferRef bufferRef(llvm::StringRef(buffer.data(), buffer.size()), "cloned module buffer"); auto expectedModule = parseBitcodeFile(bufferRef, *ctx); if (!expectedModule) return expectedModule.takeError(); std::unique_ptr<Module> deserModule = std::move(*expectedModule); // Callback to create the object layer with symbol resolution to current // process and dynamically linked libraries. auto objectLinkingLayerCreator = [&](ExecutionSession &session, const Triple &TT) { auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( session, []() { return std::make_unique<SectionMemoryManager>(); }); auto dataLayout = deserModule->getDataLayout(); // Resolve symbols that are statically linked in the current process. session.getMainJITDylib().addGenerator( cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( dataLayout.getGlobalPrefix()))); // Resolve symbols from shared libraries. for (auto libPath : sharedLibPaths) { auto mb = llvm::MemoryBuffer::getFile(libPath); if (!mb) { errs() << "Fail to create MemoryBuffer for: " << libPath << "\n"; continue; } auto &JD = session.createJITDylib(libPath); auto loaded = DynamicLibrarySearchGenerator::Load( libPath.data(), dataLayout.getGlobalPrefix()); if (!loaded) { errs() << "Could not load: " << libPath << "\n"; continue; } JD.addGenerator(std::move(*loaded)); cantFail(objectLayer->add(JD, std::move(mb.get()))); } return objectLayer; }; // Callback to inspect the cache and recompile on demand. This follows Lang's // LLJITWithObjectCache example. auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) -> Expected<IRCompileLayer::CompileFunction> { auto TM = JTMB.createTargetMachine(); if (!TM) return TM.takeError(); return IRCompileLayer::CompileFunction( TMOwningSimpleCompiler(std::move(*TM), engine->cache.get())); }; // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. auto jit = cantFail(llvm::orc::LLJITBuilder() .setCompileFunctionCreator(compileFunctionCreator) .setObjectLinkingLayerCreator(objectLinkingLayerCreator) .create()); // Add a ThreadSafemodule to the engine and return. ThreadSafeModule tsm(std::move(deserModule), std::move(ctx)); cantFail(jit->addIRModule(std::move(tsm))); engine->jit = std::move(jit); return std::move(engine); } Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); if (!expectedSymbol) return expectedSymbol.takeError(); auto rawFPtr = expectedSymbol->getAddress(); auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); if (!fptr) return make_string_error("looked up function is null"); return fptr; } Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { auto expectedFPtr = lookup(name); if (!expectedFPtr) return expectedFPtr.takeError(); auto fptr = *expectedFPtr; (*fptr)(args.data()); return Error::success(); } } // end namespace mlir <commit_msg>Use transform function on llvm::Module in the ExecutionEngine<commit_after>//===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements the execution engine for MLIR modules based on LLVM Orc // JIT engine. // //===----------------------------------------------------------------------===// #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/IR/Function.h" #include "mlir/IR/Module.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Target/LLVMIR.h" #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/ExecutionEngine/ObjectCache.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/ToolOutputFile.h" using namespace mlir; using llvm::dbgs; using llvm::Error; using llvm::errs; using llvm::Expected; using llvm::LLVMContext; using llvm::MemoryBuffer; using llvm::MemoryBufferRef; using llvm::Module; using llvm::SectionMemoryManager; using llvm::StringError; using llvm::Triple; using llvm::orc::DynamicLibrarySearchGenerator; using llvm::orc::ExecutionSession; using llvm::orc::IRCompileLayer; using llvm::orc::JITTargetMachineBuilder; using llvm::orc::RTDyldObjectLinkingLayer; using llvm::orc::ThreadSafeModule; using llvm::orc::TMOwningSimpleCompiler; // Wrap a string into an llvm::StringError. static inline Error make_string_error(const llvm::Twine &message) { return llvm::make_error<StringError>(message.str(), llvm::inconvertibleErrorCode()); } namespace mlir { void SimpleObjectCache::notifyObjectCompiled(const Module *M, MemoryBufferRef ObjBuffer) { cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy( ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier()); } std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) { auto I = cachedObjects.find(M->getModuleIdentifier()); if (I == cachedObjects.end()) { dbgs() << "No object for " << M->getModuleIdentifier() << " in cache. Compiling.\n"; return nullptr; } dbgs() << "Object for " << M->getModuleIdentifier() << " loaded from cache.\n"; return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef()); } void SimpleObjectCache::dumpToObjectFile(llvm::StringRef outputFilename) { // Set up the output file. std::string errorMessage; auto file = openOutputFile(outputFilename, &errorMessage); if (!file) { llvm::errs() << errorMessage << "\n"; return; } // Dump the object generated for a single module to the output file. assert(cachedObjects.size() == 1 && "Expected only one object entry."); auto &cachedObject = cachedObjects.begin()->second; file->os() << cachedObject->getBuffer(); file->keep(); } void ExecutionEngine::dumpToObjectFile(llvm::StringRef filename) { cache->dumpToObjectFile(filename); } // Setup LLVM target triple from the current machine. bool ExecutionEngine::setupTargetTriple(Module *llvmModule) { // Setup the machine properties from the current architecture. auto targetTriple = llvm::sys::getDefaultTargetTriple(); std::string errorMessage; auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); if (!target) { errs() << "NO target: " << errorMessage << "\n"; return true; } auto machine = target->createTargetMachine(targetTriple, "generic", "", {}, {}); llvmModule->setDataLayout(machine->createDataLayout()); llvmModule->setTargetTriple(targetTriple); return false; } static std::string makePackedFunctionName(StringRef name) { return "_mlir_" + name.str(); } // For each function in the LLVM module, define an interface function that wraps // all the arguments of the original function and all its results into an i8** // pointer to provide a unified invocation interface. void packFunctionArguments(Module *module) { auto &ctx = module->getContext(); llvm::IRBuilder<> builder(ctx); llvm::DenseSet<llvm::Function *> interfaceFunctions; for (auto &func : module->getFunctionList()) { if (func.isDeclaration()) { continue; } if (interfaceFunctions.count(&func)) { continue; } // Given a function `foo(<...>)`, define the interface function // `mlir_foo(i8**)`. auto newType = llvm::FunctionType::get( builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), /*isVarArg=*/false); auto newName = makePackedFunctionName(func.getName()); auto funcCst = module->getOrInsertFunction(newName, newType); llvm::Function *interfaceFunc = llvm::cast<llvm::Function>(funcCst.getCallee()); interfaceFunctions.insert(interfaceFunc); // Extract the arguments from the type-erased argument list and cast them to // the proper types. auto bb = llvm::BasicBlock::Create(ctx); bb->insertInto(interfaceFunc); builder.SetInsertPoint(bb); llvm::Value *argList = interfaceFunc->arg_begin(); llvm::SmallVector<llvm::Value *, 8> args; args.reserve(llvm::size(func.args())); for (auto &indexedArg : llvm::enumerate(func.args())) { llvm::Value *argIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); argPtr = builder.CreateBitCast( argPtr, indexedArg.value().getType()->getPointerTo()); llvm::Value *arg = builder.CreateLoad(argPtr); args.push_back(arg); } // Call the implementation function with the extracted arguments. llvm::Value *result = builder.CreateCall(&func, args); // Assuming the result is one value, potentially of type `void`. if (!result->getType()->isVoidTy()) { llvm::Value *retIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); builder.CreateStore(result, retPtr); } // The interface function returns void. builder.CreateRetVoid(); } } ExecutionEngine::ExecutionEngine(bool enableObjectCache) : cache(enableObjectCache ? nullptr : new SimpleObjectCache()) {} Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( ModuleOp m, std::function<Error(llvm::Module *)> transformer, ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache) { auto engine = std::make_unique<ExecutionEngine>(enableObjectCache); std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); auto llvmModule = translateModuleToLLVMIR(m); if (!llvmModule) return make_string_error("could not convert to LLVM IR"); // FIXME: the triple should be passed to the translation or dialect conversion // instead of this. Currently, the LLVM module created above has no triple // associated with it. setupTargetTriple(llvmModule.get()); packFunctionArguments(llvmModule.get()); // Clone module in a new LLVMContext since translateModuleToLLVMIR buries // ownership too deeply. // TODO(zinenko): Reevaluate model of ownership of LLVMContext in LLVMDialect. SmallVector<char, 1> buffer; { llvm::raw_svector_ostream os(buffer); WriteBitcodeToFile(*llvmModule, os); } llvm::MemoryBufferRef bufferRef(llvm::StringRef(buffer.data(), buffer.size()), "cloned module buffer"); auto expectedModule = parseBitcodeFile(bufferRef, *ctx); if (!expectedModule) return expectedModule.takeError(); std::unique_ptr<Module> deserModule = std::move(*expectedModule); // Callback to create the object layer with symbol resolution to current // process and dynamically linked libraries. auto objectLinkingLayerCreator = [&](ExecutionSession &session, const Triple &TT) { auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( session, []() { return std::make_unique<SectionMemoryManager>(); }); auto dataLayout = deserModule->getDataLayout(); // Resolve symbols that are statically linked in the current process. session.getMainJITDylib().addGenerator( cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( dataLayout.getGlobalPrefix()))); // Resolve symbols from shared libraries. for (auto libPath : sharedLibPaths) { auto mb = llvm::MemoryBuffer::getFile(libPath); if (!mb) { errs() << "Fail to create MemoryBuffer for: " << libPath << "\n"; continue; } auto &JD = session.createJITDylib(libPath); auto loaded = DynamicLibrarySearchGenerator::Load( libPath.data(), dataLayout.getGlobalPrefix()); if (!loaded) { errs() << "Could not load: " << libPath << "\n"; continue; } JD.addGenerator(std::move(*loaded)); cantFail(objectLayer->add(JD, std::move(mb.get()))); } return objectLayer; }; // Callback to inspect the cache and recompile on demand. This follows Lang's // LLJITWithObjectCache example. auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) -> Expected<IRCompileLayer::CompileFunction> { auto TM = JTMB.createTargetMachine(); if (!TM) return TM.takeError(); return IRCompileLayer::CompileFunction( TMOwningSimpleCompiler(std::move(*TM), engine->cache.get())); }; // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. auto jit = cantFail(llvm::orc::LLJITBuilder() .setCompileFunctionCreator(compileFunctionCreator) .setObjectLinkingLayerCreator(objectLinkingLayerCreator) .create()); // Add a ThreadSafemodule to the engine and return. ThreadSafeModule tsm(std::move(deserModule), std::move(ctx)); if (transformer) cantFail(tsm.withModuleDo( [&](llvm::Module &module) { return transformer(&module); })); cantFail(jit->addIRModule(std::move(tsm))); engine->jit = std::move(jit); return std::move(engine); } Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); if (!expectedSymbol) return expectedSymbol.takeError(); auto rawFPtr = expectedSymbol->getAddress(); auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); if (!fptr) return make_string_error("looked up function is null"); return fptr; } Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { auto expectedFPtr = lookup(name); if (!expectedFPtr) return expectedFPtr.takeError(); auto fptr = *expectedFPtr; (*fptr)(args.data()); return Error::success(); } } // end namespace mlir <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VndSunStarPkgUrlReferenceFactory.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-09-27 13:06:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_stoc.hxx" #include "stocservices.hxx" #include "supportsService.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/uno/Exception.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uri/UriReferenceFactory.hpp" #include "com/sun/star/uri/XUriReference.hpp" #include "com/sun/star/uri/XUriReferenceFactory.hpp" #include "com/sun/star/uri/XVndSunStarPkgUrlReferenceFactory.hpp" #include "cppuhelper/implbase2.hxx" #include "cppuhelper/weak.hxx" #include "rtl/string.h" #include "rtl/textenc.h" #include "rtl/uri.h" #include "rtl/uri.hxx" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" #include "sal/types.h" #include <new> namespace css = com::sun::star; namespace { class Factory: public cppu::WeakImplHelper2< css::lang::XServiceInfo, css::uri::XVndSunStarPkgUrlReferenceFactory > { public: explicit Factory( css::uno::Reference< css::uno::XComponentContext > const & context): m_context(context) {} virtual rtl::OUString SAL_CALL getImplementationName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException); virtual css::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (css::uno::RuntimeException); virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL createVndSunStarPkgUrlReference( css::uno::Reference< css::uri::XUriReference > const & authority) throw (css::uno::RuntimeException); private: Factory(Factory &); // not implemented void operator =(Factory); // not implemented virtual ~Factory() {} css::uno::Reference< css::uno::XComponentContext > m_context; }; rtl::OUString Factory::getImplementationName() throw (css::uno::RuntimeException) { return stoc_services::VndSunStarPkgUrlReferenceFactory:: getImplementationName(); } sal_Bool Factory::supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException) { return stoc::uriproc::supportsService( getSupportedServiceNames(), serviceName); } css::uno::Sequence< rtl::OUString > Factory::getSupportedServiceNames() throw (css::uno::RuntimeException) { return stoc_services::VndSunStarPkgUrlReferenceFactory:: getSupportedServiceNames(); } css::uno::Reference< css::uri::XUriReference > Factory::createVndSunStarPkgUrlReference( css::uno::Reference< css::uri::XUriReference > const & authority) throw (css::uno::RuntimeException) { OSL_ASSERT(authority.is()); if (authority->isAbsolute() && !authority->hasFragment()) { rtl::OUStringBuffer buf; buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.pkg://")); buf.append( rtl::Uri::encode( authority->getUriReference(), rtl_UriCharClassRegName, rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8)); css::uno::Reference< css::uri::XUriReference > uriRef( css::uri::UriReferenceFactory::create(m_context)->parse( buf.makeStringAndClear())); OSL_ASSERT(uriRef.is()); return uriRef; } else { return css::uno::Reference< css::uri::XUriReference >(); } } } namespace stoc_services { namespace VndSunStarPkgUrlReferenceFactory { css::uno::Reference< css::uno::XInterface > create( css::uno::Reference< css::uno::XComponentContext > const & context) SAL_THROW((css::uno::Exception)) { try { return static_cast< cppu::OWeakObject * >(new Factory(context)); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } rtl::OUString getImplementationName() { return rtl::OUString::createFromAscii( "com.sun.star.comp.uri.VndSunStarPkgUrlReferenceFactory"); } css::uno::Sequence< rtl::OUString > getSupportedServiceNames() { css::uno::Sequence< rtl::OUString > s(1); s[0] = rtl::OUString::createFromAscii( "com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"); return s; } } } <commit_msg>INTEGRATION: CWS changefileheader (1.5.12); FILE MERGED 2008/03/31 07:26:14 rt 1.5.12.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VndSunStarPkgUrlReferenceFactory.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_stoc.hxx" #include "stocservices.hxx" #include "supportsService.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/uno/Exception.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uri/UriReferenceFactory.hpp" #include "com/sun/star/uri/XUriReference.hpp" #include "com/sun/star/uri/XUriReferenceFactory.hpp" #include "com/sun/star/uri/XVndSunStarPkgUrlReferenceFactory.hpp" #include "cppuhelper/implbase2.hxx" #include "cppuhelper/weak.hxx" #include "rtl/string.h" #include "rtl/textenc.h" #include "rtl/uri.h" #include "rtl/uri.hxx" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" #include "sal/types.h" #include <new> namespace css = com::sun::star; namespace { class Factory: public cppu::WeakImplHelper2< css::lang::XServiceInfo, css::uri::XVndSunStarPkgUrlReferenceFactory > { public: explicit Factory( css::uno::Reference< css::uno::XComponentContext > const & context): m_context(context) {} virtual rtl::OUString SAL_CALL getImplementationName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException); virtual css::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (css::uno::RuntimeException); virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL createVndSunStarPkgUrlReference( css::uno::Reference< css::uri::XUriReference > const & authority) throw (css::uno::RuntimeException); private: Factory(Factory &); // not implemented void operator =(Factory); // not implemented virtual ~Factory() {} css::uno::Reference< css::uno::XComponentContext > m_context; }; rtl::OUString Factory::getImplementationName() throw (css::uno::RuntimeException) { return stoc_services::VndSunStarPkgUrlReferenceFactory:: getImplementationName(); } sal_Bool Factory::supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException) { return stoc::uriproc::supportsService( getSupportedServiceNames(), serviceName); } css::uno::Sequence< rtl::OUString > Factory::getSupportedServiceNames() throw (css::uno::RuntimeException) { return stoc_services::VndSunStarPkgUrlReferenceFactory:: getSupportedServiceNames(); } css::uno::Reference< css::uri::XUriReference > Factory::createVndSunStarPkgUrlReference( css::uno::Reference< css::uri::XUriReference > const & authority) throw (css::uno::RuntimeException) { OSL_ASSERT(authority.is()); if (authority->isAbsolute() && !authority->hasFragment()) { rtl::OUStringBuffer buf; buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.pkg://")); buf.append( rtl::Uri::encode( authority->getUriReference(), rtl_UriCharClassRegName, rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8)); css::uno::Reference< css::uri::XUriReference > uriRef( css::uri::UriReferenceFactory::create(m_context)->parse( buf.makeStringAndClear())); OSL_ASSERT(uriRef.is()); return uriRef; } else { return css::uno::Reference< css::uri::XUriReference >(); } } } namespace stoc_services { namespace VndSunStarPkgUrlReferenceFactory { css::uno::Reference< css::uno::XInterface > create( css::uno::Reference< css::uno::XComponentContext > const & context) SAL_THROW((css::uno::Exception)) { try { return static_cast< cppu::OWeakObject * >(new Factory(context)); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } rtl::OUString getImplementationName() { return rtl::OUString::createFromAscii( "com.sun.star.comp.uri.VndSunStarPkgUrlReferenceFactory"); } css::uno::Sequence< rtl::OUString > getSupportedServiceNames() { css::uno::Sequence< rtl::OUString > s(1); s[0] = rtl::OUString::createFromAscii( "com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"); return s; } } } <|endoftext|>
<commit_before>#include "UbidotsFONA.h" #include <stdlib.h> /** * Constructor. */ Ubidots::Ubidots(char* token, char* server = NULL){ _token = token; _server = server; _dsName = NULL; _dsTag = "FONA"; currentValue = 0; val = (Value *)malloc(MAX_VALUES*sizeof(Value)); fonaSS.begin(4800); } void Ubidots::begin() { pinMode(FONA_RST, OUTPUT); digitalWrite(FONA_RST, HIGH); delay(10); digitalWrite(FONA_RST, LOW); delay(100); digitalWrite(FONA_RST, HIGH); delay(500); } void Ubidots::setDataSourceName(char* dsName) { _dsName = dsName; } void Ubidots::setDataSourceTag(char* dsTag) { _dsTag = dsTag; } void Ubidots::add(char *variable_id, float value, char *ctext1) { (val+currentValue)->idName = variable_id; (val+currentValue)->ctext = contextOne; (val+currentValue)->varValue = idValue; currentValue++; if (currentValue > MAX_VALUE) { currentValue = MAX_VALUE; } } bool Ubidots::waitForOK(uint16_t timeout) { int len; uint32_t ts_max = millis() + timeout; while ((len = readLine(ts_max)) >= 0) { if (len == 0) { // Skip empty lines continue; } if (strcmp_P(buffer, PSTR("OK")) == 0) { return true; } else if (strcmp_P(buffer, PSTR("ERROR")) == 0) { return false; } // Other input is skipped. } return false; } bool Ubidots::setApn(char* apn, char* user, char* pwd) { fonaSS.println("AT"); if (!waitForOK(6000)) { SerialUSB.println("------>AT"); return false; } fonaSS.println("AT+CSQ"); if (!waitForOK(6000)) { SerialUSB.println("Error at CSQ"); return false; } fonaSS.println("AT+CIPSHUT"); if (!waitForOK(6000)) { SerialUSB.println("Error at CIPSHUT"); return false; } fonaSS.println("AT+CGATT?"); if (!waitForOK(6000)) { SerialUSB.println("GPRS is not attached"); return false; } fonaSS.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up CONTYPE"); return false; } fonaSS.print("AT+SAPBR=3,1,\"APN\",\""); fonaSS.print(apn); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up APN"); return false; } fonaSS.print("AT+SAPBR=3,1,\"USER\",\""); fonaSS.print(user); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up apn user"); return false; } fonaSS.print("AT+SAPBR=3,1,\"PWD\",\""); fonaSS.print(pwd); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up apn pass"); return false; } fonaSS.println("AT+SAPBR=1,1"); if (!waitForOK(6000)) { SerialUSB.println("Error with AT+SAPBR=1,1 Connection ip"); return false; } fonaSS.println("AT+SAPBR=2,1"); if (!waitForOK(6000)) { SerialUSB.println("Error with AT+SAPBR=2,1 no IP to show"); return false; } return true; } bool Ubidots::sendAll() { int i; String all; String str; all = USER_AGENT; all += VERSION; all += "|POST|"; all += _token; all += "|"; all += _dsTag; if (_dsName != NULL) { all += ":"; all += _dsName; } all += "=>"; for (i = 0; i < currentValue; ) { str = String(((val + i)->varValue), 2); all += String((val + i)->varName); all += ":"; all += str; if ((val + i)->ctext != NULL) { all += "$"; all += String((val + i)->ctext); } all += ","; i++; } all += "|end"; Serial.println(all.c_str()); fonaSS.println("AT+CIPMUX=0"); if (!waitForOK(6000)) { SerialUSB.println("Error CIPMUX=0"); return false; } fonaSS.print("AT+CIPSTART=\"TCP\",\""); fonaSS.print(SERVER); fonaSS.print("\",\""); fonaSS.print(PORT); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at CIPSTART"); return false; } fonaSS.println("AT+CIPSEND"); if (!waitForMessage(">", 6000)) { SerialUSB.println("Error at CIPSEND"); return false; } fonaSS.write(all.c_str()); fonaSS.write(0x1A); if (!waitForMessage("SEND OK", 6000)) { SerialUSB.println("Error sending the message"); return false; } fonaSS.println("AT+CIPCLOSE"); if (!waitForMessage("CLOSE OK", 6000)) { SerialUSB.println("Error closing TCP connection"); return false; } return true; } bool Ubidots::waitForMessage(const char *msg, uint32_t ts_max) { int len; while ((len = readLine(ts_max)) >= 0) { if (len == 0) { // Skip empty lines continue; } if (strncmp(buffer, msg, strlen(msg)) == 0) { return true; } } return false; // This indicates: timed out } void Ubidots::turnOnFona(){ Serial.println("Turning on Fona: "); while(digitalRead(FONA_PS)==LOW){ digitalWrite(FONA_KEY, LOW); } digitalWrite(FONA_KEY, HIGH); delay(4000); } void Ubidots::turnOffFona(){ Serial.println("Turning off Fona "); while(digitalRead(FONA_PS)==HIGH) { digitalWrite(FONA_KEY, LOW); } digitalWrite(FONA_KEY, HIGH); delay(4000); }<commit_msg>added an optional server settings<commit_after>#include "UbidotsFONA.h" #include <stdlib.h> /** * Constructor. */ Ubidots::Ubidots(char* token, char* server = NULL){ _token = token; _server = server; _dsName = NULL; _dsTag = "FONA"; currentValue = 0; val = (Value *)malloc(MAX_VALUES*sizeof(Value)); fonaSS.begin(4800); } void Ubidots::begin() { pinMode(FONA_RST, OUTPUT); digitalWrite(FONA_RST, HIGH); delay(10); digitalWrite(FONA_RST, LOW); delay(100); digitalWrite(FONA_RST, HIGH); delay(500); } void Ubidots::setDataSourceName(char* dsName) { _dsName = dsName; } void Ubidots::setDataSourceTag(char* dsTag) { _dsTag = dsTag; } void Ubidots::add(char *variable_id, float value, char *ctext1) { (val+currentValue)->idName = variable_id; (val+currentValue)->ctext = contextOne; (val+currentValue)->varValue = idValue; currentValue++; if (currentValue > MAX_VALUE) { currentValue = MAX_VALUE; } } bool Ubidots::waitForOK(uint16_t timeout) { int len; uint32_t ts_max = millis() + timeout; while ((len = readLine(ts_max)) >= 0) { if (len == 0) { // Skip empty lines continue; } if (strcmp_P(buffer, PSTR("OK")) == 0) { return true; } else if (strcmp_P(buffer, PSTR("ERROR")) == 0) { return false; } // Other input is skipped. } return false; } bool Ubidots::setApn(char* apn, char* user, char* pwd) { fonaSS.println("AT"); if (!waitForOK(6000)) { SerialUSB.println("------>AT"); return false; } fonaSS.println("AT+CSQ"); if (!waitForOK(6000)) { SerialUSB.println("Error at CSQ"); return false; } fonaSS.println("AT+CIPSHUT"); if (!waitForOK(6000)) { SerialUSB.println("Error at CIPSHUT"); return false; } fonaSS.println("AT+CGATT?"); if (!waitForOK(6000)) { SerialUSB.println("GPRS is not attached"); return false; } fonaSS.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up CONTYPE"); return false; } fonaSS.print("AT+SAPBR=3,1,\"APN\",\""); fonaSS.print(apn); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up APN"); return false; } fonaSS.print("AT+SAPBR=3,1,\"USER\",\""); fonaSS.print(user); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up apn user"); return false; } fonaSS.print("AT+SAPBR=3,1,\"PWD\",\""); fonaSS.print(pwd); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at setting up apn pass"); return false; } fonaSS.println("AT+SAPBR=1,1"); if (!waitForOK(6000)) { SerialUSB.println("Error with AT+SAPBR=1,1 Connection ip"); return false; } fonaSS.println("AT+SAPBR=2,1"); if (!waitForOK(6000)) { SerialUSB.println("Error with AT+SAPBR=2,1 no IP to show"); return false; } return true; } bool Ubidots::sendAll() { int i; String all; String str; all = USER_AGENT; all += VERSION; all += "|POST|"; all += _token; all += "|"; all += _dsTag; if (_dsName != NULL) { all += ":"; all += _dsName; } all += "=>"; for (i = 0; i < currentValue; ) { str = String(((val + i)->varValue), 2); all += String((val + i)->varName); all += ":"; all += str; if ((val + i)->ctext != NULL) { all += "$"; all += String((val + i)->ctext); } all += ","; i++; } all += "|end"; Serial.println(all.c_str()); fonaSS.println("AT+CIPMUX=0"); if (!waitForOK(6000)) { SerialUSB.println("Error CIPMUX=0"); return false; } fonaSS.print("AT+CIPSTART=\"TCP\",\""); if (_server != NULL) { fonaSS.print(_server); } else { fonaSS.print(SERVER); } fonaSS.print("\",\""); fonaSS.print(PORT); fonaSS.println("\""); if (!waitForOK(6000)) { SerialUSB.println("Error at CIPSTART"); return false; } fonaSS.println("AT+CIPSEND"); if (!waitForMessage(">", 6000)) { SerialUSB.println("Error at CIPSEND"); return false; } fonaSS.write(all.c_str()); fonaSS.write(0x1A); if (!waitForMessage("SEND OK", 6000)) { SerialUSB.println("Error sending the message"); return false; } fonaSS.println("AT+CIPCLOSE"); if (!waitForMessage("CLOSE OK", 6000)) { SerialUSB.println("Error closing TCP connection"); return false; } return true; } bool Ubidots::waitForMessage(const char *msg, uint32_t ts_max) { int len; while ((len = readLine(ts_max)) >= 0) { if (len == 0) { // Skip empty lines continue; } if (strncmp(buffer, msg, strlen(msg)) == 0) { return true; } } return false; // This indicates: timed out } void Ubidots::turnOnFona(){ Serial.println("Turning on Fona: "); while(digitalRead(FONA_PS)==LOW){ digitalWrite(FONA_KEY, LOW); } digitalWrite(FONA_KEY, HIGH); delay(4000); } void Ubidots::turnOffFona(){ Serial.println("Turning off Fona "); while(digitalRead(FONA_PS)==HIGH) { digitalWrite(FONA_KEY, LOW); } digitalWrite(FONA_KEY, HIGH); delay(4000); }<|endoftext|>
<commit_before>/** * @copyright * ==================================================================== * 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. * ==================================================================== * @endcopyright * * @file LogMessageCallback.cpp * @brief Implementation of the class LogMessageCallback */ #include "LogMessageCallback.h" #include "CreateJ.h" #include "EnumMapper.h" #include "JNIUtil.h" #include "svn_time.h" #include "svn_sorts.h" #include "svn_compat.h" /** * Create a LogMessageCallback object * @param jcallback the Java callback object. */ LogMessageCallback::LogMessageCallback(jobject jcallback) { m_callback = jcallback; } /** * Destroy a LogMessageCallback object */ LogMessageCallback::~LogMessageCallback() { // The m_callback does not need to be destroyed because it is the // passed in parameter to the Java SVNClientInterface.logMessages // method. } svn_error_t * LogMessageCallback::callback(void *baton, svn_log_entry_t *log_entry, apr_pool_t *pool) { if (baton) return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool); return SVN_NO_ERROR; } /** * Callback called for a single log message */ svn_error_t * LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); // The method id will not change during the time this library is // loaded, so it can be cached. static jmethodID sm_mid = 0; if (sm_mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/callback/LogMessageCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; sm_mid = env->GetMethodID(clazz, "singleMessage", "(Ljava/util/Set;JLjava/util/Map;Z)V"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID midCP = 0; if (midCP == 0) { midCP = env->GetMethodID(clazzCP, "<init>", "(Ljava/lang/String;JLjava/lang/String;CIII)V"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jobject jChangedPaths = NULL; if (log_entry->changed_paths) { apr_hash_index_t *hi; std::vector<jobject> jcps; for (hi = apr_hash_first(pool, log_entry->changed_paths); hi; hi = apr_hash_next(hi)) { const char *path = (const char *) svn_apr_hash_index_key(hi); svn_log_changed_path2_t *log_item = (svn_log_changed_path2_t *) svn_apr_hash_index_val(hi); jstring jpath = JNIUtil::makeJString(path); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jstring jcopyFromPath = JNIUtil::makeJString(log_item->copyfrom_path); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jlong jcopyFromRev = log_item->copyfrom_rev; jchar jaction = log_item->action; jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev, jcopyFromPath, jaction, EnumMapper::mapNodeKind(log_item->node_kind), EnumMapper::mapTristate(log_item->text_modified), EnumMapper::mapTristate(log_item->props_modified)); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jcps.push_back(cp); env->DeleteLocalRef(jpath); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jcopyFromPath); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jChangedPaths = CreateJ::Set(jcps); } jobject jrevprops = NULL; if (log_entry->revprops != NULL && apr_hash_count(log_entry->revprops) > 0) jrevprops = CreateJ::PropertyMap(log_entry->revprops, pool); env->CallVoidMethod(m_callback, sm_mid, jChangedPaths, (jlong)log_entry->revision, jrevprops, (jboolean)log_entry->has_children); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jChangedPaths); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jrevprops); // No need to check for an exception here, because we return anyway. return SVN_NO_ERROR; } <commit_msg>JavaHL: Fix build errors introduced by r922003.<commit_after>/** * @copyright * ==================================================================== * 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. * ==================================================================== * @endcopyright * * @file LogMessageCallback.cpp * @brief Implementation of the class LogMessageCallback */ #include "LogMessageCallback.h" #include "CreateJ.h" #include "EnumMapper.h" #include "JNIUtil.h" #include "svn_time.h" #include "svn_sorts.h" #include "svn_compat.h" /** * Create a LogMessageCallback object * @param jcallback the Java callback object. */ LogMessageCallback::LogMessageCallback(jobject jcallback) { m_callback = jcallback; } /** * Destroy a LogMessageCallback object */ LogMessageCallback::~LogMessageCallback() { // The m_callback does not need to be destroyed because it is the // passed in parameter to the Java SVNClientInterface.logMessages // method. } svn_error_t * LogMessageCallback::callback(void *baton, svn_log_entry_t *log_entry, apr_pool_t *pool) { if (baton) return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool); return SVN_NO_ERROR; } /** * Callback called for a single log message */ svn_error_t * LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); // The method id will not change during the time this library is // loaded, so it can be cached. static jmethodID sm_mid = 0; if (sm_mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/callback/LogMessageCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; sm_mid = env->GetMethodID(clazz, "singleMessage", "(Ljava/util/Set;JLjava/util/Map;Z)V"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID midCP = 0; if (midCP == 0) { midCP = env->GetMethodID(clazzCP, "<init>", "(Ljava/lang/String;JLjava/lang/String;CIII)V"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jobject jChangedPaths = NULL; if (log_entry->changed_paths) { apr_hash_index_t *hi; std::vector<jobject> jcps; for (hi = apr_hash_first(pool, log_entry->changed_paths); hi; hi = apr_hash_next(hi)) { const char *path = (const char *) svn__apr_hash_index_key(hi); svn_log_changed_path2_t *log_item = (svn_log_changed_path2_t *) svn__apr_hash_index_val(hi); jstring jpath = JNIUtil::makeJString(path); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jstring jcopyFromPath = JNIUtil::makeJString(log_item->copyfrom_path); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jlong jcopyFromRev = log_item->copyfrom_rev; jchar jaction = log_item->action; jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev, jcopyFromPath, jaction, EnumMapper::mapNodeKind(log_item->node_kind), EnumMapper::mapTristate(log_item->text_modified), EnumMapper::mapTristate(log_item->props_modified)); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; jcps.push_back(cp); env->DeleteLocalRef(jpath); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jcopyFromPath); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jChangedPaths = CreateJ::Set(jcps); } jobject jrevprops = NULL; if (log_entry->revprops != NULL && apr_hash_count(log_entry->revprops) > 0) jrevprops = CreateJ::PropertyMap(log_entry->revprops, pool); env->CallVoidMethod(m_callback, sm_mid, jChangedPaths, (jlong)log_entry->revision, jrevprops, (jboolean)log_entry->has_children); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jChangedPaths); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jrevprops); // No need to check for an exception here, because we return anyway. return SVN_NO_ERROR; } <|endoftext|>
<commit_before>#include <chrono> #include <memory> #include <iostream> #include <SFML/Graphics.hpp> #include <Wind/Engine/Entity/Entity.hpp> #include <Wind/Engine/Engine/Engine.hpp> int main() { sf::RenderWindow window{{800, 600}, "Windtunnel"}; window.setFramerateLimit(1000); // Basic particle shape sf::CircleShape particle_shape; particle_shape.setRadius(0.75f); particle_shape.setFillColor(sf::Color::Red); wind::Engine engine; // Create array of physics objects wind::Vector2u amount{30, 30}; std::vector<std::shared_ptr<wind::Entity>> particles; particles.resize(amount.x*amount.y); std::cout<<"num_particles: "<<particles.size()<<std::endl; // Assign particle positions for(auto particle_index=0; particle_index < particles.size(); ++particle_index) { auto& particle = particles[particle_index]; particle = std::make_shared<wind::Entity>(); particle->position.x = particle_index%amount.y; particle->position.y = particle_index/amount.x; particle->position.x*= window.getSize().x/amount.x; particle->position.y*= window.getSize().y/amount.y; particle->mass = 10000.f; particle->gravity_exert=true; particle->gravity_affected=true; engine.add_entity(particle); } // Used for calculating frametimes auto frame_start = std::chrono::high_resolution_clock::now(); while(window.isOpen()) { auto frame_duration = std::chrono::high_resolution_clock::now() - frame_start; frame_start = std::chrono::high_resolution_clock::now(); auto frame_duration_us = std::chrono::duration_cast<std::chrono::microseconds>(frame_duration); auto frametime_us = frame_duration_us.count(); auto frametime_ms = frametime_us/1000.f; auto frametime_s = frametime_ms/1000.f; window.setTitle( "Windtunnel :: [FPS] " + std::to_string(1.f/(frametime_s)) + "\t:: [Frametime] " + std::to_string(frametime_us) + "us" ); sf::Event event; while(window.pollEvent(event)) { switch(event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyReleased: switch(event.key.code) { case sf::Keyboard::G: engine.gravity = !engine.gravity; break; default: break; } default: break; } } window.clear(); engine.simulate(wind::Engine::StandardDuration(30.f)); for(auto& particle : particles) { particle_shape.setPosition(particle->position.x, particle->position.y); window.draw(particle_shape); } window.display(); } } <commit_msg>examples: testbench: Updated testbench to use new body framework<commit_after>#include <chrono> #include <memory> #include <iostream> #include <SFML/Graphics.hpp> #include <Wind/Engine/Body/Body.hpp> #include <Wind/Engine/Shape/Shape.hpp> #include <Wind/Engine/Shape/CircleShape.hpp> #include <Wind/Engine/Entity/Entity.hpp> #include <Wind/Engine/Engine/Engine.hpp> int main() { sf::RenderWindow window{{800, 600}, "Windtunnel"}; window.setFramerateLimit(1000); // Basic particle shape sf::CircleShape particle_drawable; particle_drawable.setRadius(0.75f); particle_drawable.setFillColor(sf::Color::Red); wind::Engine engine; // Create array of physics objects wind::Vector2u amount{40, 40}; std::vector<std::shared_ptr<wind::Entity>> particles; particles.resize(amount.x*amount.y); std::cout<<"num_particles: "<<particles.size()<<std::endl; // Create particle shapes and bodies std::shared_ptr<wind::Body> particle_body=std::make_shared<wind::Body>(); std::shared_ptr<wind::Shape> particle_shape=std::make_shared<wind::CircleShape>(0.75f); particle_body->add_shape(particle_shape); // Assign particle positions for(auto particle_index=0; particle_index < particles.size(); ++particle_index) { auto& particle = particles[particle_index]; particle = std::make_shared<wind::Entity>(); particle->position.x = particle_index%amount.y; particle->position.y = particle_index/amount.x; particle->position.x*= window.getSize().x/amount.x; particle->position.y*= window.getSize().y/amount.y; particle->mass = 10000.f; particle->gravity_exert=true; particle->gravity_affected=true; particle->set_body(particle_body); engine.add_entity(particle); } // Used for calculating frametimes auto frame_start = std::chrono::high_resolution_clock::now(); while(window.isOpen()) { auto frame_duration = std::chrono::high_resolution_clock::now() - frame_start; frame_start = std::chrono::high_resolution_clock::now(); auto frame_duration_us = std::chrono::duration_cast<std::chrono::microseconds>(frame_duration); auto frametime_us = frame_duration_us.count(); auto frametime_ms = frametime_us/1000.f; auto frametime_s = frametime_ms/1000.f; window.setTitle( "Windtunnel :: [FPS] " + std::to_string(1.f/(frametime_s)) + "\t:: [Frametime] " + std::to_string(frametime_us) + "us" ); sf::Event event; while(window.pollEvent(event)) { switch(event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyReleased: switch(event.key.code) { case sf::Keyboard::G: engine.gravity = !engine.gravity; break; default: break; } default: break; } } window.clear(); engine.simulate(wind::Engine::StandardDuration(30.f)); for(auto& particle : particles) { particle_drawable.setPosition(particle->position.x, particle->position.y); window.draw(particle_drawable); } window.display(); } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreD3D9RenderSystem.h" #include "OgreD3D9HardwareBufferManager.h" #include "OgreD3D9HardwareVertexBuffer.h" #include "OgreD3D9HardwareIndexBuffer.h" #include "OgreD3D9VertexDeclaration.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreException.h" namespace Ogre { //----------------------------------------------------------------------- D3D9HardwareBufferManagerBase::D3D9HardwareBufferManagerBase() { } //----------------------------------------------------------------------- D3D9HardwareBufferManagerBase::~D3D9HardwareBufferManagerBase() { destroyAllDeclarations(); destroyAllBindings(); } //----------------------------------------------------------------------- HardwareVertexBufferSharedPtr D3D9HardwareBufferManagerBase:: createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) { assert (numVerts > 0); #if OGRE_D3D_MANAGE_BUFFERS // Override shadow buffer setting; managed buffers are automatically // backed by system memory // Don't override shadow buffer if discardable, since then we use // unmanaged buffers for speed (avoids write-through overhead) // Don't override if we use directX9EX, since then we don't have managed // pool. And creating non-write only default pool causes a performance warning. if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) && !D3D9RenderSystem::isDirectX9Ex()) { useShadowBuffer = false; // Also drop any WRITE_ONLY so we can read direct if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_DYNAMIC; } else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_STATIC; } } #endif D3D9HardwareVertexBuffer* vbuf = OGRE_NEW D3D9HardwareVertexBuffer( this, vertexSize, numVerts, usage, false, useShadowBuffer); { OGRE_LOCK_MUTEX(mVertexBuffersMutex); mVertexBuffers.insert(vbuf); } return HardwareVertexBufferSharedPtr(vbuf); } //----------------------------------------------------------------------- HardwareIndexBufferSharedPtr D3D9HardwareBufferManagerBase:: createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) { assert (numIndexes > 0); #if OGRE_D3D_MANAGE_BUFFERS // Override shadow buffer setting; managed buffers are automatically // backed by system memory // Don't override shadow buffer if discardable, since then we use // unmanaged buffers for speed (avoids write-through overhead) // Don't override if we use directX9EX, since then we don't have managed // pool. And creating non-write only default pool causes a performance warning. if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) && !D3D9RenderSystem::isDirectX9Ex()) { useShadowBuffer = false; // Also drop any WRITE_ONLY so we can read direct if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_DYNAMIC; } else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_STATIC; } } #endif D3D9HardwareIndexBuffer* idx = OGRE_NEW D3D9HardwareIndexBuffer( this, itype, numIndexes, usage, false, useShadowBuffer); { OGRE_LOCK_MUTEX(mIndexBuffersMutex); mIndexBuffers.insert(idx); } return HardwareIndexBufferSharedPtr(idx); } //----------------------------------------------------------------------- RenderToVertexBufferSharedPtr D3D9HardwareBufferManagerBase::createRenderToVertexBuffer() { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Direct3D9 does not support render to vertex buffer objects", "D3D9HardwareBufferManagerBase::createRenderToVertexBuffer"); } //--------------------------------------------------------------------- HardwareUniformBufferSharedPtr D3D9HardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Uniform buffer not supported in Direct3D 9 RenderSystem.", "D3D9HardwareBufferManagerBase::createUniformBuffer"); } //----------------------------------------------------------------------- HardwareCounterBufferSharedPtr D3D9HardwareBufferManagerBase::createCounterBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3D9 does not support atomic counter buffers", "D3D9HardwareBufferManagerBase::createCounterBuffer"); } //----------------------------------------------------------------------- VertexDeclaration* D3D9HardwareBufferManagerBase::createVertexDeclarationImpl(void) { return OGRE_NEW D3D9VertexDeclaration(); } //----------------------------------------------------------------------- void D3D9HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl) { OGRE_DELETE decl; } } <commit_msg>Fixed: Index & vertex buffer performance issue in Direct3D9Ex<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreD3D9RenderSystem.h" #include "OgreD3D9HardwareBufferManager.h" #include "OgreD3D9HardwareVertexBuffer.h" #include "OgreD3D9HardwareIndexBuffer.h" #include "OgreD3D9VertexDeclaration.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreException.h" namespace Ogre { //----------------------------------------------------------------------- D3D9HardwareBufferManagerBase::D3D9HardwareBufferManagerBase() { } //----------------------------------------------------------------------- D3D9HardwareBufferManagerBase::~D3D9HardwareBufferManagerBase() { destroyAllDeclarations(); destroyAllBindings(); } //----------------------------------------------------------------------- HardwareVertexBufferSharedPtr D3D9HardwareBufferManagerBase:: createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) { assert (numVerts > 0); #if OGRE_D3D_MANAGE_BUFFERS // Override shadow buffer setting; managed buffers are automatically // backed by system memory // Don't override shadow buffer if discardable, since then we use // unmanaged buffers for speed (avoids write-through overhead) // Don't override if we use directX9EX, since then we don't have managed // pool. And creating non-write only default pool causes a performance warning. if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) && !D3D9RenderSystem::isDirectX9Ex()) { useShadowBuffer = false; // Also drop any WRITE_ONLY so we can read direct if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_DYNAMIC; } else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_STATIC; } } //If we have write only buffers in DirectX9Ex we will turn on the discardable flag. //Otherwise Ogre will operates in far less framerate if (D3D9RenderSystem::isDirectX9Ex() && (usage & HardwareBuffer::HBU_WRITE_ONLY)) { usage = (HardwareBuffer::Usage) ((unsigned int)usage | (unsigned int)HardwareBuffer::HBU_DISCARDABLE); } #endif D3D9HardwareVertexBuffer* vbuf = OGRE_NEW D3D9HardwareVertexBuffer( this, vertexSize, numVerts, usage, false, useShadowBuffer); { OGRE_LOCK_MUTEX(mVertexBuffersMutex); mVertexBuffers.insert(vbuf); } return HardwareVertexBufferSharedPtr(vbuf); } //----------------------------------------------------------------------- HardwareIndexBufferSharedPtr D3D9HardwareBufferManagerBase:: createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) { assert (numIndexes > 0); #if OGRE_D3D_MANAGE_BUFFERS // Override shadow buffer setting; managed buffers are automatically // backed by system memory // Don't override shadow buffer if discardable, since then we use // unmanaged buffers for speed (avoids write-through overhead) // Don't override if we use directX9EX, since then we don't have managed // pool. And creating non-write only default pool causes a performance warning. if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) && !D3D9RenderSystem::isDirectX9Ex()) { useShadowBuffer = false; // Also drop any WRITE_ONLY so we can read direct if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_DYNAMIC; } else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY) { usage = HardwareBuffer::HBU_STATIC; } } //If we have write only buffers in DirectX9Ex we will turn on the discardable flag. //Otherwise Ogre will operates in far less framerate if (D3D9RenderSystem::isDirectX9Ex() && (usage & HardwareBuffer::HBU_WRITE_ONLY)) { usage = (HardwareBuffer::Usage) ((unsigned int)usage | (unsigned int)HardwareBuffer::HBU_DISCARDABLE); } #endif D3D9HardwareIndexBuffer* idx = OGRE_NEW D3D9HardwareIndexBuffer( this, itype, numIndexes, usage, false, useShadowBuffer); { OGRE_LOCK_MUTEX(mIndexBuffersMutex); mIndexBuffers.insert(idx); } return HardwareIndexBufferSharedPtr(idx); } //----------------------------------------------------------------------- RenderToVertexBufferSharedPtr D3D9HardwareBufferManagerBase::createRenderToVertexBuffer() { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Direct3D9 does not support render to vertex buffer objects", "D3D9HardwareBufferManagerBase::createRenderToVertexBuffer"); } //--------------------------------------------------------------------- HardwareUniformBufferSharedPtr D3D9HardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Uniform buffer not supported in Direct3D 9 RenderSystem.", "D3D9HardwareBufferManagerBase::createUniformBuffer"); } //----------------------------------------------------------------------- HardwareCounterBufferSharedPtr D3D9HardwareBufferManagerBase::createCounterBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3D9 does not support atomic counter buffers", "D3D9HardwareBufferManagerBase::createCounterBuffer"); } //----------------------------------------------------------------------- VertexDeclaration* D3D9HardwareBufferManagerBase::createVertexDeclarationImpl(void) { return OGRE_NEW D3D9VertexDeclaration(); } //----------------------------------------------------------------------- void D3D9HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl) { OGRE_DELETE decl; } } <|endoftext|>
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_ENTITY_HPP #define ROSETTASTONE_ENTITY_HPP #include <Rosetta/Cards/Card.hpp> #include <Rosetta/Enchants/AuraEffects.hpp> #include <map> namespace RosettaStone { class Card; class Game; class Player; //! //! \brief Abstract entity structure that stores card data. //! //! This structure is base structure of all data-holding/action-performing/ //! visible or invisible objects in a RosettaStone. //! An entity is defined as a collection of properties, called GameTags. //! class Entity { public: //! Default constructor. Entity() = default; //! Constructs entity with given \p _owner and \p _card. //! \param _owner An owner of the card. //! \param _card A reference to the card. Entity(Player& _owner, Card& _card); //! Destructor. virtual ~Entity(); //! Copy constructor. Entity(const Entity& ent); //! Move constructor. Entity(Entity&& ent) noexcept; //! Copy assignment operator. Entity& operator=(const Entity& ent); //! Move assignment operator. Entity& operator=(Entity&& ent) noexcept; //! Returns the owner of character. //! \return The owner of character. Player& GetOwner() const; //! Sets the owner of character. //! \param owner The owner of character. void SetOwner(Player& owner); //! Returns the value of game tag. //! \param tag The game tag of card. //! \return The value of game tag. int GetGameTag(GameTag tag) const; //! Sets game tag to the card. //! \param tag The game tag to indicate ability or condition. //! \param value The value to set for game tag. virtual void SetGameTag(GameTag tag, int value); //! Returns the value of cost. //! \return The value of cost. int GetCost() const; //! Sets the value of cost. //! \param cost The value of cost. void SetCost(int cost); //! Destroys character. virtual void Destroy(); //! Creates entity from the card. //! \param player A player to get the card. //! \param card A card to draw. //! \return A pointer to entity that is allocated dynamically. static Entity* GetFromCard(Player& player, Card&& card); Card card; AuraEffects* auraEffects = nullptr; Aura* onGoingEffect = nullptr; std::size_t id = 0; std::size_t orderOfPlay = 0; bool isDestroyed = false; protected: Player* m_owner = nullptr; std::map<GameTag, int> m_gameTags; private: //! Releases dynamic allocated resources. void FreeMemory(); }; } // namespace RosettaStone #endif // ROSETTASTONE_ENTITY_HPP <commit_msg>feat(card-impl): Add variables 'activatedTrigger', 'appliedEnchantments'<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_ENTITY_HPP #define ROSETTASTONE_ENTITY_HPP #include <Rosetta/Cards/Card.hpp> #include <Rosetta/Enchants/AuraEffects.hpp> #include <map> namespace RosettaStone { class Card; class Enchantment; class Game; class Player; //! //! \brief Abstract entity structure that stores card data. //! //! This structure is base structure of all data-holding/action-performing/ //! visible or invisible objects in a RosettaStone. //! An entity is defined as a collection of properties, called GameTags. //! class Entity { public: //! Default constructor. Entity() = default; //! Constructs entity with given \p _owner and \p _card. //! \param _owner An owner of the card. //! \param _card A reference to the card. Entity(Player& _owner, Card& _card); //! Destructor. virtual ~Entity(); //! Copy constructor. Entity(const Entity& ent); //! Move constructor. Entity(Entity&& ent) noexcept; //! Copy assignment operator. Entity& operator=(const Entity& ent); //! Move assignment operator. Entity& operator=(Entity&& ent) noexcept; //! Returns the owner of character. //! \return The owner of character. Player& GetOwner() const; //! Sets the owner of character. //! \param owner The owner of character. void SetOwner(Player& owner); //! Returns the value of game tag. //! \param tag The game tag of card. //! \return The value of game tag. int GetGameTag(GameTag tag) const; //! Sets game tag to the card. //! \param tag The game tag to indicate ability or condition. //! \param value The value to set for game tag. virtual void SetGameTag(GameTag tag, int value); //! Returns the value of cost. //! \return The value of cost. int GetCost() const; //! Sets the value of cost. //! \param cost The value of cost. void SetCost(int cost); //! Destroys character. virtual void Destroy(); //! Creates entity from the card. //! \param player A player to get the card. //! \param card A card to draw. //! \return A pointer to entity that is allocated dynamically. static Entity* GetFromCard(Player& player, Card&& card); Card card; AuraEffects* auraEffects = nullptr; Aura* onGoingEffect = nullptr; Trigger* activatedTrigger = nullptr; std::vector<Enchantment*> appliedEnchantments; std::size_t id = 0; std::size_t orderOfPlay = 0; bool isDestroyed = false; protected: Player* m_owner = nullptr; std::map<GameTag, int> m_gameTags; private: //! Releases dynamic allocated resources. void FreeMemory(); }; } // namespace RosettaStone #endif // ROSETTASTONE_ENTITY_HPP <|endoftext|>
<commit_before>#include <examples/zurg/slave/Heartbeat.h> #include <examples/zurg/slave/SlaveConfig.h> #include <examples/zurg/proto/master.pb.h> #include <muduo/protorpc2/rpc2.pb.h> #include <muduo/base/FileUtil.h> #include <muduo/base/Logging.h> #include <muduo/base/ProcessInfo.h> #include <muduo/base/Timestamp.h> #include <muduo/net/EventLoop.h> namespace zurg { void ignoreCallback(const EmptyPtr&) { } // unique_ptr is better typedef boost::shared_ptr<muduo::FileUtil::SmallFile> SmallFilePtr; class ProcFs : boost::noncopyable { public: typedef std::map<muduo::StringPiece, SmallFilePtr> FileMap; // char* to save construction of string. int readTo(const char* filename, std::string* out) { FileMap::iterator it = files_.find(filename); if (it == files_.end()) { SmallFilePtr ptr(new muduo::FileUtil::SmallFile(filename)); it = files_.insert(std::make_pair(filename, ptr)).first; } assert (it != files_.end()); int size = 0; int err = it->second->readToBuffer(&size); LOG_TRACE << filename << " " << err << " " << size; if (size > 0) { out->assign(it->second->buffer(), size); } return err; } private: FileMap files_; }; } extern const char* slave_version; using namespace zurg; using namespace muduo; using namespace muduo::net; Heartbeat::Heartbeat(muduo::net::EventLoop* loop, const SlaveConfig& config, MasterService_Stub* stub) : loop_(loop), name_(config.name_), port_(config.listenPort_), stub_(stub), procFs_(new ProcFs), beating_(false) { loop_->runEvery(config.heartbeatInterval_, boost::bind(&Heartbeat::onTimer, this)); } Heartbeat::~Heartbeat() { } void Heartbeat::start() { beating_ = true; beat(true); } void Heartbeat::stop() { beating_ = false; } void Heartbeat::onTimer() { if (beating_) { beat(false); } } #define FILL_HB(PROC_FILE, FIELD) \ if (procFs_->readTo(PROC_FILE, hb.mutable_##FIELD()) != 0) \ hb.clear_##FIELD(); void Heartbeat::beat(bool showStatic) { LOG_DEBUG << (showStatic ? "full" : ""); SlaveHeartbeat hb; hb.set_slave_name(name_); if (showStatic) { hb.set_host_name(ProcessInfo::hostname().c_str()); if (port_ > 0) { hb.set_listen_port(port_); } hb.set_slave_pid(ProcessInfo::pid()); hb.set_start_time_us(ProcessInfo::startTime().microSecondsSinceEpoch()); hb.set_slave_version(slave_version); FILL_HB("/proc/cpuinfo", cpuinfo); FILL_HB("/proc/version", version); FILL_HB("/etc/mtab", etc_mtab); } hb.set_send_time_us(Timestamp::now().microSecondsSinceEpoch()); FILL_HB("/proc/meminfo", meminfo); FILL_HB("/proc/stat", proc_stat); FILL_HB("/proc/loadavg", loadavg); FILL_HB("/proc/diskstats", diskstats); FILL_HB("/proc/net/dev", net_dev); FILL_HB("/proc/net/tcp", net_tcp); stub_->slaveHeartbeat(hb, ignoreCallback); } <commit_msg>strip heartbeat.<commit_after>#include <examples/zurg/slave/Heartbeat.h> #include <examples/zurg/slave/SlaveConfig.h> #include <examples/zurg/proto/master.pb.h> #include <muduo/protorpc2/rpc2.pb.h> #include <muduo/base/FileUtil.h> #include <muduo/base/Logging.h> #include <muduo/base/ProcessInfo.h> #include <muduo/base/Timestamp.h> #include <muduo/net/EventLoop.h> namespace zurg { void ignoreCallback(const EmptyPtr&) { } // unique_ptr is better typedef boost::shared_ptr<muduo::FileUtil::SmallFile> SmallFilePtr; class ProcFs : boost::noncopyable { public: typedef std::map<muduo::StringPiece, SmallFilePtr> FileMap; // char* to save construction of string. int readTo(const char* filename, std::string* out) { FileMap::iterator it = files_.find(filename); if (it == files_.end()) { SmallFilePtr ptr(new muduo::FileUtil::SmallFile(filename)); it = files_.insert(std::make_pair(filename, ptr)).first; } assert (it != files_.end()); int size = 0; int err = it->second->readToBuffer(&size); LOG_TRACE << filename << " " << err << " " << size; if (size > 0) { out->assign(it->second->buffer(), size); } return err; } private: FileMap files_; }; void strip_cpuinfo(std::string* cpuinfo) { // FIXME: } void strip_diskstats(std::string* diskstats) { std::string result; result.reserve(diskstats->size()); muduo::StringPiece zeros(" 0 0 0 0 0 0 0 0 0 0 0\n"); const char* p = diskstats->c_str(); const char* nl = NULL; while ( (nl = ::strchr(p, '\n')) != NULL) { int pos = static_cast<int>(nl - p + 1); muduo::StringPiece line(p, pos); if (line.size() > zeros.size()) { muduo::StringPiece end(line.data() + line.size()-zeros.size(), zeros.size()); if (end != zeros) { result.append(line.data(), line.size()); } } p += pos; } assert(p == &*diskstats->end()); diskstats->swap(result); } struct AreBothSpaces { bool operator()(char x, char y) const { return x == ' ' && y == ' '; } }; void strip_meminfo(std::string* meminfo) { std::string::iterator it = std::unique(meminfo->begin(), meminfo->end(), AreBothSpaces()); meminfo->erase(it, meminfo->end()); } void strip_stat(std::string* proc_stat) { const char* intr = ::strstr(proc_stat->c_str(), "\nintr "); if (intr != NULL) { const char* nl = ::strchr(intr + 1, '\n'); assert(nl != NULL); muduo::StringPiece line(intr+1, static_cast<int>(nl-intr-1)); const char* p = nl; while (p[-1] == '0' && p[-2] == ' ') { p -= 2; } ++p; proc_stat->erase(p - proc_stat->c_str(), nl-p); } } } extern const char* slave_version; using namespace zurg; using namespace muduo; using namespace muduo::net; Heartbeat::Heartbeat(muduo::net::EventLoop* loop, const SlaveConfig& config, MasterService_Stub* stub) : loop_(loop), name_(config.name_), port_(config.listenPort_), stub_(stub), procFs_(new ProcFs), beating_(false) { loop_->runEvery(config.heartbeatInterval_, boost::bind(&Heartbeat::onTimer, this)); } Heartbeat::~Heartbeat() { } void Heartbeat::start() { beating_ = true; beat(true); } void Heartbeat::stop() { beating_ = false; } void Heartbeat::onTimer() { if (beating_) { beat(false); } } #define FILL_HB(PROC_FILE, FIELD) \ if (procFs_->readTo(PROC_FILE, hb.mutable_##FIELD()) != 0) \ hb.clear_##FIELD(); void Heartbeat::beat(bool showStatic) { LOG_DEBUG << (showStatic ? "full" : ""); SlaveHeartbeat hb; hb.set_slave_name(name_); if (showStatic) { hb.set_host_name(ProcessInfo::hostname().c_str()); if (port_ > 0) { hb.set_listen_port(port_); } hb.set_slave_pid(ProcessInfo::pid()); hb.set_start_time_us(ProcessInfo::startTime().microSecondsSinceEpoch()); hb.set_slave_version(slave_version); FILL_HB("/proc/cpuinfo", cpuinfo); FILL_HB("/proc/version", version); FILL_HB("/etc/mtab", etc_mtab); strip_cpuinfo(hb.mutable_cpuinfo()); } hb.set_send_time_us(Timestamp::now().microSecondsSinceEpoch()); FILL_HB("/proc/meminfo", meminfo); FILL_HB("/proc/stat", proc_stat); FILL_HB("/proc/loadavg", loadavg); FILL_HB("/proc/diskstats", diskstats); FILL_HB("/proc/net/dev", net_dev); FILL_HB("/proc/net/tcp", net_tcp); strip_diskstats(hb.mutable_diskstats()); strip_meminfo(hb.mutable_meminfo()); strip_stat(hb.mutable_proc_stat()); stub_->slaveHeartbeat(hb, ignoreCallback); } <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /**************************************************************************************/ #include "vl/VisualizationLibrary.hpp" #include "vl/Light.hpp" #include "vl/GLSL.hpp" class App_GLSL_Bumpmapping: public BaseDemo { public: App_GLSL_Bumpmapping() { } void initEvent() { if (!GLEW_ARB_shading_language_100) { vl::Log::error("GL_ARB_shading_language_100 not supported.\n"); vl::Time::sleep(3000); openglContext()->quitApplication(); return; } BaseDemo::initEvent(); // generate torus, with normals and uv coords vl::ref<vl::Geometry> model = vlut::makeTorus( vl::vec3(0,0,0), 10, 2, 25, 25, 2.0f ); vl::ref<vl::Light> light = new vl::Light(0); vl::ref<vl::Effect> effect = new vl::Effect; effect->shader()->setRenderState( light.get() ); effect->shader()->enable(vl::EN_LIGHTING); effect->shader()->enable(vl::EN_DEPTH_TEST); effect->shader()->enable(vl::EN_CULL_FACE); // effect->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE); torus = sceneManager()->tree()->addActor( model.get(), effect.get(), NULL ); vl::ref<vl::Texture> texture0 = new vl::Texture; texture0->setupTexture2D("images/normalmap.jpg"); effect->shader()->gocTextureUnit(0)->setTexture(texture0.get()); texture0->getTexParameter()->setAnisotropy(16.0); texture0->getTexParameter()->setMagFilter(vl::TPF_LINEAR); texture0->getTexParameter()->setMinFilter(vl::TPF_LINEAR_MIPMAP_LINEAR); glsl = effect->shader()->gocGLSLProgram(); glsl->attachShader( new vl::GLSLVertexShader("/glsl/bumpmap.vs") ); glsl->attachShader( new vl::GLSLFragmentShader("/glsl/bumpmap.fs") ); vl::ref<vl::Uniform> sampler0 = new vl::Uniform; sampler0->setUniform(0); sampler0->setName("sampler0"); glsl->setUniform( sampler0.get() ); light_obj_space_pos = new vl::Uniform; light_obj_space_pos->setName("light_obj_space_pos"); glsl->setUniform( light_obj_space_pos.get() ); vl::ref<vl::ArrayFVec3> tangent = new vl::ArrayFVec3; vl::ref<vl::ArrayFVec3> bitangent = new vl::ArrayFVec3; tangent->resize( model->vertexArray()->size() ); bitangent->resize( model->vertexArray()->size() ); VL_CHECK( model->primitives()->at(0)->primitiveType() == vl::PT_QUADS ); // tessellate torus quads std::vector<unsigned int> index_buffer; index_buffer.resize( model->primitives()->at(0)->triangleCount() * 3 ); unsigned int* triangle = &index_buffer.front(); for( size_t i=0; i<model->primitives()->at(0)->indexCount(); i+=4 ) { size_t a = model->primitives()->at(0)->index(i+0); size_t b = model->primitives()->at(0)->index(i+1); size_t c = model->primitives()->at(0)->index(i+2); size_t d = model->primitives()->at(0)->index(i+3); VL_CHECK(a < model->vertexArray()->size()); VL_CHECK(b < model->vertexArray()->size()); VL_CHECK(c < model->vertexArray()->size()); VL_CHECK(d < model->vertexArray()->size()); triangle[0] = a; triangle[1] = b; triangle[2] = c; triangle += 3; triangle[0] = c; triangle[1] = d; triangle[2] = a; triangle += 3; } ComputeTangentSpace( model->vertexArray()->size(), (vl::fvec3*)model->vertexArray()->ptr(), (vl::fvec3*)model->normalArray()->ptr(), (vl::fvec2*)model->texCoordArray(0)->ptr(), model->primitives()->at(0)->triangleCount(), &index_buffer.front(), tangent->begin(), bitangent->begin() ); glsl->linkProgram(); int tangent_idx = glsl->getAttribLocation("tangent"); int bitangent_idx = glsl->getAttribLocation("bitangent"); model->setVertexAttributeArray(tangent_idx, false, false, tangent.get() ); model->setVertexAttributeArray(bitangent_idx, false, false, bitangent.get() ); /* // visualize tangent space vl::ref<vl::ArrayFVec3> ntb_verts = new vl::ArrayFVec3; ntb_verts->resize( model->vertexArray()->size() * 6 ); vl::ref<vl::ArrayFVec4> ntb_cols = new vl::ArrayFVec4; ntb_cols->resize( model->vertexArray()->size() * 6 ); vl::fvec3* verts = (vl::fvec3*)model->vertexArray()->ptr(); vl::fvec3* norms = (vl::fvec3*)model->normalArray()->ptr(); float tick_size = 0.5f; for( size_t i=0; i<model->vertexArray()->size(); ++i ) { (*ntb_verts)[i*6 + 0] = verts[i]; (*ntb_verts)[i*6 + 1] = verts[i] + norms[i] * tick_size; (*ntb_verts)[i*6 + 2] = verts[i]; (*ntb_verts)[i*6 + 3] = verts[i] + (*tangent)[i] * tick_size; (*ntb_verts)[i*6 + 4] = verts[i]; (*ntb_verts)[i*6 + 5] = verts[i] + (*bitangent)[i] * tick_size; (*ntb_cols)[i*6 + 0] = vlut::red; (*ntb_cols)[i*6 + 1] = vlut::red; (*ntb_cols)[i*6 + 2] = vlut::green; (*ntb_cols)[i*6 + 3] = vlut::green; (*ntb_cols)[i*6 + 4] = vlut::blue; (*ntb_cols)[i*6 + 5] = vlut::blue; } vl::ref<vl::Geometry> NTBGeom = new vl::Geometry; NTBGeom->setVertexArray( ntb_verts.get() ); NTBGeom->setColorArray( ntb_cols.get() ); NTBGeom->primitives()->push_back( new vl::DrawArrays(vl::PT_LINES, 0, ntb_verts->size() ) ); sceneManager()->tree()->addActor( NTBGeom.get(), effect.get(), NULL ); */ // ... testa con oggetto che ruota per i fatti suoi ... // ... ripulisci implementazione: passa direttamente la matrice buona. // FIXME //MAKE UTILITY CLASSES: //+ Compute Tangent Space //+ Tangent Space Geometry Visualizer (vert, norm, tang, btang, norm_col, tang_col, btang_col, width). // +--> Exposes the effect used and the vertex and color buffer and primitive lump generated. //+ Index Buffer Tessellator -> returns a triangle list UINT out of any primitive type. // +--> Convert to triangles utility function. //+ Generate & Distribute your bump map. //- why do we need to negate the bitangent? =|> ask OpenGL.org //- implementa normalization cubemap //- GLSL shaders sono in uno stato da fare schifo, non li dovresti ridistribuire cosi //- 3DS support fix //- Primitives: texture coordinates generation OFF by default. } // Based on: // Lengyel, Eric. Computing Tangent Space Basis Vectors for an Arbitrary Mesh. Terathon Software 3D Graphics Library, 2001. // http://www.terathon.com/code/tangent.html void ComputeTangentSpace( size_t vert_count, const vl::fvec3 *vertex, const vl::fvec3* normal, const vl::fvec2 *texcoord, size_t tri_count, const unsigned int *triangles, vl::fvec3 *tangent, vl::fvec3 *bitangent ) { std::vector<vl::fvec3> tan1; std::vector<vl::fvec3> tan2; tan1.resize(vert_count); tan2.resize(vert_count); for ( size_t a = 0; a < tri_count; ++a, triangles+=3 ) { unsigned int i1 = triangles[0]; unsigned int i2 = triangles[1]; unsigned int i3 = triangles[2]; VL_CHECK(i1 < vert_count ); VL_CHECK(i2 < vert_count ); VL_CHECK(i3 < vert_count ); const vl::fvec3& v1 = vertex[i1]; const vl::fvec3& v2 = vertex[i2]; const vl::fvec3& v3 = vertex[i3]; const vl::fvec2& w1 = texcoord[i1]; const vl::fvec2& w2 = texcoord[i2]; const vl::fvec2& w3 = texcoord[i3]; float x1 = v2.x() - v1.x(); float x2 = v3.x() - v1.x(); float y1 = v2.y() - v1.y(); float y2 = v3.y() - v1.y(); float z1 = v2.z() - v1.z(); float z2 = v3.z() - v1.z(); float s1 = w2.x() - w1.x(); float s2 = w3.x() - w1.x(); float t1 = w2.y() - w1.y(); float t2 = w3.y() - w1.y(); float r = 1.0F / (s1 * t2 - s2 * t1); vl::fvec3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); vl::fvec3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for ( size_t a = 0; a < vert_count; a++) { const vl::fvec3& n = normal[a]; const vl::fvec3& t = tan1[a]; // Gram-Schmidt orthogonalize tangent[a] = (t - n * vl::dot(n, t)).normalize(); // fixme??? // Calculate handedness float w = (vl::dot(vl::cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F; bitangent[a] = vl::cross( n, tangent[a] ) * w; } } void run() { vl::fvec3 camera_pos = vl::VisualizationLibrary::rendering()->as<vl::Rendering>()->camera()->inverseViewMatrix().getT(); vl::mat4 obj_mat; if (torus->transform()) obj_mat = torus->transform()->worldMatrix(); obj_mat.invert(); vl::fvec3 camera_pos_obj_space = obj_mat * camera_pos; // light_obj_space_pos->setUniform( /*camera_pos_obj_space*/ vl::vec3(100,0,0) ); light_obj_space_pos->setUniform( camera_pos_obj_space ); // printf("camera_pos = %f %f %f\n", camera_pos.x(), camera_pos.y(), camera_pos.z() ); // printf("camera_pos_obj_space = %f %f %f\n", camera_pos_obj_space.x(), camera_pos_obj_space.y(), camera_pos_obj_space.z() ); } void shutdown() {} protected: vl::ref<vl::GLSLProgram> glsl; vl::ref<vl::Uniform> light_obj_space_pos; vl::ref<vl::Actor> torus; }; // Have fun! <commit_msg>bitangent computed in vertex shader<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /**************************************************************************************/ #include "vl/VisualizationLibrary.hpp" #include "vl/Light.hpp" #include "vl/GLSL.hpp" class App_GLSL_Bumpmapping: public BaseDemo { public: App_GLSL_Bumpmapping() { } void initEvent() { if (!GLEW_ARB_shading_language_100) { vl::Log::error("GL_ARB_shading_language_100 not supported.\n"); vl::Time::sleep(3000); openglContext()->quitApplication(); return; } BaseDemo::initEvent(); // generate torus, with normals and uv coords vl::ref<vl::Geometry> model = vlut::makeTorus( vl::vec3(0,0,0), 10, 2, 25, 25, 2.0f ); vl::ref<vl::Light> light = new vl::Light(0); vl::ref<vl::Effect> effect = new vl::Effect; effect->shader()->setRenderState( light.get() ); effect->shader()->enable(vl::EN_LIGHTING); effect->shader()->enable(vl::EN_DEPTH_TEST); effect->shader()->enable(vl::EN_CULL_FACE); // effect->shader()->gocPolygonMode()->set(vl::PM_LINE, vl::PM_LINE); torus = sceneManager()->tree()->addActor( model.get(), effect.get(), NULL ); vl::ref<vl::Texture> texture0 = new vl::Texture; texture0->setupTexture2D("images/normalmap.jpg"); effect->shader()->gocTextureUnit(0)->setTexture(texture0.get()); texture0->getTexParameter()->setAnisotropy(16.0); texture0->getTexParameter()->setMagFilter(vl::TPF_LINEAR); texture0->getTexParameter()->setMinFilter(vl::TPF_LINEAR_MIPMAP_LINEAR); glsl = effect->shader()->gocGLSLProgram(); glsl->attachShader( new vl::GLSLVertexShader("/glsl/bumpmap.vs") ); glsl->attachShader( new vl::GLSLFragmentShader("/glsl/bumpmap.fs") ); vl::ref<vl::Uniform> sampler0 = new vl::Uniform; sampler0->setUniform(0); sampler0->setName("sampler0"); glsl->setUniform( sampler0.get() ); light_obj_space_pos = new vl::Uniform; light_obj_space_pos->setName("light_obj_space_pos"); glsl->setUniform( light_obj_space_pos.get() ); vl::ref<vl::ArrayFVec3> tangent = new vl::ArrayFVec3; // vl::ref<vl::ArrayFVec3> bitangent = new vl::ArrayFVec3; tangent->resize( model->vertexArray()->size() ); // bitangent->resize( model->vertexArray()->size() ); VL_CHECK( model->primitives()->at(0)->primitiveType() == vl::PT_QUADS ); // tessellate torus quads std::vector<unsigned int> index_buffer; index_buffer.resize( model->primitives()->at(0)->triangleCount() * 3 ); unsigned int* triangle = &index_buffer.front(); for( size_t i=0; i<model->primitives()->at(0)->indexCount(); i+=4 ) { size_t a = model->primitives()->at(0)->index(i+0); size_t b = model->primitives()->at(0)->index(i+1); size_t c = model->primitives()->at(0)->index(i+2); size_t d = model->primitives()->at(0)->index(i+3); VL_CHECK(a < model->vertexArray()->size()); VL_CHECK(b < model->vertexArray()->size()); VL_CHECK(c < model->vertexArray()->size()); VL_CHECK(d < model->vertexArray()->size()); triangle[0] = a; triangle[1] = b; triangle[2] = c; triangle += 3; triangle[0] = c; triangle[1] = d; triangle[2] = a; triangle += 3; } computeTangentSpace( model->vertexArray()->size(), (vl::fvec3*)model->vertexArray()->ptr(), (vl::fvec3*)model->normalArray()->ptr(), (vl::fvec2*)model->texCoordArray(0)->ptr(), model->primitives()->at(0)->triangleCount(), &index_buffer.front(), tangent->begin(), NULL/*bitangent->begin()*/ ); glsl->linkProgram(); int tangent_idx = glsl->getAttribLocation("tangent"); // int bitangent_idx = glsl->getAttribLocation("bitangent"); model->setVertexAttributeArray(tangent_idx, false, false, tangent.get() ); // model->setVertexAttributeArray(bitangent_idx, false, false, bitangent.get() ); /* // visualize tangent space vl::ref<vl::ArrayFVec3> ntb_verts = new vl::ArrayFVec3; ntb_verts->resize( model->vertexArray()->size() * 6 ); vl::ref<vl::ArrayFVec4> ntb_cols = new vl::ArrayFVec4; ntb_cols->resize( model->vertexArray()->size() * 6 ); vl::fvec3* verts = (vl::fvec3*)model->vertexArray()->ptr(); vl::fvec3* norms = (vl::fvec3*)model->normalArray()->ptr(); float tick_size = 0.5f; for( size_t i=0; i<model->vertexArray()->size(); ++i ) { (*ntb_verts)[i*6 + 0] = verts[i]; (*ntb_verts)[i*6 + 1] = verts[i] + norms[i] * tick_size; (*ntb_verts)[i*6 + 2] = verts[i]; (*ntb_verts)[i*6 + 3] = verts[i] + (*tangent)[i] * tick_size; (*ntb_verts)[i*6 + 4] = verts[i]; (*ntb_verts)[i*6 + 5] = verts[i] + (*bitangent)[i] * tick_size; (*ntb_cols)[i*6 + 0] = vlut::red; (*ntb_cols)[i*6 + 1] = vlut::red; (*ntb_cols)[i*6 + 2] = vlut::green; (*ntb_cols)[i*6 + 3] = vlut::green; (*ntb_cols)[i*6 + 4] = vlut::blue; (*ntb_cols)[i*6 + 5] = vlut::blue; } vl::ref<vl::Geometry> NTBGeom = new vl::Geometry; NTBGeom->setVertexArray( ntb_verts.get() ); NTBGeom->setColorArray( ntb_cols.get() ); NTBGeom->primitives()->push_back( new vl::DrawArrays(vl::PT_LINES, 0, ntb_verts->size() ) ); sceneManager()->tree()->addActor( NTBGeom.get(), effect.get(), NULL ); */ // ... testa con oggetto che ruota per i fatti suoi ... // ... ripulisci implementazione: passa direttamente la matrice buona. // FIXME //MAKE UTILITY CLASSES: //+ Compute Tangent Space //+ Tangent Space Geometry Visualizer (vert, norm, tang, btang, norm_col, tang_col, btang_col, width). // +--> Exposes the effect used and the vertex and color buffer and primitive lump generated. //+ Index Buffer Tessellator -> returns a triangle list UINT out of any primitive type. // +--> Convert to triangles utility function. //+ Generate & Distribute your bump map. //- why do we need to negate the bitangent? =|> ask OpenGL.org //- implementa normalization cubemap //- GLSL shaders sono in uno stato da fare schifo, non li dovresti ridistribuire cosi //- 3DS support fix //- Primitives: texture coordinates generation OFF by default. } // Based on: // Lengyel, Eric. Computing Tangent Space Basis Vectors for an Arbitrary Mesh. Terathon Software 3D Graphics Library, 2001. // http://www.terathon.com/code/tangent.html void computeTangentSpace( size_t vert_count, const vl::fvec3 *vertex, const vl::fvec3* normal, const vl::fvec2 *texcoord, size_t tri_count, const unsigned int *triangles, vl::fvec3 *tangent, vl::fvec3 *bitangent ) { std::vector<vl::fvec3> tan1; std::vector<vl::fvec3> tan2; tan1.resize(vert_count); tan2.resize(vert_count); for ( size_t a = 0; a < tri_count; ++a, triangles+=3 ) { unsigned int i1 = triangles[0]; unsigned int i2 = triangles[1]; unsigned int i3 = triangles[2]; VL_CHECK(i1 < vert_count ); VL_CHECK(i2 < vert_count ); VL_CHECK(i3 < vert_count ); const vl::fvec3& v1 = vertex[i1]; const vl::fvec3& v2 = vertex[i2]; const vl::fvec3& v3 = vertex[i3]; const vl::fvec2& w1 = texcoord[i1]; const vl::fvec2& w2 = texcoord[i2]; const vl::fvec2& w3 = texcoord[i3]; float x1 = v2.x() - v1.x(); float x2 = v3.x() - v1.x(); float y1 = v2.y() - v1.y(); float y2 = v3.y() - v1.y(); float z1 = v2.z() - v1.z(); float z2 = v3.z() - v1.z(); float s1 = w2.x() - w1.x(); float s2 = w3.x() - w1.x(); float t1 = w2.y() - w1.y(); float t2 = w3.y() - w1.y(); float r = 1.0F / (s1 * t2 - s2 * t1); vl::fvec3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); vl::fvec3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for ( size_t a = 0; a < vert_count; a++) { const vl::fvec3& n = normal[a]; const vl::fvec3& t = tan1[a]; // Gram-Schmidt orthogonalize tangent[a] = (t - n * vl::dot(n, t)).normalize(); if ( bitangent ) { // Calculate handedness float w = (vl::dot(vl::cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F; bitangent[a] = vl::cross( n, tangent[a] ) * w; } } } void run() { vl::fvec3 camera_pos = vl::VisualizationLibrary::rendering()->as<vl::Rendering>()->camera()->inverseViewMatrix().getT(); vl::mat4 obj_mat; if (torus->transform()) obj_mat = torus->transform()->worldMatrix(); obj_mat.invert(); vl::fvec3 camera_pos_obj_space = obj_mat * camera_pos; // light_obj_space_pos->setUniform( /*camera_pos_obj_space*/ vl::vec3(100,0,0) ); light_obj_space_pos->setUniform( camera_pos_obj_space ); // printf("camera_pos = %f %f %f\n", camera_pos.x(), camera_pos.y(), camera_pos.z() ); // printf("camera_pos_obj_space = %f %f %f\n", camera_pos_obj_space.x(), camera_pos_obj_space.y(), camera_pos_obj_space.z() ); } void shutdown() {} protected: vl::ref<vl::GLSLProgram> glsl; vl::ref<vl::Uniform> light_obj_space_pos; vl::ref<vl::Actor> torus; }; // Have fun! <|endoftext|>
<commit_before>//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is an extremely simple version of the SimplifyCFG pass. Its sole // job is to delete LLVM basic blocks that are not reachable from the entry // node. To do this, it performs a simple depth first traversal of the CFG, // then deletes any unvisited nodes. // // Note that this pass is really a hack. In particular, the instruction // selectors for various targets should just not generate code for unreachable // blocks. Until LLVM has a more systematic way of defining instruction // selectors, however, we cannot really expect them to handle additional // complexity. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/Analysis/ProfileInfo.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class UnreachableBlockElim : public FunctionPass { virtual bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid UnreachableBlockElim() : FunctionPass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<ProfileInfo>(); } }; } char UnreachableBlockElim::ID = 0; INITIALIZE_PASS(UnreachableBlockElim, "unreachableblockelim", "Remove unreachable blocks from the CFG", false, false); FunctionPass *llvm::createUnreachableBlockEliminationPass() { return new UnreachableBlockElim(); } bool UnreachableBlockElim::runOnFunction(Function &F) { SmallPtrSet<BasicBlock*, 8> Reachable; // Mark all reachable blocks. for (df_ext_iterator<Function*, SmallPtrSet<BasicBlock*, 8> > I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<BasicBlock*> DeadBlocks; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { BasicBlock *BB = I; DeadBlocks.push_back(BB); while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); BB->getInstList().pop_front(); } for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } // Actually remove the blocks now. ProfileInfo *PI = getAnalysisIfAvailable<ProfileInfo>(); for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) { if (PI) PI->removeBlock(DeadBlocks[i]); DeadBlocks[i]->eraseFromParent(); } return DeadBlocks.size(); } namespace { class UnreachableMachineBlockElim : public MachineFunctionPass { virtual bool runOnMachineFunction(MachineFunction &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const; MachineModuleInfo *MMI; public: static char ID; // Pass identification, replacement for typeid UnreachableMachineBlockElim() : MachineFunctionPass(ID) {} }; } char UnreachableMachineBlockElim::ID = 0; INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination", "Remove unreachable machine basic blocks", false, false); char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID; void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<MachineLoopInfo>(); AU.addPreserved<MachineDominatorTree>(); MachineFunctionPass::getAnalysisUsage(AU); } bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { SmallPtrSet<MachineBasicBlock*, 8> Reachable; MMI = getAnalysisIfAvailable<MachineModuleInfo>(); MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>(); MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>(); // Mark all reachable blocks. for (df_ext_iterator<MachineFunction*, SmallPtrSet<MachineBasicBlock*, 8> > I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<MachineBasicBlock*> DeadBlocks; for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { MachineBasicBlock *BB = I; // Test for deadness. if (!Reachable.count(BB)) { DeadBlocks.push_back(BB); // Update dominator and loop info. if (MLI) MLI->removeBlock(BB); if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB); while (BB->succ_begin() != BB->succ_end()) { MachineBasicBlock* succ = *BB->succ_begin(); MachineBasicBlock::iterator start = succ->begin(); while (start != succ->end() && start->isPHI()) { for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2) if (start->getOperand(i).isMBB() && start->getOperand(i).getMBB() == BB) { start->RemoveOperand(i); start->RemoveOperand(i-1); } start++; } BB->removeSuccessor(BB->succ_begin()); } } } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); // Cleanup PHI nodes. for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { MachineBasicBlock *BB = I; // Prune unneeded PHI entries. SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(), BB->pred_end()); MachineBasicBlock::iterator phi = BB->begin(); while (phi != BB->end() && phi->isPHI()) { for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2) if (!preds.count(phi->getOperand(i).getMBB())) { phi->RemoveOperand(i); phi->RemoveOperand(i-1); } if (phi->getNumOperands() == 3) { unsigned Input = phi->getOperand(1).getReg(); unsigned Output = phi->getOperand(0).getReg(); MachineInstr* temp = phi; ++phi; temp->eraseFromParent(); if (Input != Output) F.getRegInfo().replaceRegWith(Output, Input); continue; } ++phi; } } F.RenumberBlocks(); return DeadBlocks.size(); } <commit_msg>UnreachableBlockElim could incorrectly return false when it had not modified the CFG, but HAD modified some PHI nodes. Fixes PR8174.<commit_after>//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is an extremely simple version of the SimplifyCFG pass. Its sole // job is to delete LLVM basic blocks that are not reachable from the entry // node. To do this, it performs a simple depth first traversal of the CFG, // then deletes any unvisited nodes. // // Note that this pass is really a hack. In particular, the instruction // selectors for various targets should just not generate code for unreachable // blocks. Until LLVM has a more systematic way of defining instruction // selectors, however, we cannot really expect them to handle additional // complexity. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/Analysis/ProfileInfo.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class UnreachableBlockElim : public FunctionPass { virtual bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid UnreachableBlockElim() : FunctionPass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<ProfileInfo>(); } }; } char UnreachableBlockElim::ID = 0; INITIALIZE_PASS(UnreachableBlockElim, "unreachableblockelim", "Remove unreachable blocks from the CFG", false, false); FunctionPass *llvm::createUnreachableBlockEliminationPass() { return new UnreachableBlockElim(); } bool UnreachableBlockElim::runOnFunction(Function &F) { SmallPtrSet<BasicBlock*, 8> Reachable; // Mark all reachable blocks. for (df_ext_iterator<Function*, SmallPtrSet<BasicBlock*, 8> > I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<BasicBlock*> DeadBlocks; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (!Reachable.count(I)) { BasicBlock *BB = I; DeadBlocks.push_back(BB); while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); BB->getInstList().pop_front(); } for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } // Actually remove the blocks now. ProfileInfo *PI = getAnalysisIfAvailable<ProfileInfo>(); for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) { if (PI) PI->removeBlock(DeadBlocks[i]); DeadBlocks[i]->eraseFromParent(); } return DeadBlocks.size(); } namespace { class UnreachableMachineBlockElim : public MachineFunctionPass { virtual bool runOnMachineFunction(MachineFunction &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const; MachineModuleInfo *MMI; public: static char ID; // Pass identification, replacement for typeid UnreachableMachineBlockElim() : MachineFunctionPass(ID) {} }; } char UnreachableMachineBlockElim::ID = 0; INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination", "Remove unreachable machine basic blocks", false, false); char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID; void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<MachineLoopInfo>(); AU.addPreserved<MachineDominatorTree>(); MachineFunctionPass::getAnalysisUsage(AU); } bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { SmallPtrSet<MachineBasicBlock*, 8> Reachable; bool ModifiedPHI = false; MMI = getAnalysisIfAvailable<MachineModuleInfo>(); MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>(); MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>(); // Mark all reachable blocks. for (df_ext_iterator<MachineFunction*, SmallPtrSet<MachineBasicBlock*, 8> > I = df_ext_begin(&F, Reachable), E = df_ext_end(&F, Reachable); I != E; ++I) /* Mark all reachable blocks */; // Loop over all dead blocks, remembering them and deleting all instructions // in them. std::vector<MachineBasicBlock*> DeadBlocks; for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { MachineBasicBlock *BB = I; // Test for deadness. if (!Reachable.count(BB)) { DeadBlocks.push_back(BB); // Update dominator and loop info. if (MLI) MLI->removeBlock(BB); if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB); while (BB->succ_begin() != BB->succ_end()) { MachineBasicBlock* succ = *BB->succ_begin(); MachineBasicBlock::iterator start = succ->begin(); while (start != succ->end() && start->isPHI()) { for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2) if (start->getOperand(i).isMBB() && start->getOperand(i).getMBB() == BB) { start->RemoveOperand(i); start->RemoveOperand(i-1); } start++; } BB->removeSuccessor(BB->succ_begin()); } } } // Actually remove the blocks now. for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) DeadBlocks[i]->eraseFromParent(); // Cleanup PHI nodes. for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { MachineBasicBlock *BB = I; // Prune unneeded PHI entries. SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(), BB->pred_end()); MachineBasicBlock::iterator phi = BB->begin(); while (phi != BB->end() && phi->isPHI()) { for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2) if (!preds.count(phi->getOperand(i).getMBB())) { phi->RemoveOperand(i); phi->RemoveOperand(i-1); ModifiedPHI = true; } if (phi->getNumOperands() == 3) { unsigned Input = phi->getOperand(1).getReg(); unsigned Output = phi->getOperand(0).getReg(); MachineInstr* temp = phi; ++phi; temp->eraseFromParent(); ModifiedPHI = true; if (Input != Output) F.getRegInfo().replaceRegWith(Output, Input); continue; } ++phi; } } F.RenumberBlocks(); return (DeadBlocks.size() || ModifiedPHI); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> using namespace std; template <class T> struct Node { T element; Node<T> *left, *right, *pparent; }; template <class T> class BST { private: Node<T> *root; int count; public: BST(); ~BST(); void deleteTree(Node<T> *Tree); void show(ostream&cout, const Node<T> *Tree) const; void add(const T&); bool search(const T&, Node<T> *Tree) const; void input(const string& file); void output(const string& file) const; Node<T>* MinElement(Node<T>* min); Node<T>* getroot() const; int getcount() const; Node<T>* del(Node<T>* parent, Node<T>* current, const T& val); bool delVal(const T& val); }; template <typename T> BST<T>::BST() { root = NULL; count = 0; } template <typename T> BST<T>::~BST() { deleteTree(root); } template <typename T>void BST<T>::deleteTree(Node<T> *Tree) { if (!Tree) return; if (Tree->left) { deleteTree(Tree->left); Tree->left = nullptr; } if (Tree->right) { deleteTree(Tree->right); Tree->right = nullptr; } delete Tree; } template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{ if (Tree != NULL) { cout << Tree->element << endl;; show(cout, Tree->left); show(cout, Tree->right); } } template <typename T> void BST<T>::add(const T &x) { Node<T>* daughter = new Node<T>; daughter->element = x; daughter->left = daughter->right = nullptr; Node<T>* parent = root; Node<T>* temp = root; while (temp) { parent = temp; if (x < temp->element) temp = temp->left; else temp = temp->right; } if (!parent) root = daughter; else { if (x < parent->element) parent->left = daughter; else parent->right = daughter; } count++; } template <typename T> Node<T>* BST<T>::getroot() const { return root; } template <typename T> int BST<T>::getcount() const { return count; } template <typename T> void BST<T>::input(const string& file) ifstream fin(file); try { int temp; while (!fin.eof()) throw 1; { fin >> temp; add(temp); } fin.close(); } catch (int i) { cout << "This file don't find" << endl; } } template <typename T> void BST<T>::output(const string& file) const { ofstream fout(file); show(fout, root); fout.close(); } template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const { if (Tree == nullptr) return false; if (x == Tree->element) { return true; } else if (x < Tree->element) { search(x, Tree->left); } else search(x, Tree->right); } template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) { if (min->left == nullptr) return min; else return MinElement(min->left); } template <typename T> Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val) { if (!current) return false; if (current->element == val) { if (current->left == NULL || current->right == NULL) { Node<T>* temp = current->left; if (current->right) temp = current->right; if (parent) { if (parent->left == current) { parent->left = temp; } else { parent->right = temp; } } else { this->root = temp; } } else { Node<T>* validSubs = current->right; while (validSubs->left) { validSubs = validSubs->left; } T temp = current->element; current->element = validSubs->element; validSubs->element = temp; return del(current, current->right, temp); } delete current; count--; return true; } if (current->element > val) return del(current, current->left, val); else return del(current, current->right, val); } template <typename T> bool BST<T>::delVal(const T& val) { return this->del(NULL, root, val); } <commit_msg>Create BST.hpp<commit_after>#include <iostream> #include <fstream> using namespace std; template <class T> struct Node { T element; Node<T> *left, *right, *pparent; }; template <class T> class BST { private: Node<T> *root; int count; public: BST(); ~BST(); void deleteTree(Node<T> *Tree); void show(ostream&cout, const Node<T> *Tree) const; void add(const T&); bool search(const T&, Node<T> *Tree) const; void input(const string& file); void output(const string& file) const; Node<T>* MinElement(Node<T>* min); Node<T>* getroot() const; int getcount() const; Node<T>* del(Node<T>* parent, Node<T>* current, const T& val); bool delVal(const T& val); }; template <typename T> BST<T>::BST() { root = NULL; count = 0; } template <typename T> BST<T>::~BST() { deleteTree(root); } template <typename T>void BST<T>::deleteTree(Node<T> *Tree) { if (!Tree) return; if (Tree->left) { deleteTree(Tree->left); Tree->left = nullptr; } if (Tree->right) { deleteTree(Tree->right); Tree->right = nullptr; } delete Tree; } template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{ if (Tree != NULL) { cout << Tree->element << endl;; show(cout, Tree->left); show(cout, Tree->right); } } template <typename T> void BST<T>::add(const T &x) { Node<T>* daughter = new Node<T>; daughter->element = x; daughter->left = daughter->right = nullptr; Node<T>* parent = root; Node<T>* temp = root; while (temp) { parent = temp; if (x < temp->element) temp = temp->left; else temp = temp->right; } if (!parent) root = daughter; else { if (x < parent->element) parent->left = daughter; else parent->right = daughter; } count++; } template <typename T> Node<T>* BST<T>::getroot() const { return root; } template <typename T> int BST<T>::getcount() const { return count; } template <typename T> void BST<T>::input(const string& file) { ifstream fin(file); try { int temp; while (!fin.eof()) throw 1; { fin >> temp; add(temp); } fin.close(); } catch (int i) { cout << "This file don't find" << endl; } } template <typename T> void BST<T>::output(const string& file) const { ofstream fout(file); show(fout, root); fout.close(); } template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const { if (Tree == nullptr) return false; if (x == Tree->element) { return true; } else if (x < Tree->element) { search(x, Tree->left); } else search(x, Tree->right); } template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) { if (min->left == nullptr) return min; else return MinElement(min->left); } template <typename T> Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val) { if (!current) return false; if (current->element == val) { if (current->left == NULL || current->right == NULL) { Node<T>* temp = current->left; if (current->right) temp = current->right; if (parent) { if (parent->left == current) { parent->left = temp; } else { parent->right = temp; } } else { this->root = temp; } } else { Node<T>* validSubs = current->right; while (validSubs->left) { validSubs = validSubs->left; } T temp = current->element; current->element = validSubs->element; validSubs->element = temp; return del(current, current->right, temp); } delete current; count--; return true; } if (current->element > val) return del(current, current->left, val); else return del(current, current->right, val); } template <typename T> bool BST<T>::delVal(const T& val) { return this->del(NULL, root, val); } <|endoftext|>
<commit_before>#pragma once #include "cpputil.hh" #include "ns.hh" #include "gc.hh" #include "atomic.hh" #include "ref.hh" u64 namehash(const strbuf<DIRSIZ>&); struct file : public referenced { static file *alloc(); file *dup(); int stat(struct stat*); int read(char *addr, int n); ssize_t pread(char *addr, size_t n, off_t offset); int write(char *addr, int n); enum { FD_NONE, FD_PIPE, FD_INODE, FD_SOCKET } type; char readable; char writable; int socket; struct pipe *pipe; struct inode *ip; u32 off; NEW_DELETE_OPS(file); private: file(); protected: virtual void onzero() const; }; // in-core file system types struct inode : public rcu_freed { u32 dev; // Device number u32 inum; // Inode number u32 gen; // Generation number std::atomic<int> ref; // Reference count int flags; // I_BUSY, I_VALID std::atomic<int> readbusy; struct condvar cv; struct spinlock lock; char lockname[16]; std::atomic<xns<strbuf<DIRSIZ>, u32, namehash>*> dir; short type; // copy of disk inode short major; short minor; short nlink; u32 size; u32 addrs[NDIRECT+1]; inode(); ~inode(); virtual void do_gc() { delete this; } NEW_DELETE_OPS(inode) }; #define I_BUSYR 0x1 #define I_BUSYW 0x2 #define I_VALID 0x4 #define I_FREE 0x8 // device implementations struct devsw { int (*read)(struct inode*, char*, u32, u32); int (*write)(struct inode*, char*, u32, u32); void (*stat)(struct inode*, struct stat*); }; extern struct devsw devsw[]; #define CONSOLE 1 #define NETIF 2 #define SAMPLER 3 #define DEVLOCKSTAT 4 <commit_msg>Misc file clean<commit_after>#pragma once #include "cpputil.hh" #include "ns.hh" #include "gc.hh" #include "atomic.hh" #include "ref.hh" u64 namehash(const strbuf<DIRSIZ>&); struct file : public referenced { static file* alloc(); file* dup(); int stat(struct stat*); int read(char *addr, int n); ssize_t pread(char *addr, size_t n, off_t offset); int write(char *addr, int n); enum { FD_NONE, FD_PIPE, FD_INODE, FD_SOCKET } type; char readable; char writable; int socket; struct pipe *pipe; struct inode *ip; u32 off; private: file(); file& operator=(const file&); file(const file& x); NEW_DELETE_OPS(file); protected: virtual void onzero() const; }; // in-core file system types struct inode : public rcu_freed { u32 dev; // Device number u32 inum; // Inode number u32 gen; // Generation number std::atomic<int> ref; // Reference count int flags; // I_BUSY, I_VALID std::atomic<int> readbusy; struct condvar cv; struct spinlock lock; char lockname[16]; std::atomic<xns<strbuf<DIRSIZ>, u32, namehash>*> dir; short type; // copy of disk inode short major; short minor; short nlink; u32 size; u32 addrs[NDIRECT+1]; inode(); ~inode(); virtual void do_gc() { delete this; } NEW_DELETE_OPS(inode) }; #define I_BUSYR 0x1 #define I_BUSYW 0x2 #define I_VALID 0x4 #define I_FREE 0x8 // device implementations struct devsw { int (*read)(struct inode*, char*, u32, u32); int (*write)(struct inode*, char*, u32, u32); void (*stat)(struct inode*, struct stat*); }; extern struct devsw devsw[]; #define CONSOLE 1 #define NETIF 2 #define SAMPLER 3 #define DEVLOCKSTAT 4 <|endoftext|>
<commit_before>/************************************************ * gen.hpp * ESA++ * * Copyright (c) 2014, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef ESAPP_GEN_HPP_ #define ESAPP_GEN_HPP_ #include <iterator> #include <type_traits> namespace esapp { /************************************************ * Declaration: class generator_iterator ************************************************/ template <typename I, typename G> class generator_iterator : public std::iterator< std::input_iterator_tag, typename std::result_of<G(I &, I const &)>::type, ptrdiff_t, typename std::add_pointer< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type, typename std::add_lvalue_reference< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type > { private: // Private Type(s) typedef std::iterator< std::input_iterator_tag, typename std::result_of<G(I &, I const &)>::type, ptrdiff_t, typename std::add_pointer< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type, typename std::add_lvalue_reference< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type > base; public: // Public Type(s) typedef typename base::iterator_category iterator_category; typedef typename base::value_type value_type; typedef typename base::reference reference; typedef typename base::pointer pointer; typedef typename base::difference_type difference_type; typedef I iterator; typedef G generator; public: // Public Method(s) generator_iterator(iterator const &begin, iterator const &end, generator const &g); template <typename Initializer> generator_iterator(iterator const &begin, iterator const &end, generator const &g, Initializer const &init); generator_iterator(generator_iterator const &it); generator_iterator begin(void) const; generator_iterator end(void) const; generator_iterator &operator++(void); generator_iterator operator++(int); reference operator*(void) const; pointer operator->(void) const; bool operator==(generator_iterator const &it) const; bool operator!=(generator_iterator const &it) const; private: // Private Property(ies) iterator begin_, end_; generator g_; value_type val_; bool has_val_; }; // class generator_iterator /************************************************ * Implementation: class generator_iterator ************************************************/ template <typename I, typename G> inline generator_iterator<I, G>::generator_iterator(iterator const &begin, iterator const &end, generator const &g) : begin_(begin), end_(end), g_(g) { operator++(); } template <typename I, typename G> template <typename Initializer> inline generator_iterator<I, G>::generator_iterator(iterator const &begin, iterator const &end, generator const &g, Initializer const &init) : begin_(begin), end_(end), g_(g) { init(begin_, end_); operator++(); } template <typename I, typename G> inline generator_iterator<I, G>::generator_iterator(generator_iterator const &it) : begin_(it.begin_), end_(it.end_), g_(it.g_), val_(it.val_), has_val_(it.has_val_) { // do nothing } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::begin(void) const { return *this; } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::end(void) const { return generator_iterator(end_, end_, g_); } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator & generator_iterator<I, G>::operator++(void) { has_val_ = begin_ != end_; val_ = has_val_ ? g_(begin_, end_) : decltype(val_)(); return *this; } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::operator++(int) { generator_iterator it(*this); operator++(); return it; } template <typename I, typename G> inline typename generator_iterator<I, G>::reference generator_iterator<I, G>::operator*(void) const { return val_; } template <typename I, typename G> inline typename generator_iterator<I, G>::pointer generator_iterator<I, G>::operator->(void) const { return &val_; } template <typename I, typename G> inline bool generator_iterator<I, G>::operator==(generator_iterator const &it) const { return begin_ == it.begin_ && end_ == it.end_ && g_ == it.g_ && val_ == it.val_ && has_val_ == it.has_val_; } template <typename I, typename G> inline bool generator_iterator<I, G>::operator!=(generator_iterator const &it) const { return !(*this == it); } } // namespace esapp #endif // ESAPP_GEN_HPP_ <commit_msg>Simpify typedefs for generator<commit_after>/************************************************ * gen.hpp * ESA++ * * Copyright (c) 2014, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef ESAPP_GEN_HPP_ #define ESAPP_GEN_HPP_ #include <iterator> #include <type_traits> namespace esapp { /************************************************ * Declaration: class generator_iterator ************************************************/ template <typename I, typename G> class generator_iterator : public std::iterator< std::input_iterator_tag, typename std::result_of<G(I &, I const &)>::type, ptrdiff_t, typename std::add_pointer< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type, typename std::add_lvalue_reference< typename std::add_const< typename std::result_of<G(I &, I const &)>::type >::type >::type > { public: // Public Type(s) typedef std::input_iterator_tag iterator_category; typedef typename std::result_of<G(I &, I const &)>::type value_type; typedef value_type const &reference; typedef value_type const *pointer; typedef ptrdiff_t difference_type; typedef I iterator; typedef G generator; public: // Public Method(s) generator_iterator(iterator const &begin, iterator const &end, generator const &g); template <typename Initializer> generator_iterator(iterator const &begin, iterator const &end, generator const &g, Initializer const &init); generator_iterator(generator_iterator const &it); generator_iterator begin(void) const; generator_iterator end(void) const; generator_iterator &operator++(void); generator_iterator operator++(int); reference operator*(void) const; pointer operator->(void) const; bool operator==(generator_iterator const &it) const; bool operator!=(generator_iterator const &it) const; private: // Private Property(ies) iterator begin_, end_; generator g_; value_type val_; bool has_val_; }; // class generator_iterator /************************************************ * Implementation: class generator_iterator ************************************************/ template <typename I, typename G> inline generator_iterator<I, G>::generator_iterator(iterator const &begin, iterator const &end, generator const &g) : begin_(begin), end_(end), g_(g) { operator++(); } template <typename I, typename G> template <typename Initializer> inline generator_iterator<I, G>::generator_iterator(iterator const &begin, iterator const &end, generator const &g, Initializer const &init) : begin_(begin), end_(end), g_(g) { init(begin_, end_); operator++(); } template <typename I, typename G> inline generator_iterator<I, G>::generator_iterator(generator_iterator const &it) : begin_(it.begin_), end_(it.end_), g_(it.g_), val_(it.val_), has_val_(it.has_val_) { // do nothing } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::begin(void) const { return *this; } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::end(void) const { return generator_iterator(end_, end_, g_); } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator & generator_iterator<I, G>::operator++(void) { has_val_ = begin_ != end_; val_ = has_val_ ? g_(begin_, end_) : decltype(val_)(); return *this; } template <typename I, typename G> inline typename generator_iterator<I, G>::generator_iterator generator_iterator<I, G>::operator++(int) { generator_iterator it(*this); operator++(); return it; } template <typename I, typename G> inline typename generator_iterator<I, G>::reference generator_iterator<I, G>::operator*(void) const { return val_; } template <typename I, typename G> inline typename generator_iterator<I, G>::pointer generator_iterator<I, G>::operator->(void) const { return &val_; } template <typename I, typename G> inline bool generator_iterator<I, G>::operator==(generator_iterator const &it) const { return begin_ == it.begin_ && end_ == it.end_ && g_ == it.g_ && val_ == it.val_ && has_val_ == it.has_val_; } template <typename I, typename G> inline bool generator_iterator<I, G>::operator!=(generator_iterator const &it) const { return !(*this == it); } } // namespace esapp #endif // ESAPP_GEN_HPP_ <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #ifndef URI_HPP #define URI_HPP #include <gsl.h> #include <unordered_map> namespace uri { /** * Representation of RFC 3986 URI's. * Ref. https://tools.ietf.org/html/rfc3986 **/ class URI { private: /** Non-owning pointer-size type */ struct Span_t { size_t begin; size_t end; Span_t(const size_t b = 0U, const size_t e = 0U) noexcept : begin{b} , end{e} {} }; //< struct Span_t public: /* * Default constructor */ URI() = default; /* * Default copy and move constructors */ URI(URI&) = default; URI(URI&&) = default; /* * Default destructor */ ~URI() = default; /* * Default assignment operators */ URI& operator=(const URI&) = default; URI& operator=(URI&&) = default; // // We might do a span-based constructor later. // URI(gsl::span<const char>); // /** * @brief Construct using a C-String * * @param uri : A C-String representing a uri */ URI(const char* uri); /** * @brief Construct using a string * * @param uri : A string representing a uri */ URI(const std::string& uri); /////////////////////////////////////////////// //----------RFC-specified URI parts----------// /////////////////////////////////////////////// /** * @brief Get userinfo. * * E.g. 'username@'... * * @return The user's information */ std::string userinfo() const; /** * @brief Get host. * * E.g. 'includeos.org', '10.0.0.42' etc. * * @return The host's information */ std::string host() const; /** * @brief Get the raw port number in decimal character representation. * * @return The raw port number as a string */ std::string port_str() const; /** * @brief Get numeric port number. * * @warning The RFC doesn't specify dimension. This funcion will truncate * any overflowing digits. * * @return The numeric port number as a 16-bit number */ uint16_t port() const noexcept; /** Get the path. E.g. /pictures/logo.png */ std::string path() const; /** Get the complete unparsed query string. */ const std::string query() const; /** Get the fragment part. E.g. "...#anchor1" */ const std::string fragment() const; /// /// Convenience /// /** * Get the URI-decoded value of a query-string key. * * E.g. for query() => "?name=Bjarne%20Stroustrup", * query("name") returns "Bjarne Stroustrup" */ std::string query(std::string key); /** String representation **/ std::string to_string() const; private: std::unordered_map<std::string,std::string> queries_; Span_t uri_data_; Span_t userinfo_; Span_t host_; Span_t port_str_; uint16_t port_ = 0; Span_t path_; Span_t query_; Span_t fragment_; static const Span_t zero_span_; // A copy of the data, if the string-based constructor was used std::string uri_str_; /** * @brief Parse the given string representing a uri * into its given parts according to RFC 3986 * * @param uri : The string representing a uri */ void parse(const std::string& uri); }; // class uri::URI std::ostream& operator<< (std::ostream&, const URI&); } // namespace uri #endif <commit_msg>Changed API doc for method API::path<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #ifndef URI_HPP #define URI_HPP #include <gsl.h> #include <unordered_map> namespace uri { /** * Representation of RFC 3986 URI's. * Ref. https://tools.ietf.org/html/rfc3986 **/ class URI { private: /** Non-owning pointer-size type */ struct Span_t { size_t begin; size_t end; Span_t(const size_t b = 0U, const size_t e = 0U) noexcept : begin{b} , end{e} {} }; //< struct Span_t public: /* * Default constructor */ URI() = default; /* * Default copy and move constructors */ URI(URI&) = default; URI(URI&&) = default; /* * Default destructor */ ~URI() = default; /* * Default assignment operators */ URI& operator=(const URI&) = default; URI& operator=(URI&&) = default; // // We might do a span-based constructor later. // URI(gsl::span<const char>); // /** * @brief Construct using a C-String * * @param uri : A C-String representing a uri */ URI(const char* uri); /** * @brief Construct using a string * * @param uri : A string representing a uri */ URI(const std::string& uri); /////////////////////////////////////////////// //----------RFC-specified URI parts----------// /////////////////////////////////////////////// /** * @brief Get userinfo. * * E.g. 'username@'... * * @return The user's information */ std::string userinfo() const; /** * @brief Get host. * * E.g. 'includeos.org', '10.0.0.42' etc. * * @return The host's information */ std::string host() const; /** * @brief Get the raw port number in decimal character representation. * * @return The raw port number as a string */ std::string port_str() const; /** * @brief Get numeric port number. * * @warning The RFC doesn't specify dimension. This funcion will truncate * any overflowing digits. * * @return The numeric port number as a 16-bit number */ uint16_t port() const noexcept; /** * @brief Get the path. * * E.g. /pictures/logo.png * * @return The path information */ std::string path() const; /** Get the complete unparsed query string. */ const std::string query() const; /** Get the fragment part. E.g. "...#anchor1" */ const std::string fragment() const; /// /// Convenience /// /** * Get the URI-decoded value of a query-string key. * * E.g. for query() => "?name=Bjarne%20Stroustrup", * query("name") returns "Bjarne Stroustrup" */ std::string query(std::string key); /** String representation **/ std::string to_string() const; private: std::unordered_map<std::string,std::string> queries_; Span_t uri_data_; Span_t userinfo_; Span_t host_; Span_t port_str_; uint16_t port_ = 0; Span_t path_; Span_t query_; Span_t fragment_; static const Span_t zero_span_; // A copy of the data, if the string-based constructor was used std::string uri_str_; /** * @brief Parse the given string representing a uri * into its given parts according to RFC 3986 * * @param uri : The string representing a uri */ void parse(const std::string& uri); }; // class uri::URI std::ostream& operator<< (std::ostream&, const URI&); } // namespace uri #endif <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.txt 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. =========================================================================*/ // QT includes #include <QChildEvent> #include <QDebug> #include <QDialogButtonBox> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QListView> #include <QPushButton> // CTK includes #include "ctkFileDialog.h" //------------------------------------------------------------------------------ class ctkFileDialogPrivate { Q_DECLARE_PUBLIC(ctkFileDialog); protected: ctkFileDialog* const q_ptr; public: ctkFileDialogPrivate(ctkFileDialog& object); void init(); void observeAcceptButton(); QPushButton* acceptButton()const; QListView* listView()const; bool AcceptButtonEnable; bool AcceptButtonState; bool IgnoreEvent; }; //------------------------------------------------------------------------------ ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object) :q_ptr(&object) { this->IgnoreEvent = false; this->AcceptButtonEnable = true; this->AcceptButtonState = true; } //------------------------------------------------------------------------------ void ctkFileDialogPrivate::init() { Q_Q(ctkFileDialog); this->observeAcceptButton(); QObject::connect(this->listView()->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(onSelectionChanged())); } //------------------------------------------------------------------------------ QPushButton* ctkFileDialogPrivate::acceptButton()const { Q_Q(const ctkFileDialog); QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>(); Q_ASSERT(buttonBox); QDialogButtonBox::StandardButton button = (q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save); return buttonBox->button(button); } //------------------------------------------------------------------------------ QListView* ctkFileDialogPrivate::listView()const { Q_Q(const ctkFileDialog); QListView* listView= q->findChild<QListView*>("listView"); Q_ASSERT(listView); return listView; } //------------------------------------------------------------------------------ void ctkFileDialogPrivate::observeAcceptButton() { Q_Q(ctkFileDialog); QPushButton* button = this->acceptButton(); Q_ASSERT(button); this->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent())); // TODO: catching the event of the enable state is not enough, if the user // double click on the file, the dialog will be accepted, that event should // be intercepted as well button->installEventFilter(q); } //------------------------------------------------------------------------------ ctkFileDialog::ctkFileDialog(QWidget *parentWidget, const QString &caption, const QString &directory, const QString &filter) :QFileDialog(parentWidget, caption, directory, filter) , d_ptr(new ctkFileDialogPrivate(*this)) { Q_D(ctkFileDialog); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) this->setOptions(DontUseNativeDialog); #endif d->init(); } //------------------------------------------------------------------------------ ctkFileDialog::~ctkFileDialog() { } //------------------------------------------------------------------------------ void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label) { QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout()); QWidget* oldBottomWidget = this->bottomWidget(); // remove the old widget from the layout if any if (oldBottomWidget) { if (oldBottomWidget == widget) { return; } gridLayout->removeWidget(oldBottomWidget); delete oldBottomWidget; } if (widget == 0) { return; } if (!label.isEmpty()) { gridLayout->addWidget(new QLabel(label), 4, 0); gridLayout->addWidget(widget,4, 1,1, 1); } else { gridLayout->addWidget(widget,4, 0,1, 2); } // The dialog button box is no longer spanned on 2 rows but on 3 rows if // there is a "bottom widget" QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>(); Q_ASSERT(buttonBox); gridLayout->removeWidget(buttonBox); gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1); } //------------------------------------------------------------------------------ QWidget* ctkFileDialog::bottomWidget()const { QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout()); QLayoutItem* item = gridLayout->itemAtPosition(4,1); return item ? item->widget() : 0; } //------------------------------------------------------------------------------ void ctkFileDialog::setAcceptButtonEnable(bool enable) { Q_D(ctkFileDialog); d->AcceptButtonEnable = enable; d->IgnoreEvent = true; d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState); d->IgnoreEvent = false; } //------------------------------------------------------------------------------ bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event) { Q_D(ctkFileDialog); QPushButton* button = d->acceptButton(); QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj); if (obj == button && event->type() == QEvent::EnabledChange && !d->IgnoreEvent) { d->IgnoreEvent = true; d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent())); button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState); d->IgnoreEvent = false; } else if (obj == button && event->type() == QEvent::Destroy) { // The accept button is deleted probably because setAcceptMode() is being called. // observe the parent to check when the accept button is added back obj->parent()->installEventFilter(this); } else if (dialogButtonBox && event->type() == QEvent::ChildAdded) { dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this); } return QFileDialog::eventFilter(obj, event); } //------------------------------------------------------------------------------ void ctkFileDialog::onSelectionChanged() { emit this->fileSelectionChanged(this->selectedFiles()); } //------------------------------------------------------------------------------ void ctkFileDialog::accept() { QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender()); if (fileNameEdit) { QFileInfo info(fileNameEdit->text()); if (info.isDir()) { setDirectory(info.absoluteFilePath()); return; } } // Don't accept read-only directories if we are in AcceptSave mode. if ((this->fileMode() == Directory || this->fileMode() == DirectoryOnly) && this->acceptMode() == AcceptSave) { QStringList files = this->selectedFiles(); QString fn = files.first(); QFileInfo info(fn); if (info.isDir() && !info.isWritable()) { this->setDirectory(info.absoluteFilePath()); return; } } this->Superclass::accept(); } <commit_msg>improved in-code description of previous ctkFileDialog crash fix<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.txt 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. =========================================================================*/ // QT includes #include <QChildEvent> #include <QDebug> #include <QDialogButtonBox> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QListView> #include <QPushButton> // CTK includes #include "ctkFileDialog.h" //------------------------------------------------------------------------------ class ctkFileDialogPrivate { Q_DECLARE_PUBLIC(ctkFileDialog); protected: ctkFileDialog* const q_ptr; public: ctkFileDialogPrivate(ctkFileDialog& object); void init(); void observeAcceptButton(); QPushButton* acceptButton()const; QListView* listView()const; bool AcceptButtonEnable; bool AcceptButtonState; bool IgnoreEvent; }; //------------------------------------------------------------------------------ ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object) :q_ptr(&object) { this->IgnoreEvent = false; this->AcceptButtonEnable = true; this->AcceptButtonState = true; } //------------------------------------------------------------------------------ void ctkFileDialogPrivate::init() { Q_Q(ctkFileDialog); this->observeAcceptButton(); QObject::connect(this->listView()->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(onSelectionChanged())); } //------------------------------------------------------------------------------ QPushButton* ctkFileDialogPrivate::acceptButton()const { Q_Q(const ctkFileDialog); QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>(); Q_ASSERT(buttonBox); QDialogButtonBox::StandardButton button = (q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save); return buttonBox->button(button); } //------------------------------------------------------------------------------ QListView* ctkFileDialogPrivate::listView()const { Q_Q(const ctkFileDialog); QListView* listView= q->findChild<QListView*>("listView"); Q_ASSERT(listView); return listView; } //------------------------------------------------------------------------------ void ctkFileDialogPrivate::observeAcceptButton() { Q_Q(ctkFileDialog); QPushButton* button = this->acceptButton(); Q_ASSERT(button); this->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent())); // TODO: catching the event of the enable state is not enough, if the user // double click on the file, the dialog will be accepted, that event should // be intercepted as well button->installEventFilter(q); } //------------------------------------------------------------------------------ ctkFileDialog::ctkFileDialog(QWidget *parentWidget, const QString &caption, const QString &directory, const QString &filter) :QFileDialog(parentWidget, caption, directory, filter) , d_ptr(new ctkFileDialogPrivate(*this)) { Q_D(ctkFileDialog); // The findChild<QDialogButtonBox*>() call fails on Mac/Qt5 because native // dialogs don't publish any internals. No problems on other OS. // Can be applied to Qt4 as well, if problems arise there. #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) this->setOptions(DontUseNativeDialog); #endif d->init(); } //------------------------------------------------------------------------------ ctkFileDialog::~ctkFileDialog() { } //------------------------------------------------------------------------------ void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label) { QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout()); QWidget* oldBottomWidget = this->bottomWidget(); // remove the old widget from the layout if any if (oldBottomWidget) { if (oldBottomWidget == widget) { return; } gridLayout->removeWidget(oldBottomWidget); delete oldBottomWidget; } if (widget == 0) { return; } if (!label.isEmpty()) { gridLayout->addWidget(new QLabel(label), 4, 0); gridLayout->addWidget(widget,4, 1,1, 1); } else { gridLayout->addWidget(widget,4, 0,1, 2); } // The dialog button box is no longer spanned on 2 rows but on 3 rows if // there is a "bottom widget" QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>(); Q_ASSERT(buttonBox); gridLayout->removeWidget(buttonBox); gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1); } //------------------------------------------------------------------------------ QWidget* ctkFileDialog::bottomWidget()const { QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout()); QLayoutItem* item = gridLayout->itemAtPosition(4,1); return item ? item->widget() : 0; } //------------------------------------------------------------------------------ void ctkFileDialog::setAcceptButtonEnable(bool enable) { Q_D(ctkFileDialog); d->AcceptButtonEnable = enable; d->IgnoreEvent = true; d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState); d->IgnoreEvent = false; } //------------------------------------------------------------------------------ bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event) { Q_D(ctkFileDialog); QPushButton* button = d->acceptButton(); QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj); if (obj == button && event->type() == QEvent::EnabledChange && !d->IgnoreEvent) { d->IgnoreEvent = true; d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent())); button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState); d->IgnoreEvent = false; } else if (obj == button && event->type() == QEvent::Destroy) { // The accept button is deleted probably because setAcceptMode() is being called. // observe the parent to check when the accept button is added back obj->parent()->installEventFilter(this); } else if (dialogButtonBox && event->type() == QEvent::ChildAdded) { dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this); } return QFileDialog::eventFilter(obj, event); } //------------------------------------------------------------------------------ void ctkFileDialog::onSelectionChanged() { emit this->fileSelectionChanged(this->selectedFiles()); } //------------------------------------------------------------------------------ void ctkFileDialog::accept() { QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender()); if (fileNameEdit) { QFileInfo info(fileNameEdit->text()); if (info.isDir()) { setDirectory(info.absoluteFilePath()); return; } } // Don't accept read-only directories if we are in AcceptSave mode. if ((this->fileMode() == Directory || this->fileMode() == DirectoryOnly) && this->acceptMode() == AcceptSave) { QStringList files = this->selectedFiles(); QString fn = files.first(); QFileInfo info(fn); if (info.isDir() && !info.isWritable()) { this->setDirectory(info.absoluteFilePath()); return; } } this->Superclass::accept(); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h" #include "mlir/Pass/PassManager.h" // TF:local_config_mlir #include "mlir/Transforms/Passes.h" // TF:local_config_mlir #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" namespace mlir { namespace TFTPU { void createTPUBridge(OpPassManager &pm) { OpPassManager &func_pm = pm.nest<FuncOp>(); func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass()); func_pm.addPass(createCanonicalizerPass()); func_pm.addPass(CreateTPUClusterFormationPass()); func_pm.addPass(tf_executor::CreateTFExecutorConstantSinkingPass()); func_pm.addPass(TFDevice::CreateResourceOpLiftingPass()); pm.addPass(TFDevice::CreateClusterOutliningPass()); pm.addPass(CreateTPURewritePass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass()); pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(createCanonicalizerPass()); } tensorflow::Status TPUBridge(ModuleOp module) { // Populate a passmanager with the list of passes that implement the bridge. PassManager bridge(module.getContext()); createTPUBridge(bridge); // Run the bridge on the module, in case of failure, the `diag_handler` // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status. mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); if (failed(bridge.run(module))) return diag_handler.ConsumeStatus(); return diag_handler.ConsumeStatus(); } } // namespace TFTPU } // namespace mlir <commit_msg>Move canonicalizer pass to after TPU cluster formation to prevent canonicalization from losing _tpu_replicate attributes<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h" #include "mlir/Pass/PassManager.h" // TF:local_config_mlir #include "mlir/Transforms/Passes.h" // TF:local_config_mlir #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" namespace mlir { namespace TFTPU { void createTPUBridge(OpPassManager &pm) { OpPassManager &func_pm = pm.nest<FuncOp>(); func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass()); func_pm.addPass(CreateTPUClusterFormationPass()); func_pm.addPass(createCanonicalizerPass()); func_pm.addPass(tf_executor::CreateTFExecutorConstantSinkingPass()); func_pm.addPass(TFDevice::CreateResourceOpLiftingPass()); pm.addPass(TFDevice::CreateClusterOutliningPass()); pm.addPass(CreateTPURewritePass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass()); pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(createCanonicalizerPass()); } tensorflow::Status TPUBridge(ModuleOp module) { // Populate a passmanager with the list of passes that implement the bridge. PassManager bridge(module.getContext()); createTPUBridge(bridge); // Run the bridge on the module, in case of failure, the `diag_handler` // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status. mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); if (failed(bridge.run(module))) return diag_handler.ConsumeStatus(); return diag_handler.ConsumeStatus(); } } // namespace TFTPU } // namespace mlir <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice 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 <boost/shared_ptr.hpp> #include <unicode/regex.h> #include <comphelper/configuration.hxx> #include <officecfg/Office/Common.hxx> #include <opencl/openclconfig.hxx> #include <opencl/platforminfo.hxx> #include <rtl/ustring.hxx> #include <sal/types.h> OpenCLConfig::OpenCLConfig() : mbUseOpenCL(true) { // This entry we have had for some time (when blacklisting was // done elsewhere in the code), so presumably there is a known // good reason for it. maBlackList.insert(ImplMatcher("Windows", "", "Intel\\(R\\) Corporation", "", "9\\.17\\.10\\.2884")); // This is what I have tested on Linux and it works for our unit tests. maWhiteList.insert(ImplMatcher("Linux", "", "Advanced Micro Devices, Inc\\.", "", "1445\\.5 \\(sse2,avx\\)")); // For now, assume that AMD, Intel and NVIDIA drivers are good maWhiteList.insert(ImplMatcher("", "", "Advanced Micro Devices, Inc\\.", "", "")); maWhiteList.insert(ImplMatcher("", "", "Intel\\(R\\) Corporation", "", "")); maWhiteList.insert(ImplMatcher("", "", "NVIDIA Corporation", "", "")); } bool OpenCLConfig::operator== (const OpenCLConfig& r) const { return (mbUseOpenCL == r.mbUseOpenCL && maBlackList == r.maBlackList && maWhiteList == r.maWhiteList && true); } bool OpenCLConfig::operator!= (const OpenCLConfig& r) const { return !operator== (r); } namespace { css::uno::Sequence<OUString> SetOfImplMatcherToStringSequence(const OpenCLConfig::ImplMatcherSet& rSet) { css::uno::Sequence<OUString> result(rSet.size()); size_t n(0); for (auto i = rSet.cbegin(); i != rSet.cend(); ++i) { result[n++] = (*i).maOS.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maOSVersion.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maPlatformVendor.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maDevice.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maDriverVersion.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B"); } return result; } OUString getToken(const OUString& string, sal_Int32& index) { OUString token(string.getToken(0, '/', index)); OUString result; sal_Int32 i(0); sal_Int32 p; while ((p = token.indexOf('%', i)) >= 0) { if (p > i) result += token.copy(i, p - i); if (p < token.getLength() - 2) { result += OUString(static_cast<sal_Unicode>(token.copy(p+1, 2).toInt32(16))); i = p + 3; } else { i = token.getLength(); } } result += token.copy(i); return result; } OpenCLConfig::ImplMatcherSet StringSequenceToSetOfImplMatcher(const css::uno::Sequence<OUString>& rSequence) { OpenCLConfig::ImplMatcherSet result; for (auto i = rSequence.begin(); i != rSequence.end(); ++i) { OpenCLConfig::ImplMatcher m; sal_Int32 index(0); m.maOS = getToken(*i, index); m.maOSVersion = getToken(*i, index); m.maPlatformVendor = getToken(*i, index); m.maDevice = getToken(*i, index); m.maDriverVersion = getToken(*i, index); result.insert(m); } return result; } bool match(const OUString& rPattern, const OUString& rInput) { if (rPattern == "") return true; UErrorCode nIcuError(U_ZERO_ERROR); icu::UnicodeString sIcuPattern(reinterpret_cast<const UChar*>(rPattern.getStr()), rPattern.getLength()); icu::UnicodeString sIcuInput(reinterpret_cast<const UChar*>(rInput.getStr()), rInput.getLength()); RegexMatcher aMatcher(sIcuPattern, sIcuInput, 0, nIcuError); if (U_SUCCESS(nIcuError) && aMatcher.matches(nIcuError) && U_SUCCESS(nIcuError)) return true; return false; } bool match(const OpenCLConfig::ImplMatcher& rListEntry, const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice) { #if defined WNT if (rListEntry.maOS != "" && rListEntry.maOS != "Windows") return false; #elif defined LINUX if (rListEntry.maOS != "" && rListEntry.maOS != "Linux") return false; #elif defined MACOSX if (rListEntry.maOS != "" && rListEntry.maOS != "OS X") return false; #endif // OS version check not yet implemented if (!match(rListEntry.maPlatformVendor, rPlatform.maVendor)) return false; if (!match(rListEntry.maDevice, rDevice.maName)) return false; if (!match(rListEntry.maDriverVersion, rDevice.maDriver)) return false; return true; } bool match(const OpenCLConfig::ImplMatcherSet& rList, const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice, const char* sKindOfList) { for (auto i = rList.cbegin(); i != rList.end(); ++i) { SAL_INFO("opencl", "Looking for match for platform=" << rPlatform << ", device=" << rDevice << " in " << sKindOfList << " entry=" << *i); if (match(*i, rPlatform, rDevice)) { SAL_INFO("opencl", "Match!"); return true; } } return false; } } // anonymous namespace OpenCLConfig OpenCLConfig::get() { OpenCLConfig result; result.mbUseOpenCL = officecfg::Office::Common::Misc::UseOpenCL::get(); result.maBlackList = StringSequenceToSetOfImplMatcher(officecfg::Office::Common::Misc::OpenCLBlackList::get()); result.maWhiteList = StringSequenceToSetOfImplMatcher(officecfg::Office::Common::Misc::OpenCLWhiteList::get()); return result; } void OpenCLConfig::set() { boost::shared_ptr<comphelper::ConfigurationChanges> batch(comphelper::ConfigurationChanges::create()); officecfg::Office::Common::Misc::UseOpenCL::set(mbUseOpenCL, batch); officecfg::Office::Common::Misc::OpenCLBlackList::set(SetOfImplMatcherToStringSequence(maBlackList), batch); officecfg::Office::Common::Misc::OpenCLWhiteList::set(SetOfImplMatcherToStringSequence(maWhiteList), batch); batch->commit(); } bool OpenCLConfig::checkImplementation(const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice) const { // Check blacklist of known bad OpenCL implementations if (match(maBlackList, rPlatform, rDevice, "blacklist")) { SAL_INFO("opencl", "Rejecting"); return true; } // Check for whitelist of known good OpenCL implementations if (match(maWhiteList, rPlatform, rDevice, "whitelist")) { SAL_INFO("opencl", "Approving"); return false; } // Fallback: reject SAL_INFO("opencl", "Fallback: rejecting platform=" << rPlatform << ", device=" << rDevice); return true; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig& rConfig) { rStream << "{" "UseOpenCL=" << (rConfig.mbUseOpenCL ? "YES" : "NO") << "," "BlackList=" << rConfig.maBlackList << "," "WhiteList=" << rConfig.maWhiteList << "}"; return rStream; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcher& rImpl) { rStream << "{" "OS=" << rImpl.maOS << "," "OSVersion=" << rImpl.maOSVersion << "," "PlatformVendor=" << rImpl.maPlatformVendor << "," "Device=" << rImpl.maDevice << "," "DriverVersion=" << rImpl.maDriverVersion << "}"; return rStream; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcherSet& rSet) { rStream << "{"; for (auto i = rSet.cbegin(); i != rSet.cend(); ++i) { if (i != rSet.cbegin()) rStream << ","; rStream << *i; } rStream << "}"; return rStream; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>opencl: Use appropriate OUString functions on string constants<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice 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 <boost/shared_ptr.hpp> #include <unicode/regex.h> #include <comphelper/configuration.hxx> #include <officecfg/Office/Common.hxx> #include <opencl/openclconfig.hxx> #include <opencl/platforminfo.hxx> #include <rtl/ustring.hxx> #include <sal/types.h> OpenCLConfig::OpenCLConfig() : mbUseOpenCL(true) { // This entry we have had for some time (when blacklisting was // done elsewhere in the code), so presumably there is a known // good reason for it. maBlackList.insert(ImplMatcher("Windows", "", "Intel\\(R\\) Corporation", "", "9\\.17\\.10\\.2884")); // This is what I have tested on Linux and it works for our unit tests. maWhiteList.insert(ImplMatcher("Linux", "", "Advanced Micro Devices, Inc\\.", "", "1445\\.5 \\(sse2,avx\\)")); // For now, assume that AMD, Intel and NVIDIA drivers are good maWhiteList.insert(ImplMatcher("", "", "Advanced Micro Devices, Inc\\.", "", "")); maWhiteList.insert(ImplMatcher("", "", "Intel\\(R\\) Corporation", "", "")); maWhiteList.insert(ImplMatcher("", "", "NVIDIA Corporation", "", "")); } bool OpenCLConfig::operator== (const OpenCLConfig& r) const { return (mbUseOpenCL == r.mbUseOpenCL && maBlackList == r.maBlackList && maWhiteList == r.maWhiteList && true); } bool OpenCLConfig::operator!= (const OpenCLConfig& r) const { return !operator== (r); } namespace { css::uno::Sequence<OUString> SetOfImplMatcherToStringSequence(const OpenCLConfig::ImplMatcherSet& rSet) { css::uno::Sequence<OUString> result(rSet.size()); size_t n(0); for (auto i = rSet.cbegin(); i != rSet.cend(); ++i) { result[n++] = (*i).maOS.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maOSVersion.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maPlatformVendor.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maDevice.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B") + "/" + (*i).maDriverVersion.replaceAll("%", "%25").replaceAll("/", "%2F").replaceAll(";", "%3B"); } return result; } OUString getToken(const OUString& string, sal_Int32& index) { OUString token(string.getToken(0, '/', index)); OUString result; sal_Int32 i(0); sal_Int32 p; while ((p = token.indexOf('%', i)) >= 0) { if (p > i) result += token.copy(i, p - i); if (p < token.getLength() - 2) { result += OUString(static_cast<sal_Unicode>(token.copy(p+1, 2).toInt32(16))); i = p + 3; } else { i = token.getLength(); } } result += token.copy(i); return result; } OpenCLConfig::ImplMatcherSet StringSequenceToSetOfImplMatcher(const css::uno::Sequence<OUString>& rSequence) { OpenCLConfig::ImplMatcherSet result; for (auto i = rSequence.begin(); i != rSequence.end(); ++i) { OpenCLConfig::ImplMatcher m; sal_Int32 index(0); m.maOS = getToken(*i, index); m.maOSVersion = getToken(*i, index); m.maPlatformVendor = getToken(*i, index); m.maDevice = getToken(*i, index); m.maDriverVersion = getToken(*i, index); result.insert(m); } return result; } bool match(const OUString& rPattern, const OUString& rInput) { if (rPattern.isEmpty()) return true; UErrorCode nIcuError(U_ZERO_ERROR); icu::UnicodeString sIcuPattern(reinterpret_cast<const UChar*>(rPattern.getStr()), rPattern.getLength()); icu::UnicodeString sIcuInput(reinterpret_cast<const UChar*>(rInput.getStr()), rInput.getLength()); RegexMatcher aMatcher(sIcuPattern, sIcuInput, 0, nIcuError); if (U_SUCCESS(nIcuError) && aMatcher.matches(nIcuError) && U_SUCCESS(nIcuError)) return true; return false; } bool match(const OpenCLConfig::ImplMatcher& rListEntry, const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice) { #if defined WNT if (!rListEntry.maOS.isEmpty() && rListEntry.maOS != "Windows") return false; #elif defined LINUX if (!rListEntry.maOS.isEmpty() && rListEntry.maOS != "Linux") return false; #elif defined MACOSX if (!rListEntry.maOS.isEmpty() && rListEntry.maOS != "OS X") return false; #endif // OS version check not yet implemented if (!match(rListEntry.maPlatformVendor, rPlatform.maVendor)) return false; if (!match(rListEntry.maDevice, rDevice.maName)) return false; if (!match(rListEntry.maDriverVersion, rDevice.maDriver)) return false; return true; } bool match(const OpenCLConfig::ImplMatcherSet& rList, const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice, const char* sKindOfList) { for (auto i = rList.cbegin(); i != rList.end(); ++i) { SAL_INFO("opencl", "Looking for match for platform=" << rPlatform << ", device=" << rDevice << " in " << sKindOfList << " entry=" << *i); if (match(*i, rPlatform, rDevice)) { SAL_INFO("opencl", "Match!"); return true; } } return false; } } // anonymous namespace OpenCLConfig OpenCLConfig::get() { OpenCLConfig result; result.mbUseOpenCL = officecfg::Office::Common::Misc::UseOpenCL::get(); result.maBlackList = StringSequenceToSetOfImplMatcher(officecfg::Office::Common::Misc::OpenCLBlackList::get()); result.maWhiteList = StringSequenceToSetOfImplMatcher(officecfg::Office::Common::Misc::OpenCLWhiteList::get()); return result; } void OpenCLConfig::set() { boost::shared_ptr<comphelper::ConfigurationChanges> batch(comphelper::ConfigurationChanges::create()); officecfg::Office::Common::Misc::UseOpenCL::set(mbUseOpenCL, batch); officecfg::Office::Common::Misc::OpenCLBlackList::set(SetOfImplMatcherToStringSequence(maBlackList), batch); officecfg::Office::Common::Misc::OpenCLWhiteList::set(SetOfImplMatcherToStringSequence(maWhiteList), batch); batch->commit(); } bool OpenCLConfig::checkImplementation(const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice) const { // Check blacklist of known bad OpenCL implementations if (match(maBlackList, rPlatform, rDevice, "blacklist")) { SAL_INFO("opencl", "Rejecting"); return true; } // Check for whitelist of known good OpenCL implementations if (match(maWhiteList, rPlatform, rDevice, "whitelist")) { SAL_INFO("opencl", "Approving"); return false; } // Fallback: reject SAL_INFO("opencl", "Fallback: rejecting platform=" << rPlatform << ", device=" << rDevice); return true; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig& rConfig) { rStream << "{" "UseOpenCL=" << (rConfig.mbUseOpenCL ? "YES" : "NO") << "," "BlackList=" << rConfig.maBlackList << "," "WhiteList=" << rConfig.maWhiteList << "}"; return rStream; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcher& rImpl) { rStream << "{" "OS=" << rImpl.maOS << "," "OSVersion=" << rImpl.maOSVersion << "," "PlatformVendor=" << rImpl.maPlatformVendor << "," "Device=" << rImpl.maDevice << "," "DriverVersion=" << rImpl.maDriverVersion << "}"; return rStream; } std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcherSet& rSet) { rStream << "{"; for (auto i = rSet.cbegin(); i != rSet.cend(); ++i) { if (i != rSet.cbegin()) rStream << ","; rStream << *i; } rStream << "}"; return rStream; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CppSound.hpp" #include <cstdio> #include <cstring> CppSound::CppSound() : Csound(), go(false), isCompiled(false), isPerforming(false), spoutSize(0) { SetHostData((CSOUND *)0); } CppSound::~CppSound() { } int CppSound::compile(int argc, char **argv_) { Message("BEGAN CppSound::compile(%d, %p)...\n", argc, argv_); go = false; int returnValue = Compile(argc, argv_); spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT); if(returnValue) { isCompiled = false; } else { const char *outfilename = GetOutputFileName(); if (outfilename) { renderedSoundfile = outfilename; } isCompiled = true; go = true; } Message("ENDED CppSound::compile.\n"); return returnValue; } int CppSound::compile() { Message("BEGAN CppSound::compile()...\n"); if(getCommand().length() <= 0) { Message("No Csound command.\n"); return 0; } scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv)); int returnValue = compile(args.size(), &argv.front()); Message("ENDED CppSound::compile.\n"); return returnValue; } int CppSound::perform(int argc, char **argv_) { double beganAt = double(clock()) / double(CLOCKS_PER_SEC); isCompiled = false; go = false; Message("BEGAN CppSound::perform(%d, %p)...\n", argc, argv_); if(argc <= 0) { Message("ENDED CppSound::perform without compiling or performing.\n"); return 0; } int result = compile(argc, argv_); if(result == -1) { return result; } for(result = 0; (result == 0) && go; ) { result = PerformKsmps(); } cleanup(); double endedAt = double(clock()) / double(CLOCKS_PER_SEC); double elapsed = endedAt - beganAt; Message("Elapsed time = %f seconds.\n", elapsed); Message("ENDED CppSound::perform.\n"); isCompiled = false; isPerforming = false; return 1; } int CppSound::perform() { int returnValue = 0; std::string command = getCommand(); if(command.find("-") == 0) { const char *argv_[] = {"csound", getFilename().c_str(), 0}; returnValue = perform(2, (char **)argv_); } else { scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv)); returnValue = perform(args.size(), &argv.front()); } return returnValue; } void CppSound::stop() { Message("RECEIVED CppSound::stop...\n"); isCompiled = false; isPerforming = false; go = false; } CSOUND *CppSound::getCsound() { return csound; } int CppSound::performKsmps(bool absolute) { if(absolute){ return PerformKsmpsAbsolute(); } else { return PerformKsmps(); } } void CppSound::cleanup() { Cleanup(); Reset(); } size_t CppSound::getSpoutSize() const { return spoutSize; } std::string CppSound::getOutputSoundfileName() const { return renderedSoundfile; } void CppSound::inputMessage(const char *istatement) { InputMessage(istatement); } void CppSound::write(const char *text) { Message("%s", text); } long CppSound::getThis() { return (long) this; } CsoundFile *CppSound::getCsoundFile() { return dynamic_cast<CsoundFile *>(this); } bool CppSound::getIsCompiled() const { return isCompiled; } void CppSound::setIsPerforming(bool isPerforming) { this->isPerforming = isPerforming; } bool CppSound::getIsPerforming() const { return isPerforming; } bool CppSound::getIsGo() { if(csound) { if(GetSpin() && GetSpout()) { return go; } } return false; } extern "C" { int PyRun_SimpleString(const char *string); } static void pythonMessageCallback(CSOUND *csound, int attr, const char *format, va_list valist) { static char buffer[0x1000]; static char buffer1[0x1000]; vsprintf(buffer, format, valist); static std::string actualBuffer; static std::string lineBuffer; actualBuffer.append(buffer); size_t position = 0; while((position = actualBuffer.find("\n")) != std::string::npos) { lineBuffer = actualBuffer.substr(0, position); actualBuffer.erase(0, position + 1); #ifndef MSVC actualBuffer.clear(); #endif sprintf(buffer1, "print '''%s'''", lineBuffer.c_str()); PyRun_SimpleString(buffer1); } } void CppSound::setPythonMessageCallback() { SetMessageCallback(pythonMessageCallback); } <commit_msg>Implement CppSound::stop with Csound::Stop.<commit_after>/** * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CppSound.hpp" #include <cstdio> #include <cstring> CppSound::CppSound() : Csound(), go(false), isCompiled(false), isPerforming(false), spoutSize(0) { SetHostData((CSOUND *)0); } CppSound::~CppSound() { } int CppSound::compile(int argc, char **argv_) { Message("BEGAN CppSound::compile(%d, %p)...\n", argc, argv_); go = false; int returnValue = Compile(argc, argv_); spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT); if(returnValue) { isCompiled = false; } else { const char *outfilename = GetOutputFileName(); if (outfilename) { renderedSoundfile = outfilename; } isCompiled = true; go = true; } Message("ENDED CppSound::compile.\n"); return returnValue; } int CppSound::compile() { Message("BEGAN CppSound::compile()...\n"); if(getCommand().length() <= 0) { Message("No Csound command.\n"); return 0; } scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv)); int returnValue = compile(args.size(), &argv.front()); Message("ENDED CppSound::compile.\n"); return returnValue; } int CppSound::perform(int argc, char **argv_) { double beganAt = double(clock()) / double(CLOCKS_PER_SEC); isCompiled = false; go = false; Message("BEGAN CppSound::perform(%d, %p)...\n", argc, argv_); if(argc <= 0) { Message("ENDED CppSound::perform without compiling or performing.\n"); return 0; } int result = compile(argc, argv_); if(result == -1) { return result; } for(result = 0; (result == 0) && go; ) { result = PerformKsmps(); } cleanup(); double endedAt = double(clock()) / double(CLOCKS_PER_SEC); double elapsed = endedAt - beganAt; Message("Elapsed time = %f seconds.\n", elapsed); Message("ENDED CppSound::perform.\n"); isCompiled = false; isPerforming = false; return 1; } int CppSound::perform() { int returnValue = 0; std::string command = getCommand(); if(command.find("-") == 0) { const char *argv_[] = {"csound", getFilename().c_str(), 0}; returnValue = perform(2, (char **)argv_); } else { scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv)); returnValue = perform(args.size(), &argv.front()); } return returnValue; } void CppSound::stop() { Message("RECEIVED CppSound::stop...\n"); isCompiled = false; isPerforming = false; go = false; Stop(); } CSOUND *CppSound::getCsound() { return csound; } int CppSound::performKsmps(bool absolute) { if(absolute){ return PerformKsmpsAbsolute(); } else { return PerformKsmps(); } } void CppSound::cleanup() { Cleanup(); Reset(); } size_t CppSound::getSpoutSize() const { return spoutSize; } std::string CppSound::getOutputSoundfileName() const { return renderedSoundfile; } void CppSound::inputMessage(const char *istatement) { InputMessage(istatement); } void CppSound::write(const char *text) { Message("%s", text); } long CppSound::getThis() { return (long) this; } CsoundFile *CppSound::getCsoundFile() { return dynamic_cast<CsoundFile *>(this); } bool CppSound::getIsCompiled() const { return isCompiled; } void CppSound::setIsPerforming(bool isPerforming) { this->isPerforming = isPerforming; } bool CppSound::getIsPerforming() const { return isPerforming; } bool CppSound::getIsGo() { if(csound) { if(GetSpin() && GetSpout()) { return go; } } return false; } extern "C" { int PyRun_SimpleString(const char *string); } static void pythonMessageCallback(CSOUND *csound, int attr, const char *format, va_list valist) { static char buffer[0x1000]; static char buffer1[0x1000]; vsprintf(buffer, format, valist); static std::string actualBuffer; static std::string lineBuffer; actualBuffer.append(buffer); size_t position = 0; while((position = actualBuffer.find("\n")) != std::string::npos) { lineBuffer = actualBuffer.substr(0, position); actualBuffer.erase(0, position + 1); #ifndef MSVC actualBuffer.clear(); #endif sprintf(buffer1, "print '''%s'''", lineBuffer.c_str()); PyRun_SimpleString(buffer1); } } void CppSound::setPythonMessageCallback() { SetMessageCallback(pythonMessageCallback); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h" #include <memory> #include "mlir/Pass/PassManager.h" // TF:llvm-project #include "mlir/Transforms/Passes.h" // TF:llvm-project #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" namespace mlir { namespace TFTPU { void CreateTPUBridge(OpPassManager &pm) { // Run island coarsening before shape inference to allow more exact shape // inference using constant folding within islands. OpPassManager &func_pm = pm.nest<FuncOp>(); func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass()); // Run shape inference so that tf_executor/tf_device ops created later will // likely to inherit more concrete types. pm.addPass(TF::CreateTFShapeInferencePass()); func_pm.addPass(CreateTPUClusterFormationPass()); func_pm.addPass(createCanonicalizerPass()); // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass // because DecomposeResourceOpsPass uses pattern rewriter which hoists // changed constants out of tf_device.Launch. func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass()); // Run another shape inference pass because resource ecomposition might have // created new partial types. pm.addPass(TF::CreateTFShapeInferencePass()); OpPassManager &func_pm2 = pm.nest<FuncOp>(); func_pm2.addPass(tf_executor::CreateTFExecutorConstantSinkingPass()); func_pm2.addPass(TFDevice::CreateResourceOpLiftingPass()); pm.addPass(TF::CreateResourceDeviceInferencePass()); pm.addPass(TFDevice::CreateClusterOutliningPass()); pm.addPass(CreateTPUDynamicPaddingMapperPass()); pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass()); pm.addPass(CreateTPURewritePass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass()); pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass()); // TODO(b/147020076): Enable this pass. // pm.addPass(CreateTPUVariableReformattingPass()); pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); } tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) { PassManager bridge(module.getContext()); // Add logger to bridge passmanager. if (enable_logging) bridge.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); // Populate a passmanager with the list of passes that implement the bridge. CreateTPUBridge(bridge); // Run the bridge on the module, in case of failure, the `diag_handler` // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status. mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); LogicalResult result = bridge.run(module); (void)result; return diag_handler.ConsumeStatus(); } } // namespace TFTPU namespace TF { tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module, bool enable_logging, bool enable_inliner) { PassManager bridge(module.getContext()); // Add logger to bridge passmanager. if (enable_logging) bridge.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); StandardPipelineOptions pipeline_options; pipeline_options.enable_inliner.setValue(enable_inliner); CreateTFStandardPipeline(bridge, pipeline_options); mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); LogicalResult result = bridge.run(module); (void)result; return diag_handler.ConsumeStatus(); } } // namespace TF } // namespace mlir <commit_msg>Fix pass pipeline<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h" #include <memory> #include "mlir/Pass/PassManager.h" // TF:llvm-project #include "mlir/Transforms/Passes.h" // TF:llvm-project #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" namespace mlir { namespace TFTPU { void CreateTPUBridge(OpPassManager &pm) { // Run island coarsening before shape inference to allow more exact shape // inference using constant folding within islands. pm.nest<FuncOp>().addPass( tf_executor::CreateTFExecutorIslandCoarseningPass()); // Run shape inference so that tf_executor/tf_device ops created later will // likely to inherit more concrete types. pm.addPass(TF::CreateTFShapeInferencePass()); OpPassManager &func_pm = pm.nest<FuncOp>(); func_pm.addPass(CreateTPUClusterFormationPass()); func_pm.addPass(createCanonicalizerPass()); // Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass // because DecomposeResourceOpsPass uses pattern rewriter which hoists // changed constants out of tf_device.Launch. func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass()); // Run another shape inference pass because resource ecomposition might have // created new partial types. pm.addPass(TF::CreateTFShapeInferencePass()); OpPassManager &func_pm2 = pm.nest<FuncOp>(); func_pm2.addPass(tf_executor::CreateTFExecutorConstantSinkingPass()); func_pm2.addPass(TFDevice::CreateResourceOpLiftingPass()); pm.addPass(TF::CreateResourceDeviceInferencePass()); pm.addPass(TFDevice::CreateClusterOutliningPass()); pm.addPass(CreateTPUDynamicPaddingMapperPass()); pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass()); pm.addPass(CreateTPURewritePass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass()); pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass()); // TODO(b/147020076): Enable this pass. // pm.addPass(CreateTPUVariableReformattingPass()); pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass()); pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass()); } tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) { PassManager bridge(module.getContext()); // Add logger to bridge passmanager. if (enable_logging) bridge.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); // Populate a passmanager with the list of passes that implement the bridge. CreateTPUBridge(bridge); // Run the bridge on the module, in case of failure, the `diag_handler` // converts MLIR errors emitted to the MLIRContext into a tensorflow::Status. mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); LogicalResult result = bridge.run(module); (void)result; return diag_handler.ConsumeStatus(); } } // namespace TFTPU namespace TF { tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module, bool enable_logging, bool enable_inliner) { PassManager bridge(module.getContext()); // Add logger to bridge passmanager. if (enable_logging) bridge.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>()); StandardPipelineOptions pipeline_options; pipeline_options.enable_inliner.setValue(enable_inliner); CreateTFStandardPipeline(bridge, pipeline_options); mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); LogicalResult result = bridge.run(module); (void)result; return diag_handler.ConsumeStatus(); } } // namespace TF } // namespace mlir <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qgraphicsvideoitem.h" #include "qmediaobject.h" #include "qmediaservice.h" #include "qpaintervideosurface_p.h" #include "qvideooutputcontrol.h" #include "qvideorenderercontrol.h" #include <QtMultimedia/qabstractvideosurface.h> #include <QtMultimedia/qvideosurfaceformat.h> #include <QtGui/qapplication.h> #include <QtGui/qgraphicsscene.h> #include <QtGui/qgraphicsview.h> class tst_QGraphicsVideoItem : public QObject { Q_OBJECT private slots: void nullObject(); void nullService(); void nullOutputControl(); void noOutputs(); void serviceDestroyed(); void show(); void boundingRect_data(); void boundingRect(); void paint(); }; Q_DECLARE_METATYPE(const uchar *) class QtTestOutputControl : public QVideoOutputControl { public: QtTestOutputControl() : m_output(NoOutput) {} QList<Output> availableOutputs() const { return m_outputs; } void setAvailableOutputs(const QList<Output> outputs) { m_outputs = outputs; } Output output() const { return m_output; } virtual void setOutput(Output output) { m_output = output; } private: Output m_output; QList<Output> m_outputs; }; class QtTestRendererControl : public QVideoRendererControl { public: QtTestRendererControl() : m_surface(0) { } QAbstractVideoSurface *surface() const { return m_surface; } void setSurface(QAbstractVideoSurface *surface) { m_surface = surface; } private: QAbstractVideoSurface *m_surface; }; class QtTestVideoService : public QMediaService { Q_OBJECT public: QtTestVideoService( QtTestOutputControl *output, QtTestRendererControl *renderer) : QMediaService(0) , outputControl(output) , rendererControl(renderer) { } ~QtTestVideoService() { delete outputControl; delete rendererControl; } QMediaControl *control(const char *name) const { if (qstrcmp(name, QVideoOutputControl_iid) == 0) return outputControl; else if (qstrcmp(name, QVideoRendererControl_iid) == 0) return rendererControl; else return 0; } QtTestOutputControl *outputControl; QtTestRendererControl *rendererControl; }; class QtTestVideoObject : public QMediaObject { Q_OBJECT public: QtTestVideoObject(QtTestRendererControl *renderer): QMediaObject(0, new QtTestVideoService(new QtTestOutputControl, renderer)) { testService = qobject_cast<QtTestVideoService*>(service()); QList<QVideoOutputControl::Output> outputs; if (renderer) outputs.append(QVideoOutputControl::RendererOutput); testService->outputControl->setAvailableOutputs(outputs); } QtTestVideoObject(QtTestVideoService *service): QMediaObject(0, service), testService(service) { } ~QtTestVideoObject() { delete testService; } QtTestVideoService *testService; }; class QtTestGraphicsVideoItem : public QGraphicsVideoItem { public: QtTestGraphicsVideoItem(QMediaObject *object, QGraphicsItem *parent = 0) : QGraphicsVideoItem(object, parent) , m_paintCount(0) { } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { ++m_paintCount; QTestEventLoop::instance().exitLoop(); QGraphicsVideoItem::paint(painter, option, widget); } bool waitForPaint(int secs) { const int paintCount = m_paintCount; QTestEventLoop::instance().enterLoop(secs); return m_paintCount != paintCount; } int paintCount() const { return m_paintCount; } private: int m_paintCount; }; void tst_QGraphicsVideoItem::nullObject() { QGraphicsVideoItem item(0); QVERIFY(item.boundingRect().isEmpty()); } void tst_QGraphicsVideoItem::nullService() { QtTestVideoService *service = 0; QtTestVideoObject object(service); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); item->show(); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::nullOutputControl() { QtTestVideoObject object(new QtTestVideoService(0, 0)); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); item->show(); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::noOutputs() { QtTestRendererControl *control = 0; QtTestVideoObject object(control); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); item->show(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::serviceDestroyed() { QtTestVideoObject *object = new QtTestVideoObject(new QtTestRendererControl); QGraphicsVideoItem item(object); delete object; QVERIFY(item.boundingRect().isEmpty()); } void tst_QGraphicsVideoItem::show() { QtTestVideoObject object(new QtTestRendererControl); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); // Graphics items are visible by default QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::RendererOutput); QVERIFY(object.testService->rendererControl->surface() != 0); item->hide(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); item->show(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::RendererOutput); QVERIFY(object.testService->rendererControl->surface() != 0); QVERIFY(item->boundingRect().isEmpty()); QVideoSurfaceFormat format(QSize(320,240),QVideoFrame::Format_RGB32); QVERIFY(object.testService->rendererControl->surface()->start(format)); QVERIFY(!item->boundingRect().isEmpty()); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); QVERIFY(item->paintCount() || item->waitForPaint(1)); } void tst_QGraphicsVideoItem::boundingRect_data() { QTest::addColumn<QSize>("frameSize"); QTest::addColumn<QRect>("viewport"); QTest::addColumn<QSize>("pixelAspectRatio"); QTest::addColumn<QRectF>("expectedRect"); QTest::newRow("640x480") << QSize(640, 480) << QRect(0, 0, 640, 480) << QSize(1, 1) << QRectF(-319, -239, 640, 480); QTest::newRow("800x600, (80,60, 640x480) viewport") << QSize(800, 600) << QRect(80, 60, 640, 480) << QSize(1, 1) << QRectF(-319,-239, 640, 480); QTest::newRow("800x600, (80,60, 640x480) viewport, 4:3") << QSize(800, 600) << QRect(80, 60, 640, 480) << QSize(4, 3) << QRectF(-426, -239, 853, 480); } void tst_QGraphicsVideoItem::boundingRect() { QFETCH(QSize, frameSize); QFETCH(QRect, viewport); QFETCH(QSize, pixelAspectRatio); QFETCH(QRectF, expectedRect); QtTestVideoObject object(new QtTestRendererControl); QGraphicsVideoItem item(&object); QVideoSurfaceFormat format(frameSize, QVideoFrame::Format_ARGB32); format.setViewport(viewport); format.setPixelAspectRatio(pixelAspectRatio); QVERIFY(object.testService->rendererControl->surface()->start(format)); QCOMPARE(item.boundingRect(), expectedRect); } static const uchar rgb32ImageData[] = { 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00 }; void tst_QGraphicsVideoItem::paint() { QtTestVideoObject object(new QtTestRendererControl); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); QPainterVideoSurface *surface = qobject_cast<QPainterVideoSurface *>( object.testService->rendererControl->surface()); QVideoSurfaceFormat format(QSize(2, 2), QVideoFrame::Format_RGB32); QVERIFY(surface->start(format)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); QVERIFY(item->waitForPaint(1)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); QVideoFrame frame(sizeof(rgb32ImageData), QSize(2, 2), 8, QVideoFrame::Format_RGB32); frame.map(QAbstractVideoBuffer::WriteOnly); memcpy(frame.bits(), rgb32ImageData, frame.mappedBytes()); frame.unmap(); QVERIFY(surface->present(frame)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), false); QVERIFY(item->waitForPaint(1)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); } QTEST_MAIN(tst_QGraphicsVideoItem) #include "tst_qgraphicsvideoitem.moc" <commit_msg>more missing export symbols when building unit tests<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qmultimediaglobal.h> #include <QtTest/QtTest> #include "qgraphicsvideoitem.h" #include "qmediaobject.h" #include "qmediaservice.h" #include "qpaintervideosurface_p.h" #include "qvideooutputcontrol.h" #include "qvideorenderercontrol.h" #include <QtMultimedia/qabstractvideosurface.h> #include <QtMultimedia/qvideosurfaceformat.h> #include <QtGui/qapplication.h> #include <QtGui/qgraphicsscene.h> #include <QtGui/qgraphicsview.h> class tst_QGraphicsVideoItem : public QObject { Q_OBJECT private slots: void nullObject(); void nullService(); void nullOutputControl(); void noOutputs(); void serviceDestroyed(); void show(); void boundingRect_data(); void boundingRect(); void paint(); }; Q_DECLARE_METATYPE(const uchar *) class QtTestOutputControl : public QVideoOutputControl { public: QtTestOutputControl() : m_output(NoOutput) {} QList<Output> availableOutputs() const { return m_outputs; } void setAvailableOutputs(const QList<Output> outputs) { m_outputs = outputs; } Output output() const { return m_output; } virtual void setOutput(Output output) { m_output = output; } private: Output m_output; QList<Output> m_outputs; }; class QtTestRendererControl : public QVideoRendererControl { public: QtTestRendererControl() : m_surface(0) { } QAbstractVideoSurface *surface() const { return m_surface; } void setSurface(QAbstractVideoSurface *surface) { m_surface = surface; } private: QAbstractVideoSurface *m_surface; }; class QtTestVideoService : public QMediaService { Q_OBJECT public: QtTestVideoService( QtTestOutputControl *output, QtTestRendererControl *renderer) : QMediaService(0) , outputControl(output) , rendererControl(renderer) { } ~QtTestVideoService() { delete outputControl; delete rendererControl; } QMediaControl *control(const char *name) const { if (qstrcmp(name, QVideoOutputControl_iid) == 0) return outputControl; else if (qstrcmp(name, QVideoRendererControl_iid) == 0) return rendererControl; else return 0; } QtTestOutputControl *outputControl; QtTestRendererControl *rendererControl; }; class QtTestVideoObject : public QMediaObject { Q_OBJECT public: QtTestVideoObject(QtTestRendererControl *renderer): QMediaObject(0, new QtTestVideoService(new QtTestOutputControl, renderer)) { testService = qobject_cast<QtTestVideoService*>(service()); QList<QVideoOutputControl::Output> outputs; if (renderer) outputs.append(QVideoOutputControl::RendererOutput); testService->outputControl->setAvailableOutputs(outputs); } QtTestVideoObject(QtTestVideoService *service): QMediaObject(0, service), testService(service) { } ~QtTestVideoObject() { delete testService; } QtTestVideoService *testService; }; class QtTestGraphicsVideoItem : public QGraphicsVideoItem { public: QtTestGraphicsVideoItem(QMediaObject *object, QGraphicsItem *parent = 0) : QGraphicsVideoItem(object, parent) , m_paintCount(0) { } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { ++m_paintCount; QTestEventLoop::instance().exitLoop(); QGraphicsVideoItem::paint(painter, option, widget); } bool waitForPaint(int secs) { const int paintCount = m_paintCount; QTestEventLoop::instance().enterLoop(secs); return m_paintCount != paintCount; } int paintCount() const { return m_paintCount; } private: int m_paintCount; }; void tst_QGraphicsVideoItem::nullObject() { QGraphicsVideoItem item(0); QVERIFY(item.boundingRect().isEmpty()); } void tst_QGraphicsVideoItem::nullService() { QtTestVideoService *service = 0; QtTestVideoObject object(service); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); item->show(); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::nullOutputControl() { QtTestVideoObject object(new QtTestVideoService(0, 0)); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); item->show(); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::noOutputs() { QtTestRendererControl *control = 0; QtTestVideoObject object(control); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QVERIFY(item->boundingRect().isEmpty()); item->hide(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); item->show(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); } void tst_QGraphicsVideoItem::serviceDestroyed() { QtTestVideoObject *object = new QtTestVideoObject(new QtTestRendererControl); QGraphicsVideoItem item(object); delete object; QVERIFY(item.boundingRect().isEmpty()); } void tst_QGraphicsVideoItem::show() { QtTestVideoObject object(new QtTestRendererControl); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); // Graphics items are visible by default QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::RendererOutput); QVERIFY(object.testService->rendererControl->surface() != 0); item->hide(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::NoOutput); item->show(); QCOMPARE(object.testService->outputControl->output(), QVideoOutputControl::RendererOutput); QVERIFY(object.testService->rendererControl->surface() != 0); QVERIFY(item->boundingRect().isEmpty()); QVideoSurfaceFormat format(QSize(320,240),QVideoFrame::Format_RGB32); QVERIFY(object.testService->rendererControl->surface()->start(format)); QVERIFY(!item->boundingRect().isEmpty()); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); QVERIFY(item->paintCount() || item->waitForPaint(1)); } void tst_QGraphicsVideoItem::boundingRect_data() { QTest::addColumn<QSize>("frameSize"); QTest::addColumn<QRect>("viewport"); QTest::addColumn<QSize>("pixelAspectRatio"); QTest::addColumn<QRectF>("expectedRect"); QTest::newRow("640x480") << QSize(640, 480) << QRect(0, 0, 640, 480) << QSize(1, 1) << QRectF(-319, -239, 640, 480); QTest::newRow("800x600, (80,60, 640x480) viewport") << QSize(800, 600) << QRect(80, 60, 640, 480) << QSize(1, 1) << QRectF(-319,-239, 640, 480); QTest::newRow("800x600, (80,60, 640x480) viewport, 4:3") << QSize(800, 600) << QRect(80, 60, 640, 480) << QSize(4, 3) << QRectF(-426, -239, 853, 480); } void tst_QGraphicsVideoItem::boundingRect() { QFETCH(QSize, frameSize); QFETCH(QRect, viewport); QFETCH(QSize, pixelAspectRatio); QFETCH(QRectF, expectedRect); QtTestVideoObject object(new QtTestRendererControl); QGraphicsVideoItem item(&object); QVideoSurfaceFormat format(frameSize, QVideoFrame::Format_ARGB32); format.setViewport(viewport); format.setPixelAspectRatio(pixelAspectRatio); QVERIFY(object.testService->rendererControl->surface()->start(format)); QCOMPARE(item.boundingRect(), expectedRect); } static const uchar rgb32ImageData[] = { 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00 }; void tst_QGraphicsVideoItem::paint() { QtTestVideoObject object(new QtTestRendererControl); QtTestGraphicsVideoItem *item = new QtTestGraphicsVideoItem(&object); QGraphicsScene graphicsScene; graphicsScene.addItem(item); QGraphicsView graphicsView(&graphicsScene); graphicsView.show(); QPainterVideoSurface *surface = qobject_cast<QPainterVideoSurface *>( object.testService->rendererControl->surface()); QVideoSurfaceFormat format(QSize(2, 2), QVideoFrame::Format_RGB32); QVERIFY(surface->start(format)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); QVERIFY(item->waitForPaint(1)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); QVideoFrame frame(sizeof(rgb32ImageData), QSize(2, 2), 8, QVideoFrame::Format_RGB32); frame.map(QAbstractVideoBuffer::WriteOnly); memcpy(frame.bits(), rgb32ImageData, frame.mappedBytes()); frame.unmap(); QVERIFY(surface->present(frame)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), false); QVERIFY(item->waitForPaint(1)); QCOMPARE(surface->isActive(), true); QCOMPARE(surface->isReady(), true); } QTEST_MAIN(tst_QGraphicsVideoItem) #include "tst_qgraphicsvideoitem.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); void tst_interfaceForMode(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } else { QVERIFY(ni.currentMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.currentMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } else { QVERIFY(ni.homeMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.homeMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty() ||ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } void tst_QSystemNetworkInfo::tst_interfaceForMode() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.interfaceForMode(mode).name().isEmpty() || !ni.interfaceForMode(mode).isValid()); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <commit_msg>Modified tst_qsystemnetworkinfo.cpp autotest again<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); void tst_interfaceForMode(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } else { QVERIFY(ni.currentMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.currentMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } else { QVERIFY(ni.homeMobileCountryCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; if(QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::HomeNetwork == ni.networkStatus(QSystemNetworkInfo::WcdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::GsmMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::CdmaMode) || QSystemNetworkInfo::Roaming == ni.networkStatus(QSystemNetworkInfo::WcdmaMode)) { QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } else { QVERIFY(ni.homeMobileNetworkCode().isEmpty()); } } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty() ||ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } void tst_QSystemNetworkInfo::tst_interfaceForMode() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.interfaceForMode(mode).name().isEmpty() || !ni.interfaceForMode(mode).isValid()); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <|endoftext|>
<commit_before>//===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements the execution engine for MLIR modules based on LLVM Orc // JIT engine. // //===----------------------------------------------------------------------===// #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/IR/Function.h" #include "mlir/IR/Module.h" #include "mlir/Target/LLVMIR.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/TargetRegistry.h" using namespace mlir; using llvm::Error; using llvm::Expected; namespace { // Memory manager for the JIT's objectLayer. Its main goal is to fallback to // resolving functions in the current process if they cannot be resolved in the // JIT-compiled modules. class MemoryManager : public llvm::SectionMemoryManager { public: MemoryManager(llvm::orc::ExecutionSession &execSession) : session(execSession) {} // Resolve the named symbol. First, try looking it up in the main library of // the execution session. If there is no such symbol, try looking it up in // the current process (for example, if it is a standard library function). // Return `nullptr` if lookup fails. llvm::JITSymbol findSymbol(const std::string &name) override { auto mainLibSymbol = session.lookup({&session.getMainJITDylib()}, name); if (mainLibSymbol) return mainLibSymbol.get(); auto address = llvm::RTDyldMemoryManager::getSymbolAddressInProcess(name); if (!address) { llvm::errs() << "Could not look up: " << name << '\n'; return nullptr; } return llvm::JITSymbol(address, llvm::JITSymbolFlags::Exported); } private: llvm::orc::ExecutionSession &session; }; } // end anonymous namespace namespace mlir { namespace impl { /// Wrapper class around DynamicLibrarySearchGenerator to allow searching /// in-process symbols that have not been explicitly exported. /// This first tries to resolve a symbol by using DynamicLibrarySearchGenerator. /// For symbols that are not found this way, it then uses /// `llvm::sys::DynamicLibrary::SearchForAddressOfSymbol` to extract symbols /// that have been explicitly added with `llvm::sys::DynamicLibrary::AddSymbol`, /// previously. class SearchGenerator { public: SearchGenerator(char GlobalPrefix) : defaultGenerator(cantFail( llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( GlobalPrefix))) {} // This function forwards to DynamicLibrarySearchGenerator::operator() and // adds an extra resolution for names explicitly registered via // `llvm::sys::DynamicLibrary::AddSymbol`. Expected<llvm::orc::SymbolNameSet> operator()(llvm::orc::JITDylib &JD, const llvm::orc::SymbolNameSet &Names) { auto res = defaultGenerator(JD, Names); if (!res) return res; llvm::orc::SymbolMap newSymbols; for (auto &Name : Names) { if (res.get().count(Name) > 0) continue; res.get().insert(Name); auto addedSymbolAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(*Name); if (!addedSymbolAddress) continue; llvm::JITEvaluatedSymbol Sym( reinterpret_cast<uintptr_t>(addedSymbolAddress), llvm::JITSymbolFlags::Exported); newSymbols[Name] = Sym; } if (!newSymbols.empty()) cantFail(JD.define(absoluteSymbols(std::move(newSymbols)))); return res; } private: llvm::orc::DynamicLibrarySearchGenerator defaultGenerator; }; // Simple layered Orc JIT compilation engine. class OrcJIT { public: using IRTransformer = std::function<Error(llvm::Module *)>; // Construct a JIT engine for the target host defined by `machineBuilder`, // using the data layout provided as `dataLayout`. // Setup the object layer to use our custom memory manager in order to // resolve calls to library functions present in the process. OrcJIT(llvm::orc::JITTargetMachineBuilder machineBuilder, llvm::DataLayout layout, IRTransformer transform, ArrayRef<StringRef> sharedLibPaths) : irTransformer(transform), objectLayer( session, [this]() { return llvm::make_unique<MemoryManager>(session); }), compileLayer( session, objectLayer, llvm::orc::ConcurrentIRCompiler(std::move(machineBuilder))), transformLayer(session, compileLayer, makeIRTransformFunction()), dataLayout(layout), mangler(session, this->dataLayout), threadSafeCtx(llvm::make_unique<llvm::LLVMContext>()) { session.getMainJITDylib().setGenerator( SearchGenerator(layout.getGlobalPrefix())); loadLibraries(sharedLibPaths); } // Create a JIT engine for the current host. static Expected<std::unique_ptr<OrcJIT>> createDefault(IRTransformer transformer, ArrayRef<StringRef> sharedLibPaths) { auto machineBuilder = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!machineBuilder) return machineBuilder.takeError(); auto dataLayout = machineBuilder->getDefaultDataLayoutForTarget(); if (!dataLayout) return dataLayout.takeError(); return llvm::make_unique<OrcJIT>(std::move(*machineBuilder), std::move(*dataLayout), transformer, sharedLibPaths); } // Add an LLVM module to the main library managed by the JIT engine. Error addModule(std::unique_ptr<llvm::Module> M) { return transformLayer.add( session.getMainJITDylib(), llvm::orc::ThreadSafeModule(std::move(M), threadSafeCtx)); } // Lookup a symbol in the main library managed by the JIT engine. Expected<llvm::JITEvaluatedSymbol> lookup(StringRef Name) { return session.lookup({&session.getMainJITDylib()}, mangler(Name.str())); } private: // Wrap the `irTransformer` into a function that can be called by the // IRTranformLayer. If `irTransformer` is not set up, return the module as // is without errors. llvm::orc::IRTransformLayer::TransformFunction makeIRTransformFunction() { return [this](llvm::orc::ThreadSafeModule module, const llvm::orc::MaterializationResponsibility &resp) -> Expected<llvm::orc::ThreadSafeModule> { (void)resp; if (!irTransformer) return std::move(module); if (Error err = irTransformer(module.getModule())) return std::move(err); return std::move(module); }; } // Iterate over shareLibPaths and load the corresponding libraries for symbol // resolution. void loadLibraries(ArrayRef<StringRef> sharedLibPaths); IRTransformer irTransformer; llvm::orc::ExecutionSession session; llvm::orc::RTDyldObjectLinkingLayer objectLayer; llvm::orc::IRCompileLayer compileLayer; llvm::orc::IRTransformLayer transformLayer; llvm::DataLayout dataLayout; llvm::orc::MangleAndInterner mangler; llvm::orc::ThreadSafeContext threadSafeCtx; }; } // end namespace impl } // namespace mlir void mlir::impl::OrcJIT::loadLibraries(ArrayRef<StringRef> sharedLibPaths) { for (auto libPath : sharedLibPaths) { auto mb = llvm::MemoryBuffer::getFile(libPath); if (!mb) { llvm::errs() << "Could not create MemoryBuffer for: " << libPath << " " << mb.getError().message() << "\n"; continue; } auto &JD = session.createJITDylib(libPath); auto loaded = llvm::orc::DynamicLibrarySearchGenerator::Load( libPath.data(), dataLayout.getGlobalPrefix()); if (!loaded) { llvm::errs() << "Could not load: " << libPath << " " << loaded.takeError() << "\n"; continue; } JD.setGenerator(loaded.get()); auto res = objectLayer.add(JD, std::move(mb.get())); if (res) llvm::errs() << "Could not add: " << libPath << " " << res << "\n"; } } // Wrap a string into an llvm::StringError. static inline Error make_string_error(const llvm::Twine &message) { return llvm::make_error<llvm::StringError>(message.str(), llvm::inconvertibleErrorCode()); } // Setup LLVM target triple from the current machine. bool ExecutionEngine::setupTargetTriple(llvm::Module *llvmModule) { // Setup the machine properties from the current architecture. auto targetTriple = llvm::sys::getDefaultTargetTriple(); std::string errorMessage; auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); if (!target) { llvm::errs() << "NO target: " << errorMessage << "\n"; return true; } auto machine = target->createTargetMachine(targetTriple, "generic", "", {}, {}); llvmModule->setDataLayout(machine->createDataLayout()); llvmModule->setTargetTriple(targetTriple); return false; } static std::string makePackedFunctionName(StringRef name) { return "_mlir_" + name.str(); } // For each function in the LLVM module, define an interface function that wraps // all the arguments of the original function and all its results into an i8** // pointer to provide a unified invocation interface. void packFunctionArguments(llvm::Module *module) { auto &ctx = module->getContext(); llvm::IRBuilder<> builder(ctx); llvm::DenseSet<llvm::Function *> interfaceFunctions; for (auto &func : module->getFunctionList()) { if (func.isDeclaration()) { continue; } if (interfaceFunctions.count(&func)) { continue; } // Given a function `foo(<...>)`, define the interface function // `mlir_foo(i8**)`. auto newType = llvm::FunctionType::get( builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), /*isVarArg=*/false); auto newName = makePackedFunctionName(func.getName()); auto funcCst = module->getOrInsertFunction(newName, newType); llvm::Function *interfaceFunc = llvm::cast<llvm::Function>(funcCst.getCallee()); interfaceFunctions.insert(interfaceFunc); // Extract the arguments from the type-erased argument list and cast them to // the proper types. auto bb = llvm::BasicBlock::Create(ctx); bb->insertInto(interfaceFunc); builder.SetInsertPoint(bb); llvm::Value *argList = interfaceFunc->arg_begin(); llvm::SmallVector<llvm::Value *, 8> args; args.reserve(llvm::size(func.args())); for (auto &indexedArg : llvm::enumerate(func.args())) { llvm::Value *argIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); argPtr = builder.CreateBitCast( argPtr, indexedArg.value().getType()->getPointerTo()); llvm::Value *arg = builder.CreateLoad(argPtr); args.push_back(arg); } // Call the implementation function with the extracted arguments. llvm::Value *result = builder.CreateCall(&func, args); // Assuming the result is one value, potentially of type `void`. if (!result->getType()->isVoidTy()) { llvm::Value *retIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); builder.CreateStore(result, retPtr); } // The interface function returns void. builder.CreateRetVoid(); } } // Out of line for PIMPL unique_ptr. ExecutionEngine::~ExecutionEngine() = default; Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create(ModuleOp m, std::function<llvm::Error(llvm::Module *)> transformer, ArrayRef<StringRef> sharedLibPaths) { auto engine = llvm::make_unique<ExecutionEngine>(); auto expectedJIT = impl::OrcJIT::createDefault(transformer, sharedLibPaths); if (!expectedJIT) return expectedJIT.takeError(); auto llvmModule = translateModuleToLLVMIR(m); if (!llvmModule) return make_string_error("could not convert to LLVM IR"); // FIXME: the triple should be passed to the translation or dialect conversion // instead of this. Currently, the LLVM module created above has no triple // associated with it. setupTargetTriple(llvmModule.get()); packFunctionArguments(llvmModule.get()); if (auto err = (*expectedJIT)->addModule(std::move(llvmModule))) return std::move(err); engine->jit = std::move(*expectedJIT); return std::move(engine); } Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); if (!expectedSymbol) return expectedSymbol.takeError(); auto rawFPtr = expectedSymbol->getAddress(); auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); if (!fptr) return make_string_error("looked up function is null"); return fptr; } llvm::Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { auto expectedFPtr = lookup(name); if (!expectedFPtr) return expectedFPtr.takeError(); auto fptr = *expectedFPtr; (*fptr)(args.data()); return llvm::Error::success(); } <commit_msg>Fix ExecutionEngine post-update in upstream LLVM<commit_after>//===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements the execution engine for MLIR modules based on LLVM Orc // JIT engine. // //===----------------------------------------------------------------------===// #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/IR/Function.h" #include "mlir/IR/Module.h" #include "mlir/Target/LLVMIR.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/TargetRegistry.h" using namespace mlir; using llvm::Error; using llvm::Expected; namespace { // Memory manager for the JIT's objectLayer. Its main goal is to fallback to // resolving functions in the current process if they cannot be resolved in the // JIT-compiled modules. class MemoryManager : public llvm::SectionMemoryManager { public: MemoryManager(llvm::orc::ExecutionSession &execSession) : session(execSession) {} // Resolve the named symbol. First, try looking it up in the main library of // the execution session. If there is no such symbol, try looking it up in // the current process (for example, if it is a standard library function). // Return `nullptr` if lookup fails. llvm::JITSymbol findSymbol(const std::string &name) override { auto mainLibSymbol = session.lookup({&session.getMainJITDylib()}, name); if (mainLibSymbol) return mainLibSymbol.get(); auto address = llvm::RTDyldMemoryManager::getSymbolAddressInProcess(name); if (!address) { llvm::errs() << "Could not look up: " << name << '\n'; return nullptr; } return llvm::JITSymbol(address, llvm::JITSymbolFlags::Exported); } private: llvm::orc::ExecutionSession &session; }; } // end anonymous namespace namespace mlir { namespace impl { /// Wrapper class around DynamicLibrarySearchGenerator to allow searching /// in-process symbols that have not been explicitly exported. /// This first tries to resolve a symbol by using DynamicLibrarySearchGenerator. /// For symbols that are not found this way, it then uses /// `llvm::sys::DynamicLibrary::SearchForAddressOfSymbol` to extract symbols /// that have been explicitly added with `llvm::sys::DynamicLibrary::AddSymbol`, /// previously. class SearchGenerator { public: SearchGenerator(char GlobalPrefix) : defaultGenerator(cantFail( llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( GlobalPrefix))) {} // This function forwards to DynamicLibrarySearchGenerator::operator() and // adds an extra resolution for names explicitly registered via // `llvm::sys::DynamicLibrary::AddSymbol`. Expected<llvm::orc::SymbolNameSet> operator()(llvm::orc::JITDylib &JD, const llvm::orc::SymbolNameSet &Names) { auto res = defaultGenerator(JD, Names); if (!res) return res; llvm::orc::SymbolMap newSymbols; for (auto &Name : Names) { if (res.get().count(Name) > 0) continue; res.get().insert(Name); auto addedSymbolAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(*Name); if (!addedSymbolAddress) continue; llvm::JITEvaluatedSymbol Sym( reinterpret_cast<uintptr_t>(addedSymbolAddress), llvm::JITSymbolFlags::Exported); newSymbols[Name] = Sym; } if (!newSymbols.empty()) cantFail(JD.define(absoluteSymbols(std::move(newSymbols)))); return res; } private: llvm::orc::DynamicLibrarySearchGenerator defaultGenerator; }; // Simple layered Orc JIT compilation engine. class OrcJIT { public: using IRTransformer = std::function<Error(llvm::Module *)>; // Construct a JIT engine for the target host defined by `machineBuilder`, // using the data layout provided as `dataLayout`. // Setup the object layer to use our custom memory manager in order to // resolve calls to library functions present in the process. OrcJIT(llvm::orc::JITTargetMachineBuilder machineBuilder, llvm::DataLayout layout, IRTransformer transform, ArrayRef<StringRef> sharedLibPaths) : irTransformer(transform), objectLayer( session, [this]() { return llvm::make_unique<MemoryManager>(session); }), compileLayer( session, objectLayer, llvm::orc::ConcurrentIRCompiler(std::move(machineBuilder))), transformLayer(session, compileLayer, makeIRTransformFunction()), dataLayout(layout), mangler(session, this->dataLayout), threadSafeCtx(llvm::make_unique<llvm::LLVMContext>()) { session.getMainJITDylib().setGenerator( SearchGenerator(layout.getGlobalPrefix())); loadLibraries(sharedLibPaths); } // Create a JIT engine for the current host. static Expected<std::unique_ptr<OrcJIT>> createDefault(IRTransformer transformer, ArrayRef<StringRef> sharedLibPaths) { auto machineBuilder = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!machineBuilder) return machineBuilder.takeError(); auto dataLayout = machineBuilder->getDefaultDataLayoutForTarget(); if (!dataLayout) return dataLayout.takeError(); return llvm::make_unique<OrcJIT>(std::move(*machineBuilder), std::move(*dataLayout), transformer, sharedLibPaths); } // Add an LLVM module to the main library managed by the JIT engine. Error addModule(std::unique_ptr<llvm::Module> M) { return transformLayer.add( session.getMainJITDylib(), llvm::orc::ThreadSafeModule(std::move(M), threadSafeCtx)); } // Lookup a symbol in the main library managed by the JIT engine. Expected<llvm::JITEvaluatedSymbol> lookup(StringRef Name) { return session.lookup({&session.getMainJITDylib()}, mangler(Name.str())); } private: // Wrap the `irTransformer` into a function that can be called by the // IRTranformLayer. If `irTransformer` is not set up, return the module as // is without errors. llvm::orc::IRTransformLayer::TransformFunction makeIRTransformFunction() { return [this](llvm::orc::ThreadSafeModule module, const llvm::orc::MaterializationResponsibility &resp) -> Expected<llvm::orc::ThreadSafeModule> { (void)resp; if (!irTransformer) return std::move(module); Error err = module.withModuleDo( [this](llvm::Module &module) { return irTransformer(&module); }); if (err) return std::move(err); return std::move(module); }; } // Iterate over shareLibPaths and load the corresponding libraries for symbol // resolution. void loadLibraries(ArrayRef<StringRef> sharedLibPaths); IRTransformer irTransformer; llvm::orc::ExecutionSession session; llvm::orc::RTDyldObjectLinkingLayer objectLayer; llvm::orc::IRCompileLayer compileLayer; llvm::orc::IRTransformLayer transformLayer; llvm::DataLayout dataLayout; llvm::orc::MangleAndInterner mangler; llvm::orc::ThreadSafeContext threadSafeCtx; }; } // end namespace impl } // namespace mlir void mlir::impl::OrcJIT::loadLibraries(ArrayRef<StringRef> sharedLibPaths) { for (auto libPath : sharedLibPaths) { auto mb = llvm::MemoryBuffer::getFile(libPath); if (!mb) { llvm::errs() << "Could not create MemoryBuffer for: " << libPath << " " << mb.getError().message() << "\n"; continue; } auto &JD = session.createJITDylib(libPath); auto loaded = llvm::orc::DynamicLibrarySearchGenerator::Load( libPath.data(), dataLayout.getGlobalPrefix()); if (!loaded) { llvm::errs() << "Could not load: " << libPath << " " << loaded.takeError() << "\n"; continue; } JD.setGenerator(loaded.get()); auto res = objectLayer.add(JD, std::move(mb.get())); if (res) llvm::errs() << "Could not add: " << libPath << " " << res << "\n"; } } // Wrap a string into an llvm::StringError. static inline Error make_string_error(const llvm::Twine &message) { return llvm::make_error<llvm::StringError>(message.str(), llvm::inconvertibleErrorCode()); } // Setup LLVM target triple from the current machine. bool ExecutionEngine::setupTargetTriple(llvm::Module *llvmModule) { // Setup the machine properties from the current architecture. auto targetTriple = llvm::sys::getDefaultTargetTriple(); std::string errorMessage; auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); if (!target) { llvm::errs() << "NO target: " << errorMessage << "\n"; return true; } auto machine = target->createTargetMachine(targetTriple, "generic", "", {}, {}); llvmModule->setDataLayout(machine->createDataLayout()); llvmModule->setTargetTriple(targetTriple); return false; } static std::string makePackedFunctionName(StringRef name) { return "_mlir_" + name.str(); } // For each function in the LLVM module, define an interface function that wraps // all the arguments of the original function and all its results into an i8** // pointer to provide a unified invocation interface. void packFunctionArguments(llvm::Module *module) { auto &ctx = module->getContext(); llvm::IRBuilder<> builder(ctx); llvm::DenseSet<llvm::Function *> interfaceFunctions; for (auto &func : module->getFunctionList()) { if (func.isDeclaration()) { continue; } if (interfaceFunctions.count(&func)) { continue; } // Given a function `foo(<...>)`, define the interface function // `mlir_foo(i8**)`. auto newType = llvm::FunctionType::get( builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), /*isVarArg=*/false); auto newName = makePackedFunctionName(func.getName()); auto funcCst = module->getOrInsertFunction(newName, newType); llvm::Function *interfaceFunc = llvm::cast<llvm::Function>(funcCst.getCallee()); interfaceFunctions.insert(interfaceFunc); // Extract the arguments from the type-erased argument list and cast them to // the proper types. auto bb = llvm::BasicBlock::Create(ctx); bb->insertInto(interfaceFunc); builder.SetInsertPoint(bb); llvm::Value *argList = interfaceFunc->arg_begin(); llvm::SmallVector<llvm::Value *, 8> args; args.reserve(llvm::size(func.args())); for (auto &indexedArg : llvm::enumerate(func.args())) { llvm::Value *argIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); argPtr = builder.CreateBitCast( argPtr, indexedArg.value().getType()->getPointerTo()); llvm::Value *arg = builder.CreateLoad(argPtr); args.push_back(arg); } // Call the implementation function with the extracted arguments. llvm::Value *result = builder.CreateCall(&func, args); // Assuming the result is one value, potentially of type `void`. if (!result->getType()->isVoidTy()) { llvm::Value *retIndex = llvm::Constant::getIntegerValue( builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); builder.CreateStore(result, retPtr); } // The interface function returns void. builder.CreateRetVoid(); } } // Out of line for PIMPL unique_ptr. ExecutionEngine::~ExecutionEngine() = default; Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create(ModuleOp m, std::function<llvm::Error(llvm::Module *)> transformer, ArrayRef<StringRef> sharedLibPaths) { auto engine = llvm::make_unique<ExecutionEngine>(); auto expectedJIT = impl::OrcJIT::createDefault(transformer, sharedLibPaths); if (!expectedJIT) return expectedJIT.takeError(); auto llvmModule = translateModuleToLLVMIR(m); if (!llvmModule) return make_string_error("could not convert to LLVM IR"); // FIXME: the triple should be passed to the translation or dialect conversion // instead of this. Currently, the LLVM module created above has no triple // associated with it. setupTargetTriple(llvmModule.get()); packFunctionArguments(llvmModule.get()); if (auto err = (*expectedJIT)->addModule(std::move(llvmModule))) return std::move(err); engine->jit = std::move(*expectedJIT); return std::move(engine); } Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); if (!expectedSymbol) return expectedSymbol.takeError(); auto rawFPtr = expectedSymbol->getAddress(); auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); if (!fptr) return make_string_error("looked up function is null"); return fptr; } llvm::Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { auto expectedFPtr = lookup(name); if (!expectedFPtr) return expectedFPtr.takeError(); auto fptr = *expectedFPtr; (*fptr)(args.data()); return llvm::Error::success(); } <|endoftext|>
<commit_before>#include <UnitTest++.h> #include <OpenSG/OSGConfig.h> #include <OpenSG/OSGBaseInitFunctions.h> int main(int argc, char *argv[]) { OSG::osgInit(argc, argv); return UnitTest::RunAllTests(); } <commit_msg>Added ability to only run named suite<commit_after>#include <UnitTest++.h> #include <TestReporterStdout.h> #include <OpenSG/OSGConfig.h> #include <OpenSG/OSGBaseInitFunctions.h> int main(int argc, char *argv[]) { OSG::osgInit(argc, argv); if(argc < 2) return UnitTest::RunAllTests(); UnitTest::TestReporterStdout rep; return UnitTest::RunAllTests(rep, UnitTest::Test::GetTestList(), argv[1]); } <|endoftext|>
<commit_before>#include "SDL.h" #include "SDL_opengl.h" #include <cmath> const float kPi = 4.0f * std::atan(1.0f); const Uint32 kLagThreshold = 1000; const Uint32 kFrameTime = 10; const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f); const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f); const float kGridSpacing = 2.0f; const int kGridSize = 8; bool buttonLeft = false, buttonRight = false, buttonUp = false, buttonDown = false; float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f; Uint32 tickref = 0; void init(void) { SDL_Surface *screen = NULL; int flags; if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } } void handleKey(SDL_keysym *key, bool state) { switch (key->sym) { case SDLK_ESCAPE: if (state) { SDL_Quit(); exit(0); } break; case SDLK_UP: case SDLK_w: buttonUp = state; break; case SDLK_DOWN: case SDLK_s: buttonDown = state; break; case SDLK_LEFT: case SDLK_a: buttonLeft = state; break; case SDLK_RIGHT: case SDLK_d: buttonRight = state; break; default: break; } } void handleEvents(void) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym, true); break; case SDL_KEYUP: handleKey(&event.key.keysym, false); break; case SDL_QUIT: SDL_Quit(); exit(0); break; } } } void advanceFrame(void) { float forward = 0.0f, turn = 0.0f, face; if (buttonLeft) turn += kPlayerTurnSpeed; if (buttonRight) turn -= kPlayerTurnSpeed; if (buttonUp) forward += kPlayerForwardSpeed; if (buttonDown) forward -= kPlayerForwardSpeed; playerFace += turn; face = playerFace * (kPi / 180.0f); playerX += forward * std::cos(face); playerY += forward * std::sin(face); } void updateState(void) { Uint32 tick = SDL_GetTicks(); if (tick > tickref + kLagThreshold) { advanceFrame(); tickref = tick; } else if (tick > tickref + kFrameTime) { do { advanceFrame(); tickref += kFrameTime; } while (tick > tickref + kFrameTime); } else if (tick < tickref) tickref = tick; } struct gradient_point { float pos; unsigned char color[3]; }; const gradient_point sky[] = { { -0.50f, { 0, 0, 51 } }, { -0.02f, { 0, 0, 0 } }, { 0.00f, { 102, 204, 255 } }, { 0.20f, { 51, 0, 255 } }, { 0.70f, { 0, 0, 0 } } }; void drawSky(void) { glPushAttrib(GL_CURRENT_BIT); glBegin(GL_TRIANGLE_STRIP); glColor3ubv(sky[0].color); glVertex3f(-2.0f, 1.0f, -1.0f); glVertex3f( 2.0f, 1.0f, -1.0f); for (int i = 0; i < sizeof(sky) / sizeof(*sky); ++i) { glColor3ubv(sky[i].color); glVertex3f(-2.0f, 1.0f, sky[i].pos); glVertex3f( 2.0f, 1.0f, sky[i].pos); } glVertex3f(-2.0f, 0.0f, 1.0f); glVertex3f( 2.0f, 0.0f, 1.0f); glEnd(); glPopAttrib(); } void drawGround(void) { float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing; float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing; glPushAttrib(GL_CURRENT_BIT); glPushMatrix(); glTranslatef(px, py, 0.0f); glScalef(kGridSpacing, kGridSpacing, 1.0f); glColor3ub(51, 0, 255); glBegin(GL_LINES); for (int i = -kGridSize; i <= kGridSize; ++i) { glVertex3f(i, -kGridSize, 0.0f); glVertex3f(i, kGridSize, 0.0f); glVertex3f(-kGridSize, i, 0.0f); glVertex3f( kGridSize, i, 0.0f); } glEnd(); glPopAttrib(); glPopMatrix(); } void drawScene(void) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); drawSky(); glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f); glTranslatef(-playerX, -playerY, -1.0f); drawGround(); SDL_GL_SwapBuffers(); } int main(int argc, char *argv[]) { init(); while (1) { handleEvents(); updateState(); drawScene(); } return 0; } <commit_msg>Fixed warning on Linux.<commit_after>#include "SDL.h" #include "SDL_opengl.h" #include <cmath> const float kPi = 4.0f * std::atan(1.0f); const Uint32 kLagThreshold = 1000; const Uint32 kFrameTime = 10; const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f); const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f); const float kGridSpacing = 2.0f; const int kGridSize = 8; bool buttonLeft = false, buttonRight = false, buttonUp = false, buttonDown = false; float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f; Uint32 tickref = 0; void init(void) { SDL_Surface *screen = NULL; int flags; if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } } void handleKey(SDL_keysym *key, bool state) { switch (key->sym) { case SDLK_ESCAPE: if (state) { SDL_Quit(); exit(0); } break; case SDLK_UP: case SDLK_w: buttonUp = state; break; case SDLK_DOWN: case SDLK_s: buttonDown = state; break; case SDLK_LEFT: case SDLK_a: buttonLeft = state; break; case SDLK_RIGHT: case SDLK_d: buttonRight = state; break; default: break; } } void handleEvents(void) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym, true); break; case SDL_KEYUP: handleKey(&event.key.keysym, false); break; case SDL_QUIT: SDL_Quit(); exit(0); break; } } } void advanceFrame(void) { float forward = 0.0f, turn = 0.0f, face; if (buttonLeft) turn += kPlayerTurnSpeed; if (buttonRight) turn -= kPlayerTurnSpeed; if (buttonUp) forward += kPlayerForwardSpeed; if (buttonDown) forward -= kPlayerForwardSpeed; playerFace += turn; face = playerFace * (kPi / 180.0f); playerX += forward * std::cos(face); playerY += forward * std::sin(face); } void updateState(void) { Uint32 tick = SDL_GetTicks(); if (tick > tickref + kLagThreshold) { advanceFrame(); tickref = tick; } else if (tick > tickref + kFrameTime) { do { advanceFrame(); tickref += kFrameTime; } while (tick > tickref + kFrameTime); } else if (tick < tickref) tickref = tick; } struct gradient_point { float pos; unsigned char color[3]; }; const gradient_point sky[] = { { -0.50f, { 0, 0, 51 } }, { -0.02f, { 0, 0, 0 } }, { 0.00f, { 102, 204, 255 } }, { 0.20f, { 51, 0, 255 } }, { 0.70f, { 0, 0, 0 } } }; void drawSky(void) { glPushAttrib(GL_CURRENT_BIT); glBegin(GL_TRIANGLE_STRIP); glColor3ubv(sky[0].color); glVertex3f(-2.0f, 1.0f, -1.0f); glVertex3f( 2.0f, 1.0f, -1.0f); for (unsigned int i = 0; i < sizeof(sky) / sizeof(*sky); ++i) { glColor3ubv(sky[i].color); glVertex3f(-2.0f, 1.0f, sky[i].pos); glVertex3f( 2.0f, 1.0f, sky[i].pos); } glVertex3f(-2.0f, 0.0f, 1.0f); glVertex3f( 2.0f, 0.0f, 1.0f); glEnd(); glPopAttrib(); } void drawGround(void) { float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing; float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing; glPushAttrib(GL_CURRENT_BIT); glPushMatrix(); glTranslatef(px, py, 0.0f); glScalef(kGridSpacing, kGridSpacing, 1.0f); glColor3ub(51, 0, 255); glBegin(GL_LINES); for (int i = -kGridSize; i <= kGridSize; ++i) { glVertex3f(i, -kGridSize, 0.0f); glVertex3f(i, kGridSize, 0.0f); glVertex3f(-kGridSize, i, 0.0f); glVertex3f( kGridSize, i, 0.0f); } glEnd(); glPopAttrib(); glPopMatrix(); } void drawScene(void) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); drawSky(); glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f); glTranslatef(-playerX, -playerY, -1.0f); drawGround(); SDL_GL_SwapBuffers(); } int main(int argc, char *argv[]) { init(); while (1) { handleEvents(); updateState(); drawScene(); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: adtabdlg.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: oj $ $Date: 2002-07-11 12:05:02 $ * * 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 DBAUI_QYDLGTAB_HXX #include "adtabdlg.hxx" #endif #ifndef DBAUI_ADTABDLG_HRC #include "adtabdlg.hrc" #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include "dbaccess_helpid.hrc" #ifndef _DBU_RESOURCE_HRC_ #include "dbu_resource.hrc" #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XViewsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif // slot ids using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace dbtools; DBG_NAME(OAddTableDlg) //------------------------------------------------------------------------------ OAddTableDlg::OAddTableDlg( Window* pParent,OJoinTableView* _pTableView) :ModelessDialog( pParent, ModuleRes(DLG_JOIN_TABADD) ) ,aFTTable( this, ResId( FT_TABLE ) ) ,aTableList( this, ResId( LB_TABLE ),sal_False,sal_False ) ,aAddButton( this, ResId( PB_ADDTABLE ) ) ,aCloseButton( this, ResId( PB_CLOSE ) ) ,aHelpButton( this, ResId( PB_HELP ) ) ,aFixedLineTable( this, ResId( FL_TABLE ) ) ,aDefaultString( ResId( STR_DEFAULT ) ) ,m_pTableView(_pTableView) ,m_bInitialized(sal_False) { DBG_CTOR(OAddTableDlg,NULL); OSL_ENSURE(_pTableView,"Must be a valid pointer!"); // der Close-Button hat schon einen Standard-Help-Text, den ich aber hier nicht haben moechte, also den Text ruecksetzen // und eine neue ID verteilen aCloseButton.SetHelpText(String()); aCloseButton.SetHelpId(HID_JOINSH_ADDTAB_CLOSE); aTableList.SetHelpId(HID_JOINSH_ADDTAB_TABLELIST); ////////////////////////////////////////////////////////////////////// // Handler setzen aAddButton.SetClickHdl( LINK(this,OAddTableDlg, AddClickHdl) ); aCloseButton.SetClickHdl( LINK(this,OAddTableDlg, CloseClickHdl) ); aTableList.SetDoubleClickHdl( LINK(this,OAddTableDlg, TableListDoubleClickHdl) ); aTableList.EnableInplaceEditing( FALSE ); aTableList.SetWindowBits(WB_BORDER | WB_HASLINES |WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HASLINESATROOT | WB_SORT | WB_HSCROLL ); aTableList.EnableCheckButton( NULL ); // do not show any buttons aTableList.SetSelectionMode( SINGLE_SELECTION ); aTableList.notifyHiContrastChanged(); FreeResource(); } //------------------------------------------------------------------------------ OAddTableDlg::~OAddTableDlg() { DBG_DTOR(OAddTableDlg,NULL); } //------------------------------------------------------------------------------ void OAddTableDlg::Update() { if(!m_bInitialized) { UpdateTableList(m_pTableView->getDesignView()->getController()->isViewAllowed()); m_bInitialized = sal_True; } } //------------------------------------------------------------------------------ void OAddTableDlg::AddTable() { ////////////////////////////////////////////////////////////////// // Tabelle hinzufuegen SvLBoxEntry* pEntry = aTableList.FirstSelected(); if( pEntry && !aTableList.GetModel()->HasChilds(pEntry)) { ::rtl::OUString aCatalog,aSchema,aTableName; SvLBoxEntry* pSchema = aTableList.GetParent(pEntry); if(pSchema && pSchema != aTableList.getAllObjectsEntry()) { SvLBoxEntry* pCatalog = aTableList.GetParent(pSchema); if(pCatalog && pCatalog != aTableList.getAllObjectsEntry()) aCatalog = aTableList.GetEntryText(pCatalog); aSchema = aTableList.GetEntryText(pSchema); } aTableName = aTableList.GetEntryText(pEntry); // den Datenbank-Namen besorgen ::rtl::OUString aComposedName; ::dbtools::composeTableName(m_pTableView->getDesignView()->getController()->getConnection()->getMetaData(), aCatalog,aSchema,aTableName,aComposedName,sal_False); // aOrigTableName is used because AddTabWin would like to have this // und das Ganze dem Container uebergeben m_pTableView->AddTabWin( aComposedName,aTableName, TRUE ); } } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, AddClickHdl, Button*, pButton ) { TableListDoubleClickHdl(NULL); return 0; } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, TableListDoubleClickHdl, ListBox *, EMPTY_ARG ) { if (IsAddAllowed()) AddTable(); if (!IsAddAllowed()) Close(); return 0; } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, CloseClickHdl, Button*, pButton ) { return Close(); } //------------------------------------------------------------------------------ BOOL OAddTableDlg::Close() { m_pTableView->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_ADDTABLE); m_pTableView->getDesignView()->getController()->getView()->GrabFocus(); return ModelessDialog::Close(); } //------------------------------------------------------------------------------ BOOL OAddTableDlg::IsAddAllowed() { return m_pTableView && m_pTableView->IsAddAllowed(); } //------------------------------------------------------------------------------ void OAddTableDlg::UpdateTableList(BOOL bViewsAllowed) { ////////////////////////////////////////////////////////////////////// // Datenbank- und Tabellennamen setzen Reference< XTablesSupplier > xTableSupp(m_pTableView->getDesignView()->getController()->getConnection(),UNO_QUERY); Reference< XViewsSupplier > xViewSupp; Reference< XNameAccess > xTables, xViews; xTables = xTableSupp->getTables(); // get the views supplier and the views Sequence< ::rtl::OUString> sTables,sViews; if (xTables.is()) sTables = xTables->getElementNames(); xViewSupp = Reference< XViewsSupplier >(xTableSupp, UNO_QUERY); if (xViewSupp.is()) { xViews = xViewSupp->getViews(); if (xViews.is()) sViews = xViews->getElementNames(); } // if no views are allowed remove the views also out the table name filter if ( !bViewsAllowed ) { const ::rtl::OUString* pTableBegin = sTables.getConstArray(); const ::rtl::OUString* pTableEnd = pTableBegin + sTables.getLength(); ::std::vector< ::rtl::OUString > aTables(pTableBegin,pTableEnd); const ::rtl::OUString* pViewBegin = sViews.getConstArray(); const ::rtl::OUString* pViewEnd = pViewBegin + sViews.getLength(); ::comphelper::TStringMixEqualFunctor aEqualFunctor; for(;pViewBegin != pViewEnd;++pViewBegin) aTables.erase(::std::remove_if(aTables.begin(),aTables.end(),::std::not1(::std::bind2nd(aEqualFunctor,*pViewBegin)))); sTables = Sequence< ::rtl::OUString>(aTables.begin(),aTables.size()); sViews = Sequence< ::rtl::OUString>(); } aTableList.UpdateTableList(Reference< XConnection>(xTableSupp,UNO_QUERY)->getMetaData(),sTables,sViews); } // ----------------------------------------------------------------------------- <commit_msg>#100000# included algorithm header<commit_after>/************************************************************************* * * $RCSfile: adtabdlg.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2002-07-16 09:53:18 $ * * 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 DBAUI_QYDLGTAB_HXX #include "adtabdlg.hxx" #endif #ifndef DBAUI_ADTABDLG_HRC #include "adtabdlg.hrc" #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include "dbaccess_helpid.hrc" #ifndef _DBU_RESOURCE_HRC_ #include "dbu_resource.hrc" #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XViewsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #include <algorithm> // slot ids using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace dbtools; DBG_NAME(OAddTableDlg) //------------------------------------------------------------------------------ OAddTableDlg::OAddTableDlg( Window* pParent,OJoinTableView* _pTableView) :ModelessDialog( pParent, ModuleRes(DLG_JOIN_TABADD) ) ,aFTTable( this, ResId( FT_TABLE ) ) ,aTableList( this, ResId( LB_TABLE ),sal_False,sal_False ) ,aAddButton( this, ResId( PB_ADDTABLE ) ) ,aCloseButton( this, ResId( PB_CLOSE ) ) ,aHelpButton( this, ResId( PB_HELP ) ) ,aFixedLineTable( this, ResId( FL_TABLE ) ) ,aDefaultString( ResId( STR_DEFAULT ) ) ,m_pTableView(_pTableView) ,m_bInitialized(sal_False) { DBG_CTOR(OAddTableDlg,NULL); OSL_ENSURE(_pTableView,"Must be a valid pointer!"); // der Close-Button hat schon einen Standard-Help-Text, den ich aber hier nicht haben moechte, also den Text ruecksetzen // und eine neue ID verteilen aCloseButton.SetHelpText(String()); aCloseButton.SetHelpId(HID_JOINSH_ADDTAB_CLOSE); aTableList.SetHelpId(HID_JOINSH_ADDTAB_TABLELIST); ////////////////////////////////////////////////////////////////////// // Handler setzen aAddButton.SetClickHdl( LINK(this,OAddTableDlg, AddClickHdl) ); aCloseButton.SetClickHdl( LINK(this,OAddTableDlg, CloseClickHdl) ); aTableList.SetDoubleClickHdl( LINK(this,OAddTableDlg, TableListDoubleClickHdl) ); aTableList.EnableInplaceEditing( FALSE ); aTableList.SetWindowBits(WB_BORDER | WB_HASLINES |WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HASLINESATROOT | WB_SORT | WB_HSCROLL ); aTableList.EnableCheckButton( NULL ); // do not show any buttons aTableList.SetSelectionMode( SINGLE_SELECTION ); aTableList.notifyHiContrastChanged(); FreeResource(); } //------------------------------------------------------------------------------ OAddTableDlg::~OAddTableDlg() { DBG_DTOR(OAddTableDlg,NULL); } //------------------------------------------------------------------------------ void OAddTableDlg::Update() { if(!m_bInitialized) { UpdateTableList(m_pTableView->getDesignView()->getController()->isViewAllowed()); m_bInitialized = sal_True; } } //------------------------------------------------------------------------------ void OAddTableDlg::AddTable() { ////////////////////////////////////////////////////////////////// // Tabelle hinzufuegen SvLBoxEntry* pEntry = aTableList.FirstSelected(); if( pEntry && !aTableList.GetModel()->HasChilds(pEntry)) { ::rtl::OUString aCatalog,aSchema,aTableName; SvLBoxEntry* pSchema = aTableList.GetParent(pEntry); if(pSchema && pSchema != aTableList.getAllObjectsEntry()) { SvLBoxEntry* pCatalog = aTableList.GetParent(pSchema); if(pCatalog && pCatalog != aTableList.getAllObjectsEntry()) aCatalog = aTableList.GetEntryText(pCatalog); aSchema = aTableList.GetEntryText(pSchema); } aTableName = aTableList.GetEntryText(pEntry); // den Datenbank-Namen besorgen ::rtl::OUString aComposedName; ::dbtools::composeTableName(m_pTableView->getDesignView()->getController()->getConnection()->getMetaData(), aCatalog,aSchema,aTableName,aComposedName,sal_False); // aOrigTableName is used because AddTabWin would like to have this // und das Ganze dem Container uebergeben m_pTableView->AddTabWin( aComposedName,aTableName, TRUE ); } } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, AddClickHdl, Button*, pButton ) { TableListDoubleClickHdl(NULL); return 0; } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, TableListDoubleClickHdl, ListBox *, EMPTY_ARG ) { if (IsAddAllowed()) AddTable(); if (!IsAddAllowed()) Close(); return 0; } //------------------------------------------------------------------------------ IMPL_LINK( OAddTableDlg, CloseClickHdl, Button*, pButton ) { return Close(); } //------------------------------------------------------------------------------ BOOL OAddTableDlg::Close() { m_pTableView->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_ADDTABLE); m_pTableView->getDesignView()->getController()->getView()->GrabFocus(); return ModelessDialog::Close(); } //------------------------------------------------------------------------------ BOOL OAddTableDlg::IsAddAllowed() { return m_pTableView && m_pTableView->IsAddAllowed(); } //------------------------------------------------------------------------------ void OAddTableDlg::UpdateTableList(BOOL bViewsAllowed) { ////////////////////////////////////////////////////////////////////// // Datenbank- und Tabellennamen setzen Reference< XTablesSupplier > xTableSupp(m_pTableView->getDesignView()->getController()->getConnection(),UNO_QUERY); Reference< XViewsSupplier > xViewSupp; Reference< XNameAccess > xTables, xViews; xTables = xTableSupp->getTables(); // get the views supplier and the views Sequence< ::rtl::OUString> sTables,sViews; if (xTables.is()) sTables = xTables->getElementNames(); xViewSupp = Reference< XViewsSupplier >(xTableSupp, UNO_QUERY); if (xViewSupp.is()) { xViews = xViewSupp->getViews(); if (xViews.is()) sViews = xViews->getElementNames(); } // if no views are allowed remove the views also out the table name filter if ( !bViewsAllowed ) { const ::rtl::OUString* pTableBegin = sTables.getConstArray(); const ::rtl::OUString* pTableEnd = pTableBegin + sTables.getLength(); ::std::vector< ::rtl::OUString > aTables(pTableBegin,pTableEnd); const ::rtl::OUString* pViewBegin = sViews.getConstArray(); const ::rtl::OUString* pViewEnd = pViewBegin + sViews.getLength(); ::comphelper::TStringMixEqualFunctor aEqualFunctor; for(;pViewBegin != pViewEnd;++pViewBegin) aTables.erase(::std::remove_if(aTables.begin(),aTables.end(),::std::not1(::std::bind2nd(aEqualFunctor,*pViewBegin)))); sTables = Sequence< ::rtl::OUString>(aTables.begin(),aTables.size()); sViews = Sequence< ::rtl::OUString>(); } aTableList.UpdateTableList(Reference< XConnection>(xTableSupp,UNO_QUERY)->getMetaData(),sTables,sViews); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // 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 other 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 <stdafx.h> #include <core/support/Common.h> #include <cursespp/Text.h> #include <cursespp/ScrollAdapterBase.h> #include <cursespp/SingleLineEntry.h> #include "DirectoryAdapter.h" using namespace musik::cube; using namespace cursespp; using namespace boost::filesystem; #ifdef WIN32 static void buildDriveList(std::vector<std::string>& target) { target.clear(); static char buffer[4096]; DWORD result = ::GetLogicalDriveStringsA(4096, buffer); if (result) { char* current = buffer; while (*current) { target.push_back(std::string(current)); current += strlen(current) + 1; } } } #endif static bool hasSubdirectories( boost::filesystem::path p, bool showDotfiles) { try { directory_iterator end; directory_iterator file(p); while (file != end) { if (is_directory(file->status())) { if (showDotfiles || file->path().leaf().string()[0] != '.') { return true; } } ++file; } } catch (...) { } return false; } static void buildDirectoryList( const path& p, std::vector<std::string>& target, bool showDotfiles) { target.clear(); try { directory_iterator end; directory_iterator file(p); while (file != end) { if (is_directory(file->status())) { std::string leaf = file->path().leaf().string(); if (showDotfiles || leaf[0] != '.') { target.push_back(leaf); } } ++file; } } catch (...) { } try { std::sort( target.begin(), target.end(), std::locale(setlocale(LC_ALL, nullptr))); } catch (...) { std::sort(target.begin(), target.end()); } } static std::string normalizePath(boost::filesystem::path path) { return musik::core::NormalizeDir(path.string()); } DirectoryAdapter::DirectoryAdapter() { this->showDotfiles = false; this->dir = musik::core::GetHomeDirectory(); buildDirectoryList(dir, subdirs, showDotfiles); } DirectoryAdapter::~DirectoryAdapter() { } void DirectoryAdapter::SetAllowEscapeRoot(bool allow) { this->allowEscapeRoot = allow; } size_t DirectoryAdapter::Select(cursespp::ListWindow* window) { bool hasParent = this->ShowParentPath(); size_t selectedIndex = NO_INDEX; size_t initialIndex = window->GetSelectedIndex(); if (hasParent && initialIndex == 0) { if (selectedIndexStack.size()) { selectedIndex = this->selectedIndexStack.top(); this->selectedIndexStack.pop(); } this->dir = this->dir.parent_path(); } else { selectedIndexStack.push(initialIndex); this->dir /= this->subdirs[hasParent ? initialIndex - 1 : initialIndex]; } #ifdef WIN32 std::string pathstr = this->dir.string(); if ((pathstr.size() == 2 && pathstr[1] == ':') || (pathstr.size() == 3 && pathstr[2] == ':')) { dir = path(); buildDriveList(subdirs); return selectedIndex; } #endif buildDirectoryList(dir, subdirs, showDotfiles); window->OnAdapterChanged(); return selectedIndex; } void DirectoryAdapter::SetRootDirectory(const std::string& directory) { if (directory.size()) { dir = rootDir = directory; } else { dir = musik::core::GetHomeDirectory(); rootDir = boost::filesystem::path(); } buildDirectoryList(dir, subdirs, showDotfiles); } std::string DirectoryAdapter::GetFullPathAt(size_t index) { bool hasParent = this->ShowParentPath(); if (hasParent && index == 0) { return ""; } index = (hasParent ? index - 1 : index); return normalizePath((dir / this->subdirs[index]).string()); } std::string DirectoryAdapter::GetLeafAt(size_t index) { if (this->ShowParentPath() && index == 0) { return ".."; } return this->subdirs[index]; } size_t DirectoryAdapter::IndexOf(const std::string& leaf) { for (size_t i = 0; i < this->subdirs.size(); i++) { if (this->subdirs[i] == leaf) { return i; } } return NO_INDEX; } size_t DirectoryAdapter::GetEntryCount() { size_t count = subdirs.size(); return this->ShowParentPath() ? count + 1 : count; } void DirectoryAdapter::SetDotfilesVisible(bool visible) { if (showDotfiles != visible) { showDotfiles = visible; buildDirectoryList(dir, subdirs, showDotfiles); } } std::string DirectoryAdapter::GetParentPath() { if (dir.has_parent_path() && normalizePath(this->dir) != normalizePath(this->rootDir)) { return normalizePath(dir.parent_path().string()); } return ""; } std::string DirectoryAdapter::GetCurrentPath() { return normalizePath(dir.string()); } void DirectoryAdapter::Refresh() { buildDirectoryList(dir, subdirs, showDotfiles); } bool DirectoryAdapter::ShowParentPath() { if (normalizePath(this->dir) == normalizePath(this->rootDir) && !this->allowEscapeRoot) { return false; } return dir.has_parent_path(); } bool DirectoryAdapter::HasSubDirectories(size_t index) { bool hasParent = this->ShowParentPath(); if (index == 0 && hasParent) { return true; } index = hasParent ? index - 1 : index; return hasSubdirectories(this->dir / this->subdirs[index], this->showDotfiles); } bool DirectoryAdapter::HasSubDirectories() { return hasSubdirectories(this->dir, this->showDotfiles); } IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(cursespp::ScrollableWindow* window, size_t index) { if (this->ShowParentPath()) { if (index == 0) { return IScrollAdapter::EntryPtr(new SingleLineEntry("..")); } --index; } auto text = text::Ellipsize(this->subdirs[index], this->GetWidth()); return IScrollAdapter::EntryPtr(new SingleLineEntry(text)); } <commit_msg>Fix #299: directory list disappears after toggling 'show dotfiles' in settings.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // 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 other 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 <stdafx.h> #include <core/support/Common.h> #include <cursespp/Text.h> #include <cursespp/ScrollAdapterBase.h> #include <cursespp/SingleLineEntry.h> #include "DirectoryAdapter.h" using namespace musik::cube; using namespace cursespp; using namespace boost::filesystem; #ifdef WIN32 static void buildDriveList(std::vector<std::string>& target) { target.clear(); static char buffer[4096]; DWORD result = ::GetLogicalDriveStringsA(4096, buffer); if (result) { char* current = buffer; while (*current) { target.push_back(std::string(current)); current += strlen(current) + 1; } } } static bool shouldBuildDriveList(const boost::filesystem::path& dir) { std::string pathstr = dir.string(); return (pathstr.size() == 2 && pathstr[1] == ':') || (pathstr.size() == 3 && pathstr[2] == ':') || (pathstr.size() == 0); } #endif static bool hasSubdirectories( boost::filesystem::path p, bool showDotfiles) { try { directory_iterator end; directory_iterator file(p); while (file != end) { if (is_directory(file->status())) { if (showDotfiles || file->path().leaf().string()[0] != '.') { return true; } } ++file; } } catch (...) { } return false; } static void buildDirectoryList( const path& p, std::vector<std::string>& target, bool showDotfiles) { target.clear(); try { directory_iterator end; directory_iterator file(p); while (file != end) { if (is_directory(file->status())) { std::string leaf = file->path().leaf().string(); if (showDotfiles || leaf[0] != '.') { target.push_back(leaf); } } ++file; } } catch (...) { } try { std::sort( target.begin(), target.end(), std::locale(setlocale(LC_ALL, nullptr))); } catch (...) { std::sort(target.begin(), target.end()); } } static std::string normalizePath(boost::filesystem::path path) { return musik::core::NormalizeDir(path.string()); } DirectoryAdapter::DirectoryAdapter() { this->showDotfiles = false; this->dir = musik::core::GetHomeDirectory(); buildDirectoryList(dir, subdirs, showDotfiles); } DirectoryAdapter::~DirectoryAdapter() { } void DirectoryAdapter::SetAllowEscapeRoot(bool allow) { this->allowEscapeRoot = allow; } size_t DirectoryAdapter::Select(cursespp::ListWindow* window) { bool hasParent = this->ShowParentPath(); size_t selectedIndex = NO_INDEX; size_t initialIndex = window->GetSelectedIndex(); if (hasParent && initialIndex == 0) { if (selectedIndexStack.size()) { selectedIndex = this->selectedIndexStack.top(); this->selectedIndexStack.pop(); } this->dir = this->dir.parent_path(); } else { selectedIndexStack.push(initialIndex); this->dir /= this->subdirs[hasParent ? initialIndex - 1 : initialIndex]; } #ifdef WIN32 if (shouldBuildDriveList(this->dir)) { dir = path(); buildDriveList(subdirs); return selectedIndex; } #endif buildDirectoryList(dir, subdirs, showDotfiles); window->OnAdapterChanged(); return selectedIndex; } void DirectoryAdapter::SetRootDirectory(const std::string& directory) { if (directory.size()) { dir = rootDir = directory; } else { dir = musik::core::GetHomeDirectory(); rootDir = boost::filesystem::path(); } buildDirectoryList(dir, subdirs, showDotfiles); } std::string DirectoryAdapter::GetFullPathAt(size_t index) { bool hasParent = this->ShowParentPath(); if (hasParent && index == 0) { return ""; } index = (hasParent ? index - 1 : index); return normalizePath((dir / this->subdirs[index]).string()); } std::string DirectoryAdapter::GetLeafAt(size_t index) { if (this->ShowParentPath() && index == 0) { return ".."; } return this->subdirs[index]; } size_t DirectoryAdapter::IndexOf(const std::string& leaf) { for (size_t i = 0; i < this->subdirs.size(); i++) { if (this->subdirs[i] == leaf) { return i; } } return NO_INDEX; } size_t DirectoryAdapter::GetEntryCount() { size_t count = subdirs.size(); return this->ShowParentPath() ? count + 1 : count; } void DirectoryAdapter::SetDotfilesVisible(bool visible) { if (showDotfiles != visible) { showDotfiles = visible; #ifdef WIN32 if (shouldBuildDriveList(this->dir)) { buildDriveList(subdirs); return; } #endif buildDirectoryList(dir, subdirs, showDotfiles); } } std::string DirectoryAdapter::GetParentPath() { if (dir.has_parent_path() && normalizePath(this->dir) != normalizePath(this->rootDir)) { return normalizePath(dir.parent_path().string()); } return ""; } std::string DirectoryAdapter::GetCurrentPath() { return normalizePath(dir.string()); } void DirectoryAdapter::Refresh() { buildDirectoryList(dir, subdirs, showDotfiles); } bool DirectoryAdapter::ShowParentPath() { if (normalizePath(this->dir) == normalizePath(this->rootDir) && !this->allowEscapeRoot) { return false; } return dir.has_parent_path(); } bool DirectoryAdapter::HasSubDirectories(size_t index) { bool hasParent = this->ShowParentPath(); if (index == 0 && hasParent) { return true; } index = hasParent ? index - 1 : index; return hasSubdirectories(this->dir / this->subdirs[index], this->showDotfiles); } bool DirectoryAdapter::HasSubDirectories() { return hasSubdirectories(this->dir, this->showDotfiles); } IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(cursespp::ScrollableWindow* window, size_t index) { if (this->ShowParentPath()) { if (index == 0) { return IScrollAdapter::EntryPtr(new SingleLineEntry("..")); } --index; } auto text = text::Ellipsize(this->subdirs[index], this->GetWidth()); return IScrollAdapter::EntryPtr(new SingleLineEntry(text)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LayerDialogChildWindow.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:07:22 $ * * 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 SD_LAYER_DIALOG_CHILD_WINDOW_HXX #define SD_LAYER_DIALOG_CHILD_WINDOW_HXX #ifndef _SFX_CHILDWIN_HXX #include <sfx2/childwin.hxx> #endif namespace sd { /** Floating container for the layout dialog. What is missing is a way to inform the layer dialog of changing views. */ class LayerDialogChildWindow : public SfxChildWindow { public: LayerDialogChildWindow ( ::Window*, USHORT, SfxBindings*, SfxChildWinInfo*); virtual ~LayerDialogChildWindow (void); SFX_DECL_CHILDWINDOW(LayerDialogChildWindow); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.624); FILE MERGED 2008/04/01 15:35:10 thb 1.3.624.2: #i85898# Stripping all external header guards 2008/03/31 13:58:09 rt 1.3.624.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LayerDialogChildWindow.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_LAYER_DIALOG_CHILD_WINDOW_HXX #define SD_LAYER_DIALOG_CHILD_WINDOW_HXX #include <sfx2/childwin.hxx> namespace sd { /** Floating container for the layout dialog. What is missing is a way to inform the layer dialog of changing views. */ class LayerDialogChildWindow : public SfxChildWindow { public: LayerDialogChildWindow ( ::Window*, USHORT, SfxBindings*, SfxChildWinInfo*); virtual ~LayerDialogChildWindow (void); SFX_DECL_CHILDWINDOW(LayerDialogChildWindow); }; } // end of namespace sd #endif <|endoftext|>
<commit_before> #include "demhandlers.h" #include "demmessages.h" #define DECLARE_DEM_HANDLER_ARRAY(funcname) \ { \ &DemHandlers::Dem_Unknown_##funcname, \ &DemHandlers::Dem_Packet_##funcname, \ &DemHandlers::Dem_Packet_##funcname, \ &DemHandlers::Dem_SyncTick_##funcname, \ &DemHandlers::Dem_ConsoleCmd_##funcname, \ &DemHandlers::Dem_UserCmd_##funcname, \ &DemHandlers::Dem_DataTables_##funcname, \ &DemHandlers::Dem_Stop_##funcname, \ &DemHandlers::Dem_StringTables_##funcname \ } typedef bool (*DemMsgFileReadFn)(FileRead& demofile, void* data); typedef bool (*DemMsgFileWriteFn)(FileWrite& demofile, void* data); typedef bool (*DemMsgJsonReadFn)(JsonRead& jsonbuf, void* data); typedef bool (*DemMsgJsonWriteFn)(JsonWrite& jsonbuf, void* data); bool DemHandlers::DemMsg_FileRead(uint32_t type, FileRead& demofile, void* data) { static const DemMsgFileReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileRead); return demHandlers[type](demofile, data); } bool DemHandlers::DemMsg_FileWrite(uint32_t type, FileWrite& demofile, void* data) { static const DemMsgFileWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileWrite); return demHandlers[type](demofile, data); } bool DemHandlers::DemMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, void* data) { static const DemMsgJsonReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonRead); return demHandlers[type](jsonbuf, data); } bool DemHandlers::DemMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, void* data) { static const DemMsgJsonWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonWrite); return demHandlers[type](jsonbuf, data); } <commit_msg>Added guards around DemHandlers functions<commit_after> #include "demhandlers.h" #include "demmessages.h" #define DECLARE_DEM_HANDLER_ARRAY(funcname) \ { \ &DemHandlers::Dem_Unknown_##funcname, \ &DemHandlers::Dem_Packet_##funcname, \ &DemHandlers::Dem_Packet_##funcname, \ &DemHandlers::Dem_SyncTick_##funcname, \ &DemHandlers::Dem_ConsoleCmd_##funcname, \ &DemHandlers::Dem_UserCmd_##funcname, \ &DemHandlers::Dem_DataTables_##funcname, \ &DemHandlers::Dem_Stop_##funcname, \ &DemHandlers::Dem_StringTables_##funcname \ } typedef bool (*DemMsgFileReadFn)(FileRead& demofile, void* data); typedef bool (*DemMsgFileWriteFn)(FileWrite& demofile, void* data); typedef bool (*DemMsgJsonReadFn)(JsonRead& jsonbuf, void* data); typedef bool (*DemMsgJsonWriteFn)(JsonWrite& jsonbuf, void* data); bool DemHandlers::DemMsg_FileRead(uint32_t type, FileRead& demofile, void* data) { static const DemMsgFileReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileRead); if (type >= (sizeof(demHandlers) / sizeof(DemMsgFileReadFn))) { return false; } return demHandlers[type](demofile, data); } bool DemHandlers::DemMsg_FileWrite(uint32_t type, FileWrite& demofile, void* data) { static const DemMsgFileWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileWrite); if (type >= (sizeof(demHandlers) / sizeof(DemMsgFileWriteFn))) { return false; } return demHandlers[type](demofile, data); } bool DemHandlers::DemMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, void* data) { static const DemMsgJsonReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonRead); if (type >= (sizeof(demHandlers) / sizeof(DemMsgJsonReadFn))) { return false; } return demHandlers[type](jsonbuf, data); } bool DemHandlers::DemMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, void* data) { static const DemMsgJsonWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonWrite); if (type >= (sizeof(demHandlers) / sizeof(DemMsgJsonWriteFn))) { return false; } return demHandlers[type](jsonbuf, data); } <|endoftext|>
<commit_before>#include "stdafx.h" #include <windows.h> #include "..\includes\CPatch.h" #include "..\includes\IniReader.h" HMODULE h_e2mfc_dll = NULL; HMODULE comics = NULL; float iniFOV, FOV; float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor; float fVisibilityFactor1, fVisibilityFactor2; unsigned int ScreenWidth, ScreenHeight; DWORD jmpAddress, jmpFOV; DWORD _EAX, _EBX, _nEDX; float _EDX; bool bComicsMode; int __fastcall PDriverGetWidth(int a1) { int result; // eax@2 if (*(DWORD *)(a1 + 48)) result = *(DWORD *)(a1 + 52); else result = *(DWORD *)(a1 + 4); ScreenWidth = result; return result; } int __fastcall PDriverGetHeight(int a1) { int result; // eax@2 if (*(DWORD *)(a1 + 48)) result = *(DWORD *)(a1 + 56); else result = *(DWORD *)(a1 + 8); ScreenHeight = result; return result; } void __declspec(naked)PatchFOV() { __asm mov ebx, FOV __asm push ebx //FOV value __asm mov ecx, esi __asm call ebp __asm jmp jmpFOV } void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue) { float v2; // eax@4 FOVvalue *= iniFOV; if (*(float *)&FOVvalue != *(float *)(P_Camera + 284)) { if (*(float *)&FOVvalue >= 0.0) { v2 = 3.1241393f; if (*(float *)&FOVvalue <= 3.1241393) v2 = FOVvalue; *(BYTE *)(P_Camera + 236) |= 0x40u; *(float *)(P_Camera + 284) = v2; } else { *(BYTE *)(P_Camera + 236) |= 0x40u; *(DWORD *)(P_Camera + 284) = 0; } } } void __declspec(naked)ForceEntireViewport() { __asm mov ax, 1 __asm ret } void __declspec(naked)DisableSubViewport() { __asm ret 10h } void __declspec(naked)PCameraValidateHook() { __asm mov _EAX, eax __asm mov _EBX, ebx __asm mov edx, [esp + 4] __asm mov _EDX, edx __asm mov _nEDX, edx if (_EDX >= 0.7f && _EDX <= 0.8f) { if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8)) { if (!fDiffFactor) { fDiffFactor = fWidthFactor / _EDX; } if (fDiffFactor) _EDX *= fDiffFactor; __asm mov edx, _EDX } } else { if (_EAX == 8 && _EDX < 0.7f) { if (fDiffFactor) _EDX *= fDiffFactor; if ((_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD)) //0.414213568, it's to avoid comics stretching __asm mov edx, _EDX } } __asm mov[esi + 20Ch], edx __asm jmp jmpAddress } DWORD WINAPI Thread(LPVOID) { CIniReader iniReader(""); iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f); do { Sleep(100); h_e2mfc_dll = GetModuleHandle("e2mfc.dll"); } while (h_e2mfc_dll == NULL); CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth); CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight); CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport); CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport); do { Sleep(0); } while (ScreenWidth == 0 || ScreenHeight == 0); /*if (iniFOV) { //FOV = iniFOV; //jmpFOV = 0x428F86; //CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack //CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV); //CPatch::SetPointer(0x428F7B, P_CameraSetFOV); }*/ fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight); fWidthFactor = fAspectRatio / (16.0f / 9.0f); if (fAspectRatio >= 1.4f) { jmpAddress = (DWORD)h_e2mfc_dll + 0x15041; CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook); //object disappearance fix CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f); stdViewPortSize = 640.0f; CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize); DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183; //doors graphics fix fVisibilityFactor1 = 0.5f; fVisibilityFactor2 = 1.5f; //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4); CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3); CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2); if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0)) bComicsMode = !bComicsMode; while (true) { Sleep(0); if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)) { bComicsMode = !bComicsMode; iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode); while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); } } if (bComicsMode) { Sleep(1); if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE) { stdViewPortSize = 480.0f * (fAspectRatio); CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } else { stdViewPortSize = 640.0f; CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } } else { Sleep(1); if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE) { stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f); CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f } else { stdViewPortSize = 640.0f; CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } } } } return 0; } BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/) { if (reason == DLL_PROCESS_ATTACH) { CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL); } return TRUE; }<commit_msg>Widescreen Fixes Pack v2.5.2<commit_after>#include "stdafx.h" #include <windows.h> #include "..\includes\CPatch.h" #include "..\includes\IniReader.h" HMODULE h_e2mfc_dll = NULL; HMODULE comics = NULL; float iniFOV, FOV; float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor; float fVisibilityFactor1, fVisibilityFactor2; unsigned int ScreenWidth, ScreenHeight; DWORD jmpAddress, jmpFOV; DWORD _EAX, _EBX, _nEDX; float _EDX; bool bComicsMode; int __fastcall PDriverGetWidth(int a1) { int result; // eax@2 if (*(DWORD *)(a1 + 48)) result = *(DWORD *)(a1 + 52); else result = *(DWORD *)(a1 + 4); ScreenWidth = result; return result; } int __fastcall PDriverGetHeight(int a1) { int result; // eax@2 if (*(DWORD *)(a1 + 48)) result = *(DWORD *)(a1 + 56); else result = *(DWORD *)(a1 + 8); ScreenHeight = result; return result; } void __declspec(naked)PatchFOV() { __asm mov ebx, FOV __asm push ebx //FOV value __asm mov ecx, esi __asm call ebp __asm jmp jmpFOV } void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue) { FOVvalue *= iniFOV; if (*(float *)&FOVvalue != *(float *)(P_Camera + 284)) { if (*(float *)&FOVvalue >= 0.0) { if (FOVvalue <= 3.1241393f) { *(BYTE *)(P_Camera + 236) |= 0x40u; *(float *)(P_Camera + 284) = FOVvalue; } } else { *(BYTE *)(P_Camera + 236) |= 0x40u; *(DWORD *)(P_Camera + 284) = 0; } } } void __declspec(naked)ForceEntireViewport() { __asm mov ax, 1 __asm ret } void __declspec(naked)DisableSubViewport() { __asm ret 10h } void __declspec(naked)PCameraValidateHook() { __asm mov _EAX, eax __asm mov _EBX, ebx __asm mov edx, [esp + 4] __asm mov _EDX, edx __asm mov _nEDX, edx if (_EDX >= 0.7f && _EDX <= 0.8f) { if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8)) { if (!fDiffFactor) { fDiffFactor = fWidthFactor / _EDX; } if (fDiffFactor) _EDX *= fDiffFactor; __asm mov edx, _EDX } } else { if (_EAX == 8 && _EDX < 0.7f) { if (fDiffFactor) _EDX *= fDiffFactor; if (_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD) //0.414213568, it's to avoid comics stretching __asm mov edx, _EDX } else { if ((_EDX > 0.8f && _EDX <= 1.5f) && _nEDX != 0x3F800000) { if (fDiffFactor) _EDX *= fDiffFactor; if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8)) __asm mov edx, _EDX } } } __asm mov[esi + 20Ch], edx __asm jmp jmpAddress } DWORD WINAPI Thread(LPVOID) { CIniReader iniReader(""); iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f); do { Sleep(100); h_e2mfc_dll = GetModuleHandle("e2mfc.dll"); } while (h_e2mfc_dll == NULL); CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth); CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight); CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport); CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport); do { Sleep(0); } while (ScreenWidth == 0 || ScreenHeight == 0); /*if (iniFOV) { //FOV = iniFOV; //jmpFOV = 0x428F86; //CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack //CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV); //CPatch::SetPointer(0x428F7B, P_CameraSetFOV); }*/ fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight); fWidthFactor = fAspectRatio / (16.0f / 9.0f); if (fAspectRatio >= 1.4f) { jmpAddress = (DWORD)h_e2mfc_dll + 0x15041; CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook); //object disappearance fix CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f); stdViewPortSize = 640.0f; CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize); DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183; //doors graphics fix fVisibilityFactor1 = 0.5f; fVisibilityFactor2 = 1.5f; //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4); CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3); CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1); //CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2); if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0)) bComicsMode = !bComicsMode; while (true) { Sleep(0); if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)) { bComicsMode = !bComicsMode; iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode); while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); } } if (bComicsMode) { Sleep(1); if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE) { stdViewPortSize = 480.0f * (fAspectRatio); CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } else { stdViewPortSize = 640.0f; CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } } else { Sleep(1); if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE) { stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f); CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f } else { stdViewPortSize = 640.0f; CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f } } } } return 0; } BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/) { if (reason == DLL_PROCESS_ATTACH) { CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL); } return TRUE; }<|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <arrayfire.h> #include <cstdio> #include <math.h> using namespace af; static const int POINTS = 30; static const int N = 2 * POINTS; int main(int argc, char *argv[]) { try { // Initialize the kernel array just once af::info(); af::Window myWindow(800, 800, "3D Surface example: ArrayFire"); // Creates grid of between [-1 1] with precision of 1 / POINTS const array x = iota(dim4(N, 1), dim4(1, N)) / POINTS - 1; const array y = iota(dim4(1, N), dim4(N, 1)) / POINTS - 1; std::cout << x.dims() << y.dims() << std::endl; static float t=0; while(!myWindow.close()) { t+=0.07; array z = 10*x*-abs(y) * cos(x*x*(y+t))+sin(y*(x+t))-1.5; myWindow.surface(x, y, z); } } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } <commit_msg>Fixing surface.cpp example to work on windows<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <arrayfire.h> #include <cstdio> #include <math.h> using namespace af; static const int M = 30; static const int N = 2 * M; int main(int argc, char *argv[]) { try { // Initialize the kernel array just once af::info(); af::Window myWindow(800, 800, "3D Surface example: ArrayFire"); // Creates grid of between [-1 1] with precision of 1 / M const array x = iota(dim4(N, 1), dim4(1, N)) / M - 1; const array y = iota(dim4(1, N), dim4(N, 1)) / M - 1; std::cout << x.dims() << y.dims() << std::endl; static float t=0; while(!myWindow.close()) { t+=0.07; array z = 10*x*-abs(y) * cos(x*x*(y+t))+sin(y*(x+t))-1.5; myWindow.surface(x, y, z); } } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Dan Solomon * * 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. */ /* * joint_trajectory_pt.cpp * * Created on: Oct 3, 2014 * Author: Dan Solomon */ #include <console_bridge/console.h> #include "descartes_core/joint_trajectory_pt.h" #define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret; namespace descartes_core { JointTrajectoryPt::JointTrajectoryPt(): tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const Frame &tool, const Frame &wobj): joint_position_(joints), tool_(tool), wobj_(wobj) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints): joint_position_(joints), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints): tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) { for (size_t ii = 0; ii < joints.size(); ++ii) { joint_position_.push_back(TolerancedJointValue(joints[ii])); } } bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { NOT_IMPLEMENTED_ERR(false) } bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { std::vector<double> joints; for(auto& tj: joint_position_) { joints.push_back(tj.nominal); } return model.getFK(joints,pose); } void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const { poses.clear(); } bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { NOT_IMPLEMENTED_ERR(false); } bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.resize(joint_position_.size()); for (size_t ii=0; ii<joint_position_.size(); ++ii) { joint_pose[ii] = joint_position_[ii].nominal; } return true; } void JointTrajectoryPt::getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { std::vector<double> empty_seed; joint_poses.resize(1); getNominalJointPose(empty_seed,model,joint_poses[0]); } bool JointTrajectoryPt::isValid(const RobotModel &model) const { std::vector<double> lower(joint_position_.size()); std::vector<double> upper(joint_position_.size()); for (size_t ii = 0; ii < joint_position_.size(); ++ii) { lower[ii] = joint_position_[ii].tolerance.lower; upper[ii] = joint_position_[ii].tolerance.upper; } return model.isValid(lower) && model.isValid(upper); } bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization) { if (discretization.size() != 1 || discretization.size() != joint_position_.size()) { logError("discretization must be size 1 or same size as joint count."); return false; } if (discretization.size() == 1) { discretization_ = std::vector<double>(joint_position_.size(), discretization[0]); return true; } /* Do not copy discretization values until all values are confirmed */ for (size_t ii=0; ii<discretization.size(); ++ii) { if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range()) { logError("discretization value out of range."); return false; } } discretization_ = discretization; return true; } } /* namespace descartes_core */ <commit_msg>implemented Joint Trajectory point getClosestJointPose(...) method<commit_after>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Dan Solomon * * 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. */ /* * joint_trajectory_pt.cpp * * Created on: Oct 3, 2014 * Author: Dan Solomon */ #include <console_bridge/console.h> #include "descartes_core/joint_trajectory_pt.h" #define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret; namespace descartes_core { JointTrajectoryPt::JointTrajectoryPt(): tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints, const Frame &tool, const Frame &wobj): joint_position_(joints), tool_(tool), wobj_(wobj) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints): joint_position_(joints), tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) {} JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints): tool_(Eigen::Affine3d::Identity()), wobj_(Eigen::Affine3d::Identity()) { for (size_t ii = 0; ii < joints.size(); ++ii) { joint_position_.push_back(TolerancedJointValue(joints[ii])); } } bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { NOT_IMPLEMENTED_ERR(false) } bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state, const RobotModel &model, Eigen::Affine3d &pose) const { std::vector<double> joints; for(auto& tj: joint_position_) { joints.push_back(tj.nominal); } return model.getFK(joints,pose); } void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const { poses.clear(); } bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.assign(seed_state.begin(),seed_state.end()); } bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.resize(joint_position_.size()); for (size_t ii=0; ii<joint_position_.size(); ++ii) { joint_pose[ii] = joint_position_[ii].nominal; } return true; } void JointTrajectoryPt::getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { std::vector<double> empty_seed; joint_poses.resize(1); getNominalJointPose(empty_seed,model,joint_poses[0]); } bool JointTrajectoryPt::isValid(const RobotModel &model) const { std::vector<double> lower(joint_position_.size()); std::vector<double> upper(joint_position_.size()); for (size_t ii = 0; ii < joint_position_.size(); ++ii) { lower[ii] = joint_position_[ii].tolerance.lower; upper[ii] = joint_position_[ii].tolerance.upper; } return model.isValid(lower) && model.isValid(upper); } bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization) { if (discretization.size() != 1 || discretization.size() != joint_position_.size()) { logError("discretization must be size 1 or same size as joint count."); return false; } if (discretization.size() == 1) { discretization_ = std::vector<double>(joint_position_.size(), discretization[0]); return true; } /* Do not copy discretization values until all values are confirmed */ for (size_t ii=0; ii<discretization.size(); ++ii) { if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range()) { logError("discretization value out of range."); return false; } } discretization_ = discretization; return true; } } /* namespace descartes_core */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: services.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-03-15 12:23:44 $ * * 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): _______________________________________ * * ************************************************************************/ #include "evaluation.hxx" #ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_ #include <com/sun/star/beans/NamedValue.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _UNO_ENVIRONMENT_H_ #include <uno/environment.h> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #include "oemjob.hxx" #include "evaluation.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::registry; using namespace ::desktop; static const char* pServices[] = { SOEvaluation::serviceName, OEMPreloadJob::serviceName, NULL }; static const char* pImplementations[] = { SOEvaluation::implementationName, OEMPreloadJob::implementationName, NULL }; typedef Reference<XInterface>(* fProvider)(const Reference<XMultiServiceFactory>&); static const fProvider pInstanceProviders[] = { SOEvaluation::CreateInstance, OEMPreloadJob::CreateInstance, NULL }; static const char** pSupportedServices[] = { SOEvaluation::interfaces, OEMPreloadJob::interfaces, NULL }; static Sequence<OUString> getSupportedServiceNames(int p) { const char **names = pSupportedServices[p]; Sequence<OUString> aSeq; for(int i = 0; names[i] != NULL; i++) { aSeq.realloc(i+1); aSeq[i] = OUString::createFromAscii(names[i]); } return aSeq; } extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey) { Reference<XMultiServiceFactory> xMan( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; Reference<XRegistryKey> xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ; // iterate over service names and register them... OUString aImpl; const char* pServiceName = NULL; const char* pImplName = NULL; for (int i = 0; (pServices[i]!=NULL)&&(pImplementations[i]!=NULL); i++) { pServiceName= pServices[i]; pImplName = pImplementations[i]; aImpl = OUString::createFromAscii("/") + OUString::createFromAscii(pImplName) + OUString::createFromAscii("/UNO/SERVICES"); Reference<XRegistryKey> xNewKey = xKey->createKey(aImpl); xNewKey->createKey(OUString::createFromAscii(pServiceName)); } return sal_True; } void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey) { // Set default return value for this operation - if it failed. if ( pImplementationName && pServiceManager ) { Reference< XSingleServiceFactory > xFactory; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; // search implementation for (int i = 0; (pImplementations[i]!=NULL); i++) { if ( strcmp(pImplementations[i], pImplementationName ) == 0 ) { // found implementation xFactory = Reference<XSingleServiceFactory>(cppu::createSingleFactory( xServiceManager, OUString::createFromAscii(pImplementationName), pInstanceProviders[i], getSupportedServiceNames(i))); if ( xFactory.is() ) { // Factory is valid - service was found. xFactory->acquire(); return xFactory.get(); } } } // for() } // Return with result of this operation. return NULL; } } // extern "C" <commit_msg>INTEGRATION: CWS ooo19126 (1.4.126); FILE MERGED 2005/09/05 17:50:59 rt 1.4.126.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: services.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:48:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "evaluation.hxx" #ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_ #include <com/sun/star/beans/NamedValue.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _UNO_ENVIRONMENT_H_ #include <uno/environment.h> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #include "oemjob.hxx" #include "evaluation.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::registry; using namespace ::desktop; static const char* pServices[] = { SOEvaluation::serviceName, OEMPreloadJob::serviceName, NULL }; static const char* pImplementations[] = { SOEvaluation::implementationName, OEMPreloadJob::implementationName, NULL }; typedef Reference<XInterface>(* fProvider)(const Reference<XMultiServiceFactory>&); static const fProvider pInstanceProviders[] = { SOEvaluation::CreateInstance, OEMPreloadJob::CreateInstance, NULL }; static const char** pSupportedServices[] = { SOEvaluation::interfaces, OEMPreloadJob::interfaces, NULL }; static Sequence<OUString> getSupportedServiceNames(int p) { const char **names = pSupportedServices[p]; Sequence<OUString> aSeq; for(int i = 0; names[i] != NULL; i++) { aSeq.realloc(i+1); aSeq[i] = OUString::createFromAscii(names[i]); } return aSeq; } extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey) { Reference<XMultiServiceFactory> xMan( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; Reference<XRegistryKey> xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ; // iterate over service names and register them... OUString aImpl; const char* pServiceName = NULL; const char* pImplName = NULL; for (int i = 0; (pServices[i]!=NULL)&&(pImplementations[i]!=NULL); i++) { pServiceName= pServices[i]; pImplName = pImplementations[i]; aImpl = OUString::createFromAscii("/") + OUString::createFromAscii(pImplName) + OUString::createFromAscii("/UNO/SERVICES"); Reference<XRegistryKey> xNewKey = xKey->createKey(aImpl); xNewKey->createKey(OUString::createFromAscii(pServiceName)); } return sal_True; } void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey) { // Set default return value for this operation - if it failed. if ( pImplementationName && pServiceManager ) { Reference< XSingleServiceFactory > xFactory; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; // search implementation for (int i = 0; (pImplementations[i]!=NULL); i++) { if ( strcmp(pImplementations[i], pImplementationName ) == 0 ) { // found implementation xFactory = Reference<XSingleServiceFactory>(cppu::createSingleFactory( xServiceManager, OUString::createFromAscii(pImplementationName), pInstanceProviders[i], getSupportedServiceNames(i))); if ( xFactory.is() ) { // Factory is valid - service was found. xFactory->acquire(); return xFactory.get(); } } } // for() } // Return with result of this operation. return NULL; } } // extern "C" <|endoftext|>
<commit_before>// implementation for p_evaluate.h #include <Rd/r_index.h> #include <Rd/cdf_utils.h> #include <utils/array1d.h> #include <numerics/schoenberg_splines.h> namespace WaveletTL { template <int d, int dT> SampledMapping<1> evaluate(const PBasis<d,dT>& basis, const typename PBasis<d,dT>::Index& lambda, const bool primal, const int resolution) { if (lambda.e() == 0) { // generator if (primal) { Grid<1> grid(0, 1, 1<<resolution); MathTL::Array1D<double> values((1<<resolution)+1); for (unsigned int i(0); i < values.size(); i++) values[i] = evaluate(basis, 0, lambda, i*ldexp(1.0,-resolution)); return SampledMapping<1>(grid, values); } else { // dual int s0 = basis.get_s0(); int s1 = basis.get_s1(); const Matrix<double>& CLAT = basis.get_CLAT(); // left boundary generator if (lambda.k() < basis.DeltaLTmin()+(int)CLAT.column_dimension()) { if (s0 >= d-2) { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CLAT.row_dimension(); i++) { double v(CLAT(i, lambda.k()-basis.DeltaLTmin())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j(), 0, 1-ell2T<d,dT>()+i), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } else { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CLAT.row_dimension(); i++) { double v(CLAT(i, lambda.k()-basis.DeltaLTmin())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j()+1, 0, 1-ell2T<d,dT>()+i), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } } // no left boundary generator else { const Matrix<double>& CRAT = basis.get_CRAT(); if (lambda.k() > basis.DeltaRTmax(lambda.j())-(int)CRAT.column_dimension()) { if (s1 >= d-2) { // right boundary generator InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CRAT.row_dimension(); i++) { double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j(), 0, (1<<lambda.j())-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } else { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CRAT.row_dimension(); i++) { double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j()+1, 0, (1<<lambda.j()+1)-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } } // inner generator else { return basis.get_CDF_basis().evaluate(0, RIndex(lambda.j(), 0, lambda.k()), primal, 0, 1, resolution); } } } } else { // wavelet InfiniteVector<double, typename PBasis<d,dT>::Index> gcoeffs; if (primal) basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); else basis.reconstruct_t_1(lambda, lambda.j()+1, gcoeffs); return evaluate(basis, gcoeffs, primal, resolution); } return SampledMapping<1>(); // dummy return for the compiler } template <int d, int dT> SampledMapping<1> evaluate(const PBasis<d,dT>& basis, const InfiniteVector<double, typename PBasis<d,dT>::Index>& coeffs, const bool primal, const int resolution) { SampledMapping<1> result(Grid<1>(0, 1, 1<<resolution)); // zero if (coeffs.size() > 0) { // determine maximal level int jmax(0); typedef typename PBasis<d,dT>::Index Index; for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()), itend(coeffs.end()); it != itend; ++it) jmax = std::max(it.index().j()+it.index().e(), jmax); // switch to generator representation InfiniteVector<double,Index> gcoeffs; if (primal) basis.reconstruct(coeffs,jmax,gcoeffs); else basis.reconstruct_t(coeffs,jmax,gcoeffs); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()), itend(gcoeffs.end()); it != itend; ++it) result.add(*it, evaluate(basis, it.index(), primal, resolution)); } return result; } template <int d, int dT> double evaluate(const PBasis<d,dT>& basis, const unsigned int derivative, const typename PBasis<d,dT>::Index& lambda, const double x) { assert(derivative <= 1); // we only support derivatives up to the first order double r = 0; if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) { switch (derivative){ case 0: r= MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; } } else { switch (derivative){ case 0: r=MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x); break; case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x); break; case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x); break; } } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) r += *it * evaluate(basis, derivative, it.index(), x); } return r; } template <int d, int dT> void evaluate(const PBasis<d,dT>& basis, const unsigned int derivative, const typename PBasis<d,dT>::Index& lambda, const Array1D<double>& points, Array1D<double>& values) { assert(derivative <= 2); // we only support derivatives up to the second order values.resize(points.size()); for (unsigned int i(0); i < values.size(); i++) values[i] = 0; if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) switch (derivative) { case 0: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; case 1: for (unsigned int m(0); m < points.size(); m++) values[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; case 2: for (unsigned int m(0); m < points.size(); m++) values[m] = -MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; } else switch (derivative) { case 0: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), points[m]); break; case 1: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m]); break; case 2: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), points[m]); break; } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); Array1D<double> help(points.size()); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) { evaluate(basis, derivative, it.index(), points, help); for (unsigned int i = 0; i < points.size(); i++) values[i] += *it * help[i]; } } } template <int d, int dT> void evaluate(const PBasis<d,dT>& basis, const typename PBasis<d,dT>::Index& lambda, const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues) { const unsigned int npoints(points.size()); funcvalues.resize(npoints); dervalues.resize(npoints); for (unsigned int i(0); i < npoints; i++) { funcvalues[i] = 0; dervalues[i] = 0; } if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) { for (unsigned int m(0); m < npoints; m++) { funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); dervalues[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); } } else { for (unsigned int m(0); m < npoints; m++) { funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m]); dervalues[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m]); } } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); Array1D<double> help1, help2; for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) { evaluate(basis, it.index(), points, help1, help2); for (unsigned int i = 0; i < npoints; i++) { funcvalues[i] += *it * help1[i]; dervalues[i] += *it * help2[i]; } } } } } <commit_msg>Minor mistakes eliminated<commit_after>// implementation for p_evaluate.h #include <Rd/r_index.h> #include <Rd/cdf_utils.h> #include <utils/array1d.h> #include <numerics/schoenberg_splines.h> namespace WaveletTL { template <int d, int dT> SampledMapping<1> evaluate(const PBasis<d,dT>& basis, const typename PBasis<d,dT>::Index& lambda, const bool primal, const int resolution) { if (lambda.e() == 0) { // generator if (primal) { Grid<1> grid(0, 1, 1<<resolution); MathTL::Array1D<double> values((1<<resolution)+1); for (unsigned int i(0); i < values.size(); i++) values[i] = evaluate(basis, 0, lambda, i*ldexp(1.0,-resolution)); return SampledMapping<1>(grid, values); } else { // dual int s0 = basis.get_s0(); int s1 = basis.get_s1(); const Matrix<double>& CLAT = basis.get_CLAT(); // left boundary generator if (lambda.k() < basis.DeltaLTmin()+(int)CLAT.column_dimension()) { if (s0 >= d-2) { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CLAT.row_dimension(); i++) { double v(CLAT(i, lambda.k()-basis.DeltaLTmin())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j(), 0, 1-ell2T<d,dT>()+i), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } else { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CLAT.row_dimension(); i++) { double v(CLAT(i, lambda.k()-basis.DeltaLTmin())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j()+1, 0, 1-ell2T<d,dT>()+i), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } } // no left boundary generator else { const Matrix<double>& CRAT = basis.get_CRAT(); if (lambda.k() > basis.DeltaRTmax(lambda.j())-(int)CRAT.column_dimension()) { if (s1 >= d-2) { // right boundary generator InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CRAT.row_dimension(); i++) { double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j(), 0, (1<<lambda.j())-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } else { InfiniteVector<double, RIndex> coeffs; for (unsigned int i(0); i < CRAT.row_dimension(); i++) { double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k())); if (v != 0) coeffs.set_coefficient(RIndex(lambda.j()+1, 0, (1<<lambda.j()+1)-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v); } return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution); } } // inner generator else { return basis.get_CDF_basis().evaluate(0, RIndex(lambda.j(), 0, lambda.k()), primal, 0, 1, resolution); } } } } else { // wavelet InfiniteVector<double, typename PBasis<d,dT>::Index> gcoeffs; if (primal) basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); else basis.reconstruct_t_1(lambda, lambda.j()+1, gcoeffs); return evaluate(basis, gcoeffs, primal, resolution); } return SampledMapping<1>(); // dummy return for the compiler } template <int d, int dT> SampledMapping<1> evaluate(const PBasis<d,dT>& basis, const InfiniteVector<double, typename PBasis<d,dT>::Index>& coeffs, const bool primal, const int resolution) { SampledMapping<1> result(Grid<1>(0, 1, 1<<resolution)); // zero if (coeffs.size() > 0) { // determine maximal level int jmax(0); typedef typename PBasis<d,dT>::Index Index; for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()), itend(coeffs.end()); it != itend; ++it) jmax = std::max(it.index().j()+it.index().e(), jmax); // switch to generator representation InfiniteVector<double,Index> gcoeffs; if (primal) basis.reconstruct(coeffs,jmax,gcoeffs); else basis.reconstruct_t(coeffs,jmax,gcoeffs); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()), itend(gcoeffs.end()); it != itend; ++it) result.add(*it, evaluate(basis, it.index(), primal, resolution)); } return result; } template <int d, int dT> double evaluate(const PBasis<d,dT>& basis, const unsigned int derivative, const typename PBasis<d,dT>::Index& lambda, const double x) { assert(derivative <= 1); // we only support derivatives up to the first order double r = 0; if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) { switch (derivative){ case 0: r= MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; case 1: r=-MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x); break; } } else { switch (derivative){ case 0: r=MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x); break; case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x); break; case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x); break; } } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) r += *it * evaluate(basis, derivative, it.index(), x); } return r; } template <int d, int dT> void evaluate(const PBasis<d,dT>& basis, const unsigned int derivative, const typename PBasis<d,dT>::Index& lambda, const Array1D<double>& points, Array1D<double>& values) { assert(derivative <= 2); // we only support derivatives up to the second order values.resize(points.size()); for (unsigned int i(0); i < values.size(); i++) values[i] = 0; if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) switch (derivative) { case 0: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; case 1: for (unsigned int m(0); m < points.size(); m++) values[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; case 2: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); break; } else switch (derivative) { case 0: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), points[m]); break; case 1: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m]); break; case 2: for (unsigned int m(0); m < points.size(); m++) values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), points[m]); break; } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); Array1D<double> help(points.size()); for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) { evaluate(basis, derivative, it.index(), points, help); for (unsigned int i = 0; i < points.size(); i++) values[i] += *it * help[i]; } } } template <int d, int dT> void evaluate(const PBasis<d,dT>& basis, const typename PBasis<d,dT>::Index& lambda, const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues) { const unsigned int npoints(points.size()); funcvalues.resize(npoints); dervalues.resize(npoints); for (unsigned int i(0); i < npoints; i++) { funcvalues[i] = 0; dervalues[i] = 0; } if (lambda.e() == 0) { // generator if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) { for (unsigned int m(0); m < npoints; m++) { funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); dervalues[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m]); } } else { for (unsigned int m(0); m < npoints; m++) { funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m]); dervalues[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m]); } } } else { // wavelet typedef typename PBasis<d,dT>::Index Index; InfiniteVector<double,Index> gcoeffs; basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs); Array1D<double> help1, help2; for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()); it != gcoeffs.end(); ++it) { evaluate(basis, it.index(), points, help1, help2); for (unsigned int i = 0; i < npoints; i++) { funcvalues[i] += *it * help1[i]; dervalues[i] += *it * help2[i]; } } } } } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/base_layer_derivations/base_filterbanklayer.h" #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "elm/core/cv/mat_vector_utils.h" #include "elm/core/layeroutputnames.h" #include "elm/core/signal.h" using namespace cv; using namespace elm; base_FilterBankLayer::~base_FilterBankLayer() { } base_FilterBankLayer::base_FilterBankLayer() : base_SingleInputFeatureLayer() { } base_FilterBankLayer::base_FilterBankLayer(const LayerConfig &cfg) : base_SingleInputFeatureLayer(cfg) { } void base_FilterBankLayer::Clear() { kernels_ = VecMat1f(); response_ = VecMat1f(); } void base_FilterBankLayer::Reset(const LayerConfig &config) { Clear(); Reconfigure(config); kernels_ = Kernels(); } void base_FilterBankLayer::OutputNames(const LayerOutputNames &io) { name_out_ = io.Output(KEY_OUTPUT_RESPONSE); } void base_FilterBankLayer::Activate(const Signal &signal) { response_.clear(); response_.reserve(kernels_.size()); response_ = Convolve(signal.MostRecentMat1f(name_input_)); } void base_FilterBankLayer::Response(Signal &signal) { signal.Append(name_out_, response_); } VecMat1f base_FilterBankLayer::Convolve(const cv::Mat1f &stimulus) { for(VecMat1f::const_iterator itr=kernels_.begin(); itr != kernels_.end(); itr++) { Mat1f r; filter2D(stimulus, r, -1, *itr, Point(-1, -1), 0, BORDER_REPLICATE); Rectify(r); response_.push_back(r); } return response_; } void base_FilterBankLayer::Rectify(Mat1f &response) { // default is to do nothing and leave response as is } Mat1f base_FilterBankLayer::ElementResponse(int r, int c) const { return elm::ElementsAt(response_, r, c); } size_t base_FilterBankLayer::size() const { return Kernels().size(); } <commit_msg>responses are cleared with every call to Convolve()<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/base_layer_derivations/base_filterbanklayer.h" #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "elm/core/cv/mat_vector_utils.h" #include "elm/core/layeroutputnames.h" #include "elm/core/signal.h" using namespace cv; using namespace elm; base_FilterBankLayer::~base_FilterBankLayer() { } base_FilterBankLayer::base_FilterBankLayer() : base_SingleInputFeatureLayer() { } base_FilterBankLayer::base_FilterBankLayer(const LayerConfig &cfg) : base_SingleInputFeatureLayer(cfg) { } void base_FilterBankLayer::Clear() { kernels_ = VecMat1f(); response_ = VecMat1f(); } void base_FilterBankLayer::Reset(const LayerConfig &config) { Clear(); Reconfigure(config); kernels_ = Kernels(); } void base_FilterBankLayer::OutputNames(const LayerOutputNames &io) { name_out_ = io.Output(KEY_OUTPUT_RESPONSE); } void base_FilterBankLayer::Activate(const Signal &signal) { response_ = Convolve(signal.MostRecentMat1f(name_input_)); } void base_FilterBankLayer::Response(Signal &signal) { signal.Append(name_out_, response_); } VecMat1f base_FilterBankLayer::Convolve(const cv::Mat1f &stimulus) { response_.clear(); response_.reserve(kernels_.size()); for(VecMat1f::const_iterator itr=kernels_.begin(); itr != kernels_.end(); itr++) { Mat1f r; filter2D(stimulus, r, -1, *itr, Point(-1, -1), 0, BORDER_REPLICATE); Rectify(r); response_.push_back(r); } return response_; } void base_FilterBankLayer::Rectify(Mat1f &response) { // default is to do nothing and leave response as is } Mat1f base_FilterBankLayer::ElementResponse(int r, int c) const { return elm::ElementsAt(response_, r, c); } size_t base_FilterBankLayer::size() const { return Kernels().size(); } <|endoftext|>
<commit_before>// // // Copyright (C) 2004 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdio.h> #include <signal.h> #include <iostream> // APPLICATION INCLUDES #ifndef SIPX_VERSION # include "sipxregistry-buildstamp.h" # define SIPXCHANGE_VERSION SipXregistryVersion # define SIPXCHANGE_VERSION_COMMENT SipXregistryBuildStamp #else # define SIPXCHANGE_VERSION SIPX_VERSION # define SIPXCHANGE_VERSION_COMMENT "" #endif #include "os/OsConfigDb.h" #include "os/OsFS.h" #include "os/OsTask.h" #include "net/NameValueTokenizer.h" #include "sipdb/SIPDBManager.h" #include "sipdb/ExtensionDB.h" #include "SipRegistrar.h" // DEFINES #define CONFIG_SETTINGS_FILE "registrar-config" #define CONFIG_LOG_FILE "sipregistrar.log" #define CONFIG_LOG_DIR SIPX_LOGDIR #define CONFIG_ETC_DIR SIPX_CONFDIR #define CONFIG_SETTING_LOG_LEVEL "SIP_REGISTRAR_LOG_LEVEL" #define CONFIG_SETTING_LOG_CONSOLE "SIP_REGISTRAR_LOG_CONSOLE" #define CONFIG_SETTING_LOG_DIR "SIP_REGISTRAR_LOG_DIR" #define LOG_FACILITY FAC_SIP // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef void (*sighandler_t)(int); using namespace std ; // FUNCTIONS extern "C" { void sigHandler( int sig_num ); sighandler_t pt_signal( int sig_num, sighandler_t handler ); } // FORWARD DECLARATIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // GLOBAL VARIABLE INITIALIZATIONS OsServerTask* pServerTask = NULL; UtlBoolean gShutdownFlag = FALSE; UtlBoolean gClosingIMDB = FALSE; OsMutex* gpLockMutex = new OsMutex(OsMutex::Q_FIFO); /* ============================ FUNCTIONS ================================= */ /** * Description: * closes any open connections to the IMDB safely using a mutex lock */ void closeIMDBConnections () { // Critical Section here OsLock lock( *gpLockMutex ); SIPDBManager* db = SIPDBManager::getInstance(); db->releaseAllDatabase(); delete db; } /** * Description: * This is a replacement for signal() which registers a signal handler but sets * a flag causing system calls ( namely read() or getchar() ) not to bail out * upon recepit of that signal. We need this behavior, so we must call * sigaction() manually. */ sighandler_t pt_signal( int sig_num, sighandler_t handler) { #if defined(__pingtel_on_posix__) struct sigaction action[2]; action[0].sa_handler = handler; sigemptyset(&action[0].sa_mask); action[0].sa_flags = 0; sigaction ( sig_num, &action[0], &action[1] ); return action[1].sa_handler; #else return signal( sig_num, handler ); #endif } /** * Description: * This is the signal handler, When called this sets the * global gShutdownFlag allowing the main processing * loop to exit cleanly. */ void sigHandler( int sig_num ) { // set a global shutdown flag gShutdownFlag = TRUE; // Unregister interest in the signal to prevent recursive callbacks pt_signal( sig_num, SIG_DFL ); // Minimize the chance that we loose log data OsSysLog::flush(); if (SIGTERM == sig_num) { OsSysLog::add( LOG_FACILITY, PRI_INFO, "sigHandler: terminate signal received."); } else { OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: caught signal: %d", sig_num ); } OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: closing IMDB connections" ); OsSysLog::flush(); // Finally close the IMDB connections closeIMDBConnections(); } // Initialize the OsSysLog void initSysLog(OsConfigDb* pConfig) { UtlString logLevel; // Controls Log Verbosity UtlString consoleLogging; // Enable console logging by default? UtlString fileTarget; // Path to store log file. UtlBoolean bSpecifiedDirError ; // Set if the specified log dir does not // exist struct tagPriorityLookupTable { const char* pIdentity; OsSysLogPriority ePriority; }; struct tagPriorityLookupTable lkupTable[] = { { "DEBUG", PRI_DEBUG}, { "INFO", PRI_INFO}, { "NOTICE", PRI_NOTICE}, { "WARNING", PRI_WARNING}, { "ERR", PRI_ERR}, { "CRIT", PRI_CRIT}, { "ALERT", PRI_ALERT}, { "EMERG", PRI_EMERG}, }; OsSysLog::initialize(0, "SipRegistrar"); // // Get/Apply Log Filename // fileTarget.remove(0) ; if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) || fileTarget.isNull() || !OsFileSystem::exists(fileTarget)) { bSpecifiedDirError = !fileTarget.isNull() ; // If the log file directory exists use that, otherwise place the log // in the current directory OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_LOG_DIR)) { fileTarget = CONFIG_LOG_DIR; OsPath path(fileTarget); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } fileTarget = workingDirectory + OsPathBase::separator + CONFIG_LOG_FILE; } else { bSpecifiedDirError = false ; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; fileTarget = fileTarget + OsPathBase::separator + CONFIG_LOG_FILE; } OsSysLog::setOutputFile(0, fileTarget) ; // // Get/Apply Log Level // if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) || logLevel.isNull()) { logLevel = "NOTICE"; } logLevel.toUpper(); OsSysLogPriority priority = PRI_ERR; int iEntries = sizeof(lkupTable)/sizeof(struct tagPriorityLookupTable); for (int i=0; i<iEntries; i++) { if (logLevel == lkupTable[i].pIdentity) { priority = lkupTable[i].ePriority; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ; break; } } OsSysLog::setLoggingPriority(priority); // // Get/Apply console logging // UtlBoolean bConsoleLoggingEnabled = false ; if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS)) { consoleLogging.toUpper(); if (consoleLogging == "ENABLE") { OsSysLog::enableConsoleOutput(true); bConsoleLoggingEnabled = true ; } } OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; if (bSpecifiedDirError) { OsSysLog::add(FAC_LOG, PRI_CRIT, "Cannot access directory '%s'; please check configuration.", CONFIG_SETTING_LOG_DIR); } } /** The main entry point to the sipregistrar */ int main(int argc, char* argv[] ) { // Configuration Database (used for OsSysLog) OsConfigDb configDb; // Register Signal handlers to close IMDB pt_signal(SIGINT, sigHandler); // Trap Ctrl-C on NT pt_signal(SIGILL, sigHandler); pt_signal(SIGABRT, sigHandler); // Abort signal 6 pt_signal(SIGFPE, sigHandler); // Floading Point Exception pt_signal(SIGSEGV, sigHandler); // Address access violations signal 11 pt_signal(SIGTERM, sigHandler); // Trap kill -15 on UNIX #if defined(__pingtel_on_posix__) pt_signal(SIGHUP, sigHandler); // Hangup pt_signal(SIGQUIT, sigHandler); pt_signal(SIGPIPE, SIG_IGN); // Handle TCP Failure pt_signal(SIGBUS, sigHandler); pt_signal(SIGSYS, sigHandler); pt_signal(SIGXCPU, sigHandler); pt_signal(SIGXFSZ, sigHandler); pt_signal(SIGUSR1, sigHandler); pt_signal(SIGUSR2, sigHandler); #endif UtlBoolean interactiveSet = false; UtlString argString; for (int argIndex = 1; argIndex < argc; argIndex++) { osPrintf("arg[%d]: %s\n", argIndex, argv[argIndex]); argString = argv[argIndex]; NameValueTokenizer::frontBackTrim(&argString, "\t "); if (argString.compareTo("-v") == 0) { osPrintf("Version: %s (%s)\n", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT); return(1); } else if ( argString.compareTo("-i") == 0) { interactiveSet = true; osPrintf("Entering Interactive Mode\n"); } else { osPrintf("usage: %s [-v] [-i]\nwhere:\n -v provides the software version\n" " -i start the server in an interactive mode\n", argv[0]); return(1); } } // initialize log file OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_ETC_DIR)) { workingDirectory = CONFIG_ETC_DIR; OsPath path(workingDirectory); path.getNativePath(workingDirectory); } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); } UtlString fileName = workingDirectory + OsPathBase::separator + CONFIG_SETTINGS_FILE; bool configLoaded = ( configDb.loadFromFile(fileName) == OS_SUCCESS ); if (!configLoaded) { configDb.set("SIP_REGISTRAR_UDP_PORT", "5070"); configDb.set("SIP_REGISTRAR_TCP_PORT", "5070"); configDb.set("SIP_REGISTRAR_TLS_PORT", "5071"); configDb.set("SIP_REGISTRAR_PROXY_PORT", "5060"); configDb.set("SIP_REGISTRAR_MAX_EXPIRES", ""); configDb.set("SIP_REGISTRAR_MIN_EXPIRES", ""); configDb.set("SIP_REGISTRAR_DOMAIN_NAME", ""); //configDb.set("SIP_REGISTRAR_AUTHENTICATE_SCHEME", ""); configDb.set("SIP_REGISTRAR_AUTHENTICATE_ALGORITHM", ""); configDb.set("SIP_REGISTRAR_AUTHENTICATE_QOP", ""); configDb.set("SIP_REGISTRAR_AUTHENTICATE_REALM", ""); configDb.set("SIP_REGISTRAR_MEDIA_SERVER", ""); configDb.set("SIP_REGISTRAR_VOICEMAIL_SERVER", ""); configDb.set(CONFIG_SETTING_LOG_DIR, ""); configDb.set(CONFIG_SETTING_LOG_LEVEL, ""); configDb.set(CONFIG_SETTING_LOG_CONSOLE, ""); } initSysLog(&configDb) ; OsSysLog::add(FAC_SIP, PRI_NOTICE, "SipRegistrar >>>>>>>>>>>>>>>> STARTED" ); if (configLoaded) { OsSysLog::add(FAC_SIP, PRI_INFO, "Read config %s", fileName.data()); } else { if (configDb.storeToFile(fileName) == OS_SUCCESS) { OsSysLog::add( FAC_SIP, PRI_INFO, "Default config written to: %s", fileName.data() ); } else { OsSysLog::add( FAC_SIP, PRI_ERR, "Default config write failed to: %s", fileName.data()); } } // Fetch Pointer to the OsServer task object, note that // object uses the IMDB so it is important to shut this thread // cleanly before the signal handler exits SipRegistrar* registrar = SipRegistrar::getInstance(&configDb); registrar->start(); pServerTask = static_cast<OsServerTask*>(registrar); // Do not exit, let the services run... while( !gShutdownFlag ) { if ( interactiveSet) { int charCode = getchar(); if (charCode != '\n' && charCode != '\r') { if ( charCode == 'e') { OsSysLog::enableConsoleOutput(TRUE); } else if ( charCode == 'd') { OsSysLog::enableConsoleOutput(FALSE); } } } else { OsTask::delay(2000); } } // Remove the current process's row from the IMDB // Persisting the database if necessary // This is a server task so gracefully shutdown the // server task using the waitForShutdown method, this // will implicitly request a shutdown for us if one is // not already in progress if ( pServerTask != NULL ) { // Deleting a server task is the only way of // waiting for shutdown to complete cleanly pServerTask->requestShutdown(); delete pServerTask; pServerTask = NULL; } // now deregister this process's database references from the IMDB closeIMDBConnections(); // Flush the log file OsSysLog::flush(); return 0; } <commit_msg>Heap-alloc the config DB, don't stack-alloc it, since we are passing it to SipRegistrar, which holds onto it for a little while. Unlikely to cause problems in practice but must be done right.<commit_after>// // // Copyright (C) 2004 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdio.h> #include <signal.h> #include <iostream> // APPLICATION INCLUDES #ifndef SIPX_VERSION # include "sipxregistry-buildstamp.h" # define SIPXCHANGE_VERSION SipXregistryVersion # define SIPXCHANGE_VERSION_COMMENT SipXregistryBuildStamp #else # define SIPXCHANGE_VERSION SIPX_VERSION # define SIPXCHANGE_VERSION_COMMENT "" #endif #include "os/OsConfigDb.h" #include "os/OsFS.h" #include "os/OsTask.h" #include "net/NameValueTokenizer.h" #include "sipdb/SIPDBManager.h" #include "sipdb/ExtensionDB.h" #include "SipRegistrar.h" // DEFINES #define CONFIG_SETTINGS_FILE "registrar-config" #define CONFIG_LOG_FILE "sipregistrar.log" #define CONFIG_LOG_DIR SIPX_LOGDIR #define CONFIG_ETC_DIR SIPX_CONFDIR #define CONFIG_SETTING_LOG_LEVEL "SIP_REGISTRAR_LOG_LEVEL" #define CONFIG_SETTING_LOG_CONSOLE "SIP_REGISTRAR_LOG_CONSOLE" #define CONFIG_SETTING_LOG_DIR "SIP_REGISTRAR_LOG_DIR" #define LOG_FACILITY FAC_SIP // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef void (*sighandler_t)(int); using namespace std ; // FUNCTIONS extern "C" { void sigHandler( int sig_num ); sighandler_t pt_signal( int sig_num, sighandler_t handler ); } // FORWARD DECLARATIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // GLOBAL VARIABLE INITIALIZATIONS OsServerTask* pServerTask = NULL; UtlBoolean gShutdownFlag = FALSE; UtlBoolean gClosingIMDB = FALSE; OsMutex* gpLockMutex = new OsMutex(OsMutex::Q_FIFO); /* ============================ FUNCTIONS ================================= */ /** * Description: * closes any open connections to the IMDB safely using a mutex lock */ void closeIMDBConnections () { // Critical Section here OsLock lock( *gpLockMutex ); SIPDBManager* db = SIPDBManager::getInstance(); db->releaseAllDatabase(); delete db; } /** * Description: * This is a replacement for signal() which registers a signal handler but sets * a flag causing system calls ( namely read() or getchar() ) not to bail out * upon recepit of that signal. We need this behavior, so we must call * sigaction() manually. */ sighandler_t pt_signal( int sig_num, sighandler_t handler) { #if defined(__pingtel_on_posix__) struct sigaction action[2]; action[0].sa_handler = handler; sigemptyset(&action[0].sa_mask); action[0].sa_flags = 0; sigaction ( sig_num, &action[0], &action[1] ); return action[1].sa_handler; #else return signal( sig_num, handler ); #endif } /** * Description: * This is the signal handler, When called this sets the * global gShutdownFlag allowing the main processing * loop to exit cleanly. */ void sigHandler( int sig_num ) { // set a global shutdown flag gShutdownFlag = TRUE; // Unregister interest in the signal to prevent recursive callbacks pt_signal( sig_num, SIG_DFL ); // Minimize the chance that we loose log data OsSysLog::flush(); if (SIGTERM == sig_num) { OsSysLog::add( LOG_FACILITY, PRI_INFO, "sigHandler: terminate signal received."); } else { OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: caught signal: %d", sig_num ); } OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: closing IMDB connections" ); OsSysLog::flush(); // Finally close the IMDB connections closeIMDBConnections(); } // Initialize the OsSysLog void initSysLog(OsConfigDb* pConfig) { UtlString logLevel; // Controls Log Verbosity UtlString consoleLogging; // Enable console logging by default? UtlString fileTarget; // Path to store log file. UtlBoolean bSpecifiedDirError ; // Set if the specified log dir does not // exist struct tagPriorityLookupTable { const char* pIdentity; OsSysLogPriority ePriority; }; struct tagPriorityLookupTable lkupTable[] = { { "DEBUG", PRI_DEBUG}, { "INFO", PRI_INFO}, { "NOTICE", PRI_NOTICE}, { "WARNING", PRI_WARNING}, { "ERR", PRI_ERR}, { "CRIT", PRI_CRIT}, { "ALERT", PRI_ALERT}, { "EMERG", PRI_EMERG}, }; OsSysLog::initialize(0, "SipRegistrar"); // // Get/Apply Log Filename // fileTarget.remove(0) ; if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) || fileTarget.isNull() || !OsFileSystem::exists(fileTarget)) { bSpecifiedDirError = !fileTarget.isNull() ; // If the log file directory exists use that, otherwise place the log // in the current directory OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_LOG_DIR)) { fileTarget = CONFIG_LOG_DIR; OsPath path(fileTarget); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } fileTarget = workingDirectory + OsPathBase::separator + CONFIG_LOG_FILE; } else { bSpecifiedDirError = false ; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; fileTarget = fileTarget + OsPathBase::separator + CONFIG_LOG_FILE; } OsSysLog::setOutputFile(0, fileTarget) ; // // Get/Apply Log Level // if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) || logLevel.isNull()) { logLevel = "NOTICE"; } logLevel.toUpper(); OsSysLogPriority priority = PRI_ERR; int iEntries = sizeof(lkupTable)/sizeof(struct tagPriorityLookupTable); for (int i=0; i<iEntries; i++) { if (logLevel == lkupTable[i].pIdentity) { priority = lkupTable[i].ePriority; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ; OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ; break; } } OsSysLog::setLoggingPriority(priority); // // Get/Apply console logging // UtlBoolean bConsoleLoggingEnabled = false ; if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS)) { consoleLogging.toUpper(); if (consoleLogging == "ENABLE") { OsSysLog::enableConsoleOutput(true); bConsoleLoggingEnabled = true ; } } OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; if (bSpecifiedDirError) { OsSysLog::add(FAC_LOG, PRI_CRIT, "Cannot access directory '%s'; please check configuration.", CONFIG_SETTING_LOG_DIR); } } /** The main entry point to the sipregistrar */ int main(int argc, char* argv[] ) { // Configuration Database (used for OsSysLog) OsConfigDb* configDb = new OsConfigDb(); // Register Signal handlers to close IMDB pt_signal(SIGINT, sigHandler); // Trap Ctrl-C on NT pt_signal(SIGILL, sigHandler); pt_signal(SIGABRT, sigHandler); // Abort signal 6 pt_signal(SIGFPE, sigHandler); // Floading Point Exception pt_signal(SIGSEGV, sigHandler); // Address access violations signal 11 pt_signal(SIGTERM, sigHandler); // Trap kill -15 on UNIX #if defined(__pingtel_on_posix__) pt_signal(SIGHUP, sigHandler); // Hangup pt_signal(SIGQUIT, sigHandler); pt_signal(SIGPIPE, SIG_IGN); // Handle TCP Failure pt_signal(SIGBUS, sigHandler); pt_signal(SIGSYS, sigHandler); pt_signal(SIGXCPU, sigHandler); pt_signal(SIGXFSZ, sigHandler); pt_signal(SIGUSR1, sigHandler); pt_signal(SIGUSR2, sigHandler); #endif UtlBoolean interactiveSet = false; UtlString argString; for (int argIndex = 1; argIndex < argc; argIndex++) { osPrintf("arg[%d]: %s\n", argIndex, argv[argIndex]); argString = argv[argIndex]; NameValueTokenizer::frontBackTrim(&argString, "\t "); if (argString.compareTo("-v") == 0) { osPrintf("Version: %s (%s)\n", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT); return(1); } else if ( argString.compareTo("-i") == 0) { interactiveSet = true; osPrintf("Entering Interactive Mode\n"); } else { osPrintf("usage: %s [-v] [-i]\nwhere:\n -v provides the software version\n" " -i start the server in an interactive mode\n", argv[0]); return(1); } } // initialize log file OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_ETC_DIR)) { workingDirectory = CONFIG_ETC_DIR; OsPath path(workingDirectory); path.getNativePath(workingDirectory); } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); } UtlString fileName = workingDirectory + OsPathBase::separator + CONFIG_SETTINGS_FILE; bool configLoaded = ( configDb->loadFromFile(fileName) == OS_SUCCESS ); if (!configLoaded) { configDb->set("SIP_REGISTRAR_UDP_PORT", "5070"); configDb->set("SIP_REGISTRAR_TCP_PORT", "5070"); configDb->set("SIP_REGISTRAR_TLS_PORT", "5071"); configDb->set("SIP_REGISTRAR_PROXY_PORT", "5060"); configDb->set("SIP_REGISTRAR_MAX_EXPIRES", ""); configDb->set("SIP_REGISTRAR_MIN_EXPIRES", ""); configDb->set("SIP_REGISTRAR_DOMAIN_NAME", ""); //configDb->set("SIP_REGISTRAR_AUTHENTICATE_SCHEME", ""); configDb->set("SIP_REGISTRAR_AUTHENTICATE_ALGORITHM", ""); configDb->set("SIP_REGISTRAR_AUTHENTICATE_QOP", ""); configDb->set("SIP_REGISTRAR_AUTHENTICATE_REALM", ""); configDb->set("SIP_REGISTRAR_MEDIA_SERVER", ""); configDb->set("SIP_REGISTRAR_VOICEMAIL_SERVER", ""); configDb->set(CONFIG_SETTING_LOG_DIR, ""); configDb->set(CONFIG_SETTING_LOG_LEVEL, ""); configDb->set(CONFIG_SETTING_LOG_CONSOLE, ""); } initSysLog(configDb) ; OsSysLog::add(FAC_SIP, PRI_NOTICE, "SipRegistrar >>>>>>>>>>>>>>>> STARTED" ); if (configLoaded) { OsSysLog::add(FAC_SIP, PRI_INFO, "Read config %s", fileName.data()); } else { if (configDb->storeToFile(fileName) == OS_SUCCESS) { OsSysLog::add( FAC_SIP, PRI_INFO, "Default config written to: %s", fileName.data() ); } else { OsSysLog::add( FAC_SIP, PRI_ERR, "Default config write failed to: %s", fileName.data()); } } // Fetch Pointer to the OsServer task object, note that // object uses the IMDB so it is important to shut this thread // cleanly before the signal handler exits SipRegistrar* registrar = SipRegistrar::getInstance(configDb); registrar->start(); pServerTask = static_cast<OsServerTask*>(registrar); // Do not exit, let the services run... while( !gShutdownFlag ) { if ( interactiveSet) { int charCode = getchar(); if (charCode != '\n' && charCode != '\r') { if ( charCode == 'e') { OsSysLog::enableConsoleOutput(TRUE); } else if ( charCode == 'd') { OsSysLog::enableConsoleOutput(FALSE); } } } else { OsTask::delay(2000); } } // Remove the current process's row from the IMDB // Persisting the database if necessary // This is a server task so gracefully shutdown the // server task using the waitForShutdown method, this // will implicitly request a shutdown for us if one is // not already in progress if ( pServerTask != NULL ) { // Deleting a server task is the only way of // waiting for shutdown to complete cleanly pServerTask->requestShutdown(); delete pServerTask; pServerTask = NULL; } // now deregister this process's database references from the IMDB closeIMDBConnections(); if ( configDb != NULL ) { delete configDb; } // Flush the log file OsSysLog::flush(); return 0; } <|endoftext|>
<commit_before>/****************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * 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 "simulator_manager.h" #include "simulator_resource_factory.h" #include "simulator_remote_resource_impl.h" #include "simulator_utils.h" SimulatorManager *SimulatorManager::getInstance() { static SimulatorManager s_instance; return &s_instance; } SimulatorManager::SimulatorManager() { OC::PlatformConfig conf { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces 0, // Uses randomly available port OC::QualityOfService::LowQos }; OC::OCPlatform::Configure(conf); } std::shared_ptr<SimulatorResource> SimulatorManager::createResource( const std::string &configPath) { VALIDATE_INPUT(configPath.empty(), "Empty path!") std::shared_ptr<SimulatorResource> resource; try { resource = SimulatorResourceFactory::getInstance()->createResource(configPath); if (!resource) throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } catch (RAML::RamlException &e) { throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } return resource; } std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource( const std::string &configPath, unsigned int count) { VALIDATE_INPUT(configPath.empty(), "Empty path!") VALIDATE_INPUT(!count, "Count is zero!") std::vector<std::shared_ptr<SimulatorResource>> resources; try { resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count); if (!resources.size()) throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } catch (RAML::RamlException &e) { throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } return resources; } std::shared_ptr<SimulatorSingleResource> SimulatorManager::createSingleResource( const std::string &name, const std::string &uri, const std::string &resourceType) { VALIDATE_INPUT(name.empty(), "Empty resource name!") VALIDATE_INPUT(uri.empty(), "Empty URI!") VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType); } std::shared_ptr<SimulatorCollectionResource> SimulatorManager::createCollectionResource( const std::string &name, const std::string &uri, const std::string &resourceType) { VALIDATE_INPUT(name.empty(), "Empty resource name!") VALIDATE_INPUT(uri.empty(), "Empty URI!") VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType); } void SimulatorManager::findResource(ResourceFindCallback callback) { VALIDATE_CALLBACK(callback) OC::FindCallback findCallback = std::bind( [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback) { if (!ocResource) return; callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource)); }, std::placeholders::_1, callback); typedef OCStackResult (*FindResource)(const std::string &, const std::string &, OCConnectivityType, OC::FindCallback); invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback); } void SimulatorManager::findResource(const std::string &resourceType, ResourceFindCallback callback) { VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") VALIDATE_CALLBACK(callback) OC::FindCallback findCallback = std::bind( [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback) { if (!ocResource) return; callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource)); }, std::placeholders::_1, callback); std::ostringstream query; query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType; typedef OCStackResult (*FindResource)(const std::string &, const std::string &, OCConnectivityType, OC::FindCallback); invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(), CT_DEFAULT, findCallback); } void SimulatorManager::getDeviceInfo(const std::string &host, DeviceInfoCallback callback) { VALIDATE_CALLBACK(callback) OC::FindDeviceCallback deviceCallback = std::bind( [](const OC::OCRepresentation & rep, const std::string & hostUri, DeviceInfoCallback callback) { std::string deviceName = rep.getValue<std::string>("n"); std::string deviceID = rep.getValue<std::string>("di"); std::string deviceSpecVersion = rep.getValue<std::string>("lcv"); std::string deviceDMV = rep.getValue<std::string>("dmv"); DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV); callback(hostUri, deviceInfo); }, std::placeholders::_1, host, callback); typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &, OCConnectivityType, OC::FindDeviceCallback); invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), host.c_str(), "/oic/d", CT_DEFAULT, deviceCallback); } void SimulatorManager::setDeviceInfo(const std::string &deviceName) { VALIDATE_INPUT(deviceName.empty(), "Empty resource type!") typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo); OCDeviceInfo ocDeviceInfo; ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str()); invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo), ocDeviceInfo); } void SimulatorManager::getPlatformInfo(const std::string &host, PlatformInfoCallback callback) { VALIDATE_CALLBACK(callback) OC::FindPlatformCallback platformCallback = std::bind( [](const OC::OCRepresentation & rep, const std::string & hostUri, PlatformInfoCallback callback) { PlatformInfo platformInfo; platformInfo.setPlatformID(rep.getValue<std::string>("pi")); platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv")); platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn")); platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml")); platformInfo.setModelNumber(rep.getValue<std::string>("mnmo")); platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt")); platformInfo.setOSVersion(rep.getValue<std::string>("mnos")); platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw")); platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv")); platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl")); platformInfo.setSystemTime(rep.getValue<std::string>("st")); callback(hostUri, platformInfo); }, std::placeholders::_1, host, callback); typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &, OCConnectivityType, OC::FindPlatformCallback); invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), host.c_str(), "/oic/p", CT_DEFAULT, platformCallback); } void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo) { OCPlatformInfo ocPlatformInfo; ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str()); ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str()); ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str()); ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str()); ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str()); ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str()); ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str()); ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str()); ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str()); ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str()); ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str()); typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo); invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo), ocPlatformInfo); } void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger) { simLogger().setCustomTarget(logger); } bool SimulatorManager::setConsoleLogger() { return simLogger().setDefaultConsoleTarget(); } bool SimulatorManager::setFileLogger(const std::string &path) { return simLogger().setDefaultFileTarget(path); }<commit_msg>Resolved simulator crash issue.<commit_after>/****************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * 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 "simulator_manager.h" #include "simulator_resource_factory.h" #include "simulator_remote_resource_impl.h" #include "simulator_utils.h" SimulatorManager *SimulatorManager::getInstance() { static SimulatorManager s_instance; return &s_instance; } SimulatorManager::SimulatorManager() { OC::PlatformConfig conf { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces 0, // Uses randomly available port OC::QualityOfService::LowQos }; OC::OCPlatform::Configure(conf); } std::shared_ptr<SimulatorResource> SimulatorManager::createResource( const std::string &configPath) { VALIDATE_INPUT(configPath.empty(), "Empty path!") std::shared_ptr<SimulatorResource> resource; try { resource = SimulatorResourceFactory::getInstance()->createResource(configPath); if (!resource) throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } catch (RAML::RamlException &e) { throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } return resource; } std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource( const std::string &configPath, unsigned int count) { VALIDATE_INPUT(configPath.empty(), "Empty path!") VALIDATE_INPUT(!count, "Count is zero!") std::vector<std::shared_ptr<SimulatorResource>> resources; try { resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count); if (!resources.size()) throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } catch (RAML::RamlException &e) { throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); } return resources; } std::shared_ptr<SimulatorSingleResource> SimulatorManager::createSingleResource( const std::string &name, const std::string &uri, const std::string &resourceType) { VALIDATE_INPUT(name.empty(), "Empty resource name!") VALIDATE_INPUT(uri.empty(), "Empty URI!") VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType); } std::shared_ptr<SimulatorCollectionResource> SimulatorManager::createCollectionResource( const std::string &name, const std::string &uri, const std::string &resourceType) { VALIDATE_INPUT(name.empty(), "Empty resource name!") VALIDATE_INPUT(uri.empty(), "Empty URI!") VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType); } void SimulatorManager::findResource(ResourceFindCallback callback) { VALIDATE_CALLBACK(callback) OC::FindCallback findCallback = std::bind( [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback) { if (!ocResource) return; callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource)); }, std::placeholders::_1, callback); typedef OCStackResult (*FindResource)(const std::string &, const std::string &, OCConnectivityType, OC::FindCallback); invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback); } void SimulatorManager::findResource(const std::string &resourceType, ResourceFindCallback callback) { VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") VALIDATE_CALLBACK(callback) OC::FindCallback findCallback = std::bind( [](std::shared_ptr<OC::OCResource> ocResource, ResourceFindCallback callback) { if (!ocResource) return; callback(std::make_shared<SimulatorRemoteResourceImpl>(ocResource)); }, std::placeholders::_1, callback); std::ostringstream query; query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType; typedef OCStackResult (*FindResource)(const std::string &, const std::string &, OCConnectivityType, OC::FindCallback); invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(), CT_DEFAULT, findCallback); } void SimulatorManager::getDeviceInfo(const std::string &host, DeviceInfoCallback callback) { VALIDATE_CALLBACK(callback) OC::FindDeviceCallback deviceCallback = std::bind( [](const OC::OCRepresentation & rep, const std::string & hostUri, DeviceInfoCallback callback) { std::string deviceName = rep.getValue<std::string>("n"); std::string deviceID = rep.getValue<std::string>("di"); std::string deviceSpecVersion = rep.getValue<std::string>("lcv"); std::string deviceDMV = rep.getValue<std::string>("dmv"); DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV); callback(hostUri, deviceInfo); }, std::placeholders::_1, host, callback); typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &, OCConnectivityType, OC::FindDeviceCallback); invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), host.c_str(), "/oic/d", CT_DEFAULT, deviceCallback); } void SimulatorManager::setDeviceInfo(const std::string &deviceName) { VALIDATE_INPUT(deviceName.empty(), "Empty resource type!") typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo); OCDeviceInfo ocDeviceInfo {nullptr, nullptr}; ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str()); invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo), ocDeviceInfo); } void SimulatorManager::getPlatformInfo(const std::string &host, PlatformInfoCallback callback) { VALIDATE_CALLBACK(callback) OC::FindPlatformCallback platformCallback = std::bind( [](const OC::OCRepresentation & rep, const std::string & hostUri, PlatformInfoCallback callback) { PlatformInfo platformInfo; platformInfo.setPlatformID(rep.getValue<std::string>("pi")); platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv")); platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn")); platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml")); platformInfo.setModelNumber(rep.getValue<std::string>("mnmo")); platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt")); platformInfo.setOSVersion(rep.getValue<std::string>("mnos")); platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw")); platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv")); platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl")); platformInfo.setSystemTime(rep.getValue<std::string>("st")); callback(hostUri, platformInfo); }, std::placeholders::_1, host, callback); typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &, OCConnectivityType, OC::FindPlatformCallback); invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), host.c_str(), "/oic/p", CT_DEFAULT, platformCallback); } void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo) { OCPlatformInfo ocPlatformInfo; ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str()); ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str()); ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str()); ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str()); ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str()); ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str()); ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str()); ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str()); ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str()); ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str()); ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str()); typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo); invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo), ocPlatformInfo); } void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger) { simLogger().setCustomTarget(logger); } bool SimulatorManager::setConsoleLogger() { return simLogger().setDefaultConsoleTarget(); } bool SimulatorManager::setFileLogger(const std::string &path) { return simLogger().setDefaultFileTarget(path); }<|endoftext|>
<commit_before>#pragma once #include <vector> #include <utility> #include <iosfwd> #include <gmpxx.h> // sam: this stuff should really be a class -- otherwise you have to understand // your implementation to use these functions without doing something you // do not want. // notably, you open a file and close it in different functions // maybe in the class version open in the constructor and close in the // destructor? (not totally sure that is good advice) // I've also left some comments in the cc // I also moved you to using std::blah, and removed all std:: from the file // // TODO: // - [ ] put in class (or atleast a namespace, these shouldn't be global) // - [ ] fix exceptions // - [ ] dedicate to either writing std or using std::blah, a mix is hard to // read std::vector<std::pair<mpz_class, mpz_class>> findPrimeFactors(mpz_class n); void generateNPrimes(long int n); std::ifstream& skipToLine(std::ifstream& file, mpz_class num); mpz_class getNthPrime(mpz_class n); mpz_class getNextPrime( std::ifstream& prime_file, mpz_class n); // this function is faster since you can hold onto your place <commit_msg>clang formatted<commit_after>#pragma once #include <vector> #include <utility> #include <iosfwd> #include <gmpxx.h> // sam: this stuff should really be a class -- otherwise you have to understand // your implementation to use these functions without doing something you // do not want. // notably, you open a file and close it in different functions // maybe in the class version open in the constructor and close in the // destructor? (not totally sure that is good advice) // I've also left some comments in the cc // I also moved you to using std::blah, and removed all std:: from the file // // TODO: // - [ ] put in class (or atleast a namespace, these shouldn't be global) // - [ ] fix exceptions // - [ ] dedicate to either writing std or using std::blah, a mix is hard // to // read std::vector<std::pair<mpz_class, mpz_class>> findPrimeFactors(mpz_class n); void generateNPrimes(long int n); std::ifstream& skipToLine(std::ifstream& file, mpz_class num); mpz_class getNthPrime(mpz_class n); mpz_class getNextPrime( std::ifstream& prime_file, mpz_class n); // this function is faster since you can hold onto your place <|endoftext|>
<commit_before>#include<bits/stdc++.h> #define MAXN 5001 #define MAXH 5001 #define INF 0x3f3f3f3f using namespace std; int N,H,R; int rules[MAXN]; int DP[MAXN][MAXH]; int rec(int num_heads, int cur_health) { if(num_heads == 0) { return 0; } else if (DP[num_heads][cur_health] != INF){ return DP[num_heads][cur_health]; } else { // try defending int num_head_if_defend = rules[num_heads]; int cur_health_if_defend = cur_health-1; // avoid case where we constantly defend only to lose health, this is a lost battle anyway if(cur_health_if_defend > 0 && rules[num_heads] != num_heads) { DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_defend, cur_health_if_defend)); } // try attacking int num_head_if_attack = rules[num_heads-1]; int cur_health_if_attack = cur_health-num_heads; if(cur_health_if_attack > 0) { DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_attack, cur_health_if_attack)); } if(DP[num_heads][cur_health] == INF)// i.e.e impossible DP[num_heads][cur_health] = INF+1; return DP[num_heads][cur_health]; } } int main() { cin >> N >> H >> R; memset(DP, INF, sizeof(DP)); for(int i = 0;i < MAXN;i++) { rules[i] = i; } for(int i = 0;i < R;i++) { int n_i, n_j; cin >> n_i >> n_j; rules[n_i] = n_j; } int ans = rec(N, H); if(ans >= INF) cout << "retreat" << endl; else cout << ans << endl; return 0; } <commit_msg>made solution more clear<commit_after>#include<bits/stdc++.h> #define MAXN 5001 #define MAXH 5001 #define INF 0x3f3f3f3f #define IMPOSSIBLE INF+1 using namespace std; int N,H,R; int rules[MAXN]; int DP[MAXN][MAXH]; int rec(int num_heads, int cur_health) { if(num_heads == 0) { return 0; } else if (DP[num_heads][cur_health] != INF){ return DP[num_heads][cur_health]; } else { // try defending int num_head_if_defend = rules[num_heads]; int cur_health_if_defend = cur_health-1; if(cur_health_if_defend > 0) { DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_defend, cur_health_if_defend)); } // try attacking int num_head_if_attack = rules[num_heads-1]; int cur_health_if_attack = cur_health-num_heads; if(cur_health_if_attack > 0) { DP[num_heads][cur_health] = min(DP[num_heads][cur_health], 1+rec(num_head_if_attack, cur_health_if_attack)); } if(DP[num_heads][cur_health] == INF){ // we have attempted computing this state and it's impossible DP[num_heads][cur_health] = IMPOSSIBLE; } return DP[num_heads][cur_health]; } } int main() { cin >> N >> H >> R; memset(DP, INF, sizeof(DP)); for(int i = 0;i < MAXN;i++) { rules[i] = i; } for(int i = 0;i < R;i++) { int n_i, n_j; cin >> n_i >> n_j; rules[n_i] = n_j; } int ans = rec(N, H); if(ans == INF || ans == IMPOSSIBLE) cout << "retreat" << endl; else cout << ans << endl; return 0; } <|endoftext|>
<commit_before><commit_msg>洛谷 T52793<commit_after><|endoftext|>
<commit_before>// Python includes #include <Python.h> // Stl includes #include <fstream> // Qt includes #include <QResource> #include <QMetaType> #include <QFile> #include <QDir> // hyperion util includes #include <utils/jsonschema/JsonSchemaChecker.h> #include <utils/FileUtils.h> // effect engine includes #include <effectengine/EffectEngine.h> #include "Effect.h" #include "HyperionConfig.h" EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig) : _hyperion(hyperion) , _availableEffects() , _activeEffects() , _mainThreadState(nullptr) , _log(Logger::getInstance("EFFECTENGINE")) { qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>"); // connect the Hyperion channel clear feedback connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int))); connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared())); // read all effects const Json::Value & paths = jsonEffectConfig["paths"]; for (Json::UInt i = 0; i < paths.size(); ++i) { const std::string & path = paths[i].asString(); QDir directory(QString::fromStdString(path)); if (directory.exists()) { int efxCount = 0; QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase); foreach (const QString & filename, filenames) { EffectDefinition def; if (loadEffectDefinition(path, filename.toStdString(), def)) { _availableEffects.push_back(def); efxCount++; } } Info(_log, "%d effects loaded from directory %s", efxCount, path.c_str()); } } if (_availableEffects.size() == 0) { Error(_log, "no effects found, check your effect directories"); } // initialize the python interpreter Debug(_log,"Initializing Python interpreter"); Effect::registerHyperionExtensionModule(); Py_InitializeEx(0); PyEval_InitThreads(); // Create the GIL _mainThreadState = PyEval_SaveThread(); } EffectEngine::~EffectEngine() { // clean up the Python interpreter Debug(_log, "Cleaning up Python interpreter"); PyEval_RestoreThread(_mainThreadState); Py_Finalize(); } const std::list<EffectDefinition> &EffectEngine::getEffects() const { return _availableEffects; } const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects() { _availableActiveEffects.clear(); for (Effect * effect : _activeEffects) { ActiveEffectDefinition activeEffectDefinition; activeEffectDefinition.script = effect->getScript(); activeEffectDefinition.priority = effect->getPriority(); activeEffectDefinition.timeout = effect->getTimeout(); activeEffectDefinition.args = effect->getArgs(); _availableActiveEffects.push_back(activeEffectDefinition); } return _availableActiveEffects; } bool EffectEngine::loadEffectDefinition(const std::string &path, const std::string &effectConfigFile, EffectDefinition & effectDefinition) { std::string fileName = path + QDir::separator().toLatin1() + effectConfigFile; std::ifstream file(fileName.c_str()); Logger * log = Logger::getInstance("EFFECTENGINE"); if (!file.is_open()) { Error( log, "Effect file '%s' could not be loaded", fileName.c_str()); return false; } // Read the json config file Json::Reader jsonReader; Json::Value config; if (!jsonReader.parse(file, config, false)) { Error( log, "Error while reading effect '%s': %s", fileName.c_str(), jsonReader.getFormattedErrorMessages().c_str()); return false; } // Read the json schema file QResource schemaData(":effect-schema"); JsonSchemaChecker schemaChecker; Json::Value schema; Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false); schemaChecker.setSchema(schema); if (!schemaChecker.validate(config)) { const std::list<std::string> & errors = schemaChecker.getMessages(); foreach (const std::string & error, errors) { Error( log, "Error while checking '%s':%s", fileName.c_str(), error.c_str()); } return false; } // setup the definition effectDefinition.name = config["name"].asString(); effectDefinition.script = path + QDir::separator().toLatin1() + config["script"].asString(); effectDefinition.args = config["args"]; return true; } int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout) { return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout); } int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout) { Info( _log, "run effect %s on channel %d", effectName.c_str(), priority); const EffectDefinition * effectDefinition = nullptr; for (const EffectDefinition & e : _availableEffects) { if (e.name == effectName) { effectDefinition = &e; break; } } if (effectDefinition == nullptr) { // no such effect Error(_log, "effect %s not found", effectName.c_str()); return -1; } return runEffectScript(effectDefinition->script, args.isNull() ? effectDefinition->args : args, priority, timeout); } int EffectEngine::runEffectScript(const std::string &script, const Json::Value &args, int priority, int timeout) { // clear current effect on the channel channelCleared(priority); // create the effect Effect * effect = new Effect(_mainThreadState, priority, timeout, script, args); connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection); connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*))); _activeEffects.push_back(effect); // start the effect _hyperion->registerPriority("EFFECT: "+FileUtils::getBaseName(script), priority); effect->start(); return 0; } void EffectEngine::channelCleared(int priority) { for (Effect * effect : _activeEffects) { if (effect->getPriority() == priority) { effect->abort(); } } } void EffectEngine::allChannelsCleared() { for (Effect * effect : _activeEffects) { effect->abort(); } } void EffectEngine::effectFinished(Effect *effect) { if (!effect->isAbortRequested()) { // effect stopped by itself. Clear the channel _hyperion->clear(effect->getPriority()); } Info( _log, "effect finished"); for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt) { if (*effectIt == effect) { _activeEffects.erase(effectIt); break; } } // cleanup the effect effect->deleteLater(); _hyperion->unRegisterPriority("EFFECT: " + effect->getScript()); } <commit_msg>fix effect prio unregister<commit_after>// Python includes #include <Python.h> // Stl includes #include <fstream> // Qt includes #include <QResource> #include <QMetaType> #include <QFile> #include <QDir> // hyperion util includes #include <utils/jsonschema/JsonSchemaChecker.h> #include <utils/FileUtils.h> // effect engine includes #include <effectengine/EffectEngine.h> #include "Effect.h" #include "HyperionConfig.h" EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig) : _hyperion(hyperion) , _availableEffects() , _activeEffects() , _mainThreadState(nullptr) , _log(Logger::getInstance("EFFECTENGINE")) { qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>"); // connect the Hyperion channel clear feedback connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int))); connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared())); // read all effects const Json::Value & paths = jsonEffectConfig["paths"]; for (Json::UInt i = 0; i < paths.size(); ++i) { const std::string & path = paths[i].asString(); QDir directory(QString::fromStdString(path)); if (directory.exists()) { int efxCount = 0; QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase); foreach (const QString & filename, filenames) { EffectDefinition def; if (loadEffectDefinition(path, filename.toStdString(), def)) { _availableEffects.push_back(def); efxCount++; } } Info(_log, "%d effects loaded from directory %s", efxCount, path.c_str()); } } if (_availableEffects.size() == 0) { Error(_log, "no effects found, check your effect directories"); } // initialize the python interpreter Debug(_log,"Initializing Python interpreter"); Effect::registerHyperionExtensionModule(); Py_InitializeEx(0); PyEval_InitThreads(); // Create the GIL _mainThreadState = PyEval_SaveThread(); } EffectEngine::~EffectEngine() { // clean up the Python interpreter Debug(_log, "Cleaning up Python interpreter"); PyEval_RestoreThread(_mainThreadState); Py_Finalize(); } const std::list<EffectDefinition> &EffectEngine::getEffects() const { return _availableEffects; } const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects() { _availableActiveEffects.clear(); for (Effect * effect : _activeEffects) { ActiveEffectDefinition activeEffectDefinition; activeEffectDefinition.script = effect->getScript(); activeEffectDefinition.priority = effect->getPriority(); activeEffectDefinition.timeout = effect->getTimeout(); activeEffectDefinition.args = effect->getArgs(); _availableActiveEffects.push_back(activeEffectDefinition); } return _availableActiveEffects; } bool EffectEngine::loadEffectDefinition(const std::string &path, const std::string &effectConfigFile, EffectDefinition & effectDefinition) { std::string fileName = path + QDir::separator().toLatin1() + effectConfigFile; std::ifstream file(fileName.c_str()); Logger * log = Logger::getInstance("EFFECTENGINE"); if (!file.is_open()) { Error( log, "Effect file '%s' could not be loaded", fileName.c_str()); return false; } // Read the json config file Json::Reader jsonReader; Json::Value config; if (!jsonReader.parse(file, config, false)) { Error( log, "Error while reading effect '%s': %s", fileName.c_str(), jsonReader.getFormattedErrorMessages().c_str()); return false; } // Read the json schema file QResource schemaData(":effect-schema"); JsonSchemaChecker schemaChecker; Json::Value schema; Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false); schemaChecker.setSchema(schema); if (!schemaChecker.validate(config)) { const std::list<std::string> & errors = schemaChecker.getMessages(); foreach (const std::string & error, errors) { Error( log, "Error while checking '%s':%s", fileName.c_str(), error.c_str()); } return false; } // setup the definition effectDefinition.name = config["name"].asString(); effectDefinition.script = path + QDir::separator().toLatin1() + config["script"].asString(); effectDefinition.args = config["args"]; return true; } int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout) { return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout); } int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout) { Info( _log, "run effect %s on channel %d", effectName.c_str(), priority); const EffectDefinition * effectDefinition = nullptr; for (const EffectDefinition & e : _availableEffects) { if (e.name == effectName) { effectDefinition = &e; break; } } if (effectDefinition == nullptr) { // no such effect Error(_log, "effect %s not found", effectName.c_str()); return -1; } return runEffectScript(effectDefinition->script, args.isNull() ? effectDefinition->args : args, priority, timeout); } int EffectEngine::runEffectScript(const std::string &script, const Json::Value &args, int priority, int timeout) { // clear current effect on the channel channelCleared(priority); // create the effect Effect * effect = new Effect(_mainThreadState, priority, timeout, script, args); connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection); connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*))); _activeEffects.push_back(effect); // start the effect _hyperion->registerPriority("EFFECT: "+FileUtils::getBaseName(script), priority); effect->start(); return 0; } void EffectEngine::channelCleared(int priority) { for (Effect * effect : _activeEffects) { if (effect->getPriority() == priority) { effect->abort(); } } } void EffectEngine::allChannelsCleared() { for (Effect * effect : _activeEffects) { effect->abort(); } } void EffectEngine::effectFinished(Effect *effect) { if (!effect->isAbortRequested()) { // effect stopped by itself. Clear the channel _hyperion->clear(effect->getPriority()); } Info( _log, "effect finished"); for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt) { if (*effectIt == effect) { _activeEffects.erase(effectIt); break; } } // cleanup the effect effect->deleteLater(); _hyperion->unRegisterPriority("EFFECT: " + FileUtils::getBaseName(effect->getScript())); } <|endoftext|>
<commit_before>// Quick benchmark comparison of inlined 4-element sorting network // vs std::sort. // compile with: g++ --std=c++11 -O3 sort_compare.cc -o sort_compare // Copyright (C) 2016 David G. Andersen. // Apache licensed, see LICENSE file. #include <sys/types.h> #include <sys/time.h> #include <inttypes.h> #include <stdio.h> #include <algorithm> #include <iterator> constexpr int WARMUP_ITERS = 1000; constexpr int EVAL_ITERS = 200000000; constexpr int NUM_TAGS = 4; // Benchmark function 1 - the inlined version. Note that both // benchmark functions return the value of the last tag; we use // this to discourage the compiler from optimizing away all of this // useless work. inline void SortPair(uint32_t& a, uint32_t& b) { if ((a & 0x0f) > (b & 0x0f)) { std::swap(a, b); } } inline int32_t SortTags(uint32_t tags[4]) { SortPair(tags[0], tags[2]); SortPair(tags[1], tags[3]); SortPair(tags[0], tags[1]); SortPair(tags[2], tags[3]); SortPair(tags[1], tags[2]); return tags[3]; } // STL version. inline int32_t STLSortTags(uint32_t (&tags)[4]) { std::sort(std::begin(tags), std::end(tags), [](uint32_t a, uint32_t b) { return (a & 0xf) < (b & 0xf); }); return tags[3]; } // Quick hack LCRNG to seed tags. We seed the tags randomly each // time so that the benchmark isn't getting excess benefit from // the branch predictor, which might change the results. This // isn't designed to be strong, it's designed to be fast and // just good enough that the compiler doesn't invalidate our results. uint64_t state = 1234567u; inline void randomizeTags(uint32_t tags[NUM_TAGS]) { uint64_t old = state; tags[0] = state >> 4; tags[1] = state >> 16; tags[2] = state >> 24; tags[3] = state >> 32; state = state * 6364136223846793005ULL + 7; } void print_timing(const struct timeval *tv_start, const struct timeval *tv_end, const char *name, int32_t sum) { int64_t usec = (tv_end->tv_sec - tv_start->tv_sec) * 1000000 + (tv_end->tv_usec - tv_start->tv_usec); float sec = (float)usec/1000000.0; printf("%s : %.2f seconds\n", name, sec); if (sum == 0) { printf("Hey, neat coincidence, sum is zero\n"); } } #define BENCHMARK(f, name) do { \ struct timeval tv_start, tv_end; \ int32_t sum = 0; \ for (int i = 0; i < WARMUP_ITERS; i++) { \ randomizeTags(tags); \ f; \ } \ gettimeofday(&tv_start, NULL); \ for (int i = 0; i < EVAL_ITERS; i++) { \ randomizeTags(tags); \ sum += f; \ } \ gettimeofday(&tv_end, NULL); \ print_timing(&tv_start, &tv_end, name, sum); \ } while(0) int main() { uint32_t tags[4]; BENCHMARK(SortTags(tags), "fully inlined"); BENCHMARK(STLSortTags(tags), "STL sort"); } <commit_msg>Bit more cleanup<commit_after>// Quick benchmark comparison of inlined 4-element sorting network // vs std::sort. // compile with: g++ --std=c++11 -O3 sort_compare.cc -o sort_compare // Copyright (C) 2016 David G. Andersen. // Apache licensed, see LICENSE file. #include <sys/types.h> #include <sys/time.h> #include <inttypes.h> #include <stdio.h> #include <algorithm> #include <iterator> constexpr int WARMUP_ITERS = 2000; constexpr int EVAL_ITERS = 200000000; constexpr int NUM_TAGS = 4; // Benchmark function 1 - the inlined version. Note that both // benchmark functions return the value of the last tag; we use // this to discourage the compiler from optimizing away all of this // useless work. inline void SortPair(uint32_t& a, uint32_t& b) { if ((a & 0x0f) > (b & 0x0f)) { std::swap(a, b); } } inline int32_t SortTags(uint32_t tags[4]) { SortPair(tags[0], tags[2]); SortPair(tags[1], tags[3]); SortPair(tags[0], tags[1]); SortPair(tags[2], tags[3]); SortPair(tags[1], tags[2]); return tags[3]; } // STL version. inline int32_t STLSortTags(uint32_t (&tags)[4]) { std::sort(std::begin(tags), std::end(tags), [](uint32_t a, uint32_t b) { return (a & 0xf) < (b & 0xf); }); return tags[3]; } // Quick hack LCRNG to seed tags. We seed the tags randomly each // time so that the benchmark isn't getting excess benefit from // the branch predictor, which might change the results. This // isn't designed to be strong, it's designed to be fast and // just good enough that the compiler doesn't invalidate our results. uint64_t state = 1234567u; inline void randomizeTags(uint32_t tags[NUM_TAGS]) { tags[0] = state >> 4; tags[1] = state >> 16; tags[2] = state >> 24; tags[3] = state >> 32; state = state * 6364136223846793005ULL + 7; } void print_timing(const struct timeval *tv_start, const struct timeval *tv_end, const char *name, int32_t sum) { int64_t usec = (tv_end->tv_sec - tv_start->tv_sec) * 1000000 + (tv_end->tv_usec - tv_start->tv_usec); float sec = (float)usec/1000000.0; printf("%s : %.2f seconds\n", name, sec); if (sum == 0) { printf("Hey, neat coincidence, sum is zero\n"); } } #define BENCHMARK(f, name) do { \ struct timeval tv_start, tv_end; \ int32_t sum = 0; \ for (int i = 0; i < WARMUP_ITERS; i++) { \ randomizeTags(tags); \ f; \ } \ gettimeofday(&tv_start, NULL); \ for (int i = 0; i < EVAL_ITERS; i++) { \ randomizeTags(tags); \ sum += f; \ } \ gettimeofday(&tv_end, NULL); \ print_timing(&tv_start, &tv_end, name, sum); \ } while(0) int main() { uint32_t tags[4]; BENCHMARK(SortTags(tags), "fully inlined"); BENCHMARK(STLSortTags(tags), "STL sort"); } <|endoftext|>
<commit_before>#include <3ds.h> #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include "file.h" #include "display.h" #include "file_io.h" #define BUFFER_SIZE 60 #define MAX_BOTTOM_SIZE 28 #define VERSION "Notepad3DS Version 1.0" PrintConsole topScreen, bottomScreen; int scroll = 0; bool fast_scroll = false; void move_down(File file); void move_up(File file); unsigned int curr_line = 0; int main(int argc, char **argv) { gfxInitDefault(); consoleInit(GFX_TOP, &topScreen); consoleInit(GFX_BOTTOM, &bottomScreen); consoleSelect(&bottomScreen); //Software keyboard thanks to fincs print_instructions(); print_version(VERSION); File file; //Use as default file update_screen(file, curr_line); while (aptMainLoop()) { hidScanInput(); u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); if (kDown & KEY_START) break; static SwkbdState swkbd; static char mybuf[BUFFER_SIZE]; SwkbdButton button = SWKBD_BUTTON_NONE; bool didit = false; swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1); swkbdSetValidation(&swkbd, SWKBD_ANYTHING, SWKBD_FILTER_DIGITS | SWKBD_FILTER_AT | SWKBD_FILTER_PERCENT /*| SWKBD_FILTER_BACKSLASH*/ | SWKBD_FILTER_PROFANITY, 2); swkbdSetFeatures(&swkbd, SWKBD_MULTILINE); if (kDown & KEY_A) { //Select current line for editing swkbdSetHintText(&swkbd, "Input text here."); //Iterator to find current selected line auto line = file.lines.begin(); if (curr_line < file.lines.size()) { if (curr_line != 0) advance(line, curr_line); if (curr_line == file.lines.size() - 1) { file.lines.push_back(std::vector<char>{'\n'}); } //Need a char array to output to keyboard char current_text[BUFFER_SIZE] = ""; copy(line->begin(), line->end(), current_text); swkbdSetInitialText(&swkbd, current_text); } didit = true; button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); } if (kDown & KEY_B) { //Create new file //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Confirm creating a new file swkbdSetHintText(&swkbd, "Are you sure you want to open a BLANK file? y/n"); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); if (mybuf[0] == 'y') { File blankFile; file = blankFile; curr_line = 0; scroll = 0; update_screen(file, curr_line); print_save_status("New file created"); } else print_save_status("No new file created"); } if (kDown & KEY_R) { //find a thing //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get term to search for swkbdSetHintText(&swkbd, "Input search term here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); int line = file.find(mybuf); if (line < 0) printf("Could not find %s", mybuf); else { printf("Found %s at %d", mybuf, line); curr_line = line; if (curr_line > MAX_BOTTOM_SIZE) { scroll = curr_line - MAX_BOTTOM_SIZE; } update_screen(file, curr_line); } } if (kHeld & KEY_L) { //If held, allows for jumping to end and start of file fast_scroll = true; } else { fast_scroll = false; } if (kDown & KEY_X) { //Save current file //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get file name swkbdSetHintText(&swkbd, "Input filename here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); std::string filename = ""; for (int i = 0; mybuf[i] != '\0'; i++) filename.push_back(mybuf[i]); //Write out characters to file bool success = write_to_file(filename, file); if (success) { print_save_status("File written to " + filename); print_directory_status(filename); } else { print_save_status("Failed to write " + filename); } } if (kDown & KEY_Y) { //Similar code to pressing X, see about refactoring //Open a file curr_line = 0; scroll = 0; //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get file name swkbdSetHintText(&swkbd, "Input filename here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); std::string filename = ""; for (int i = 0; mybuf[i] != '\0'; i++) filename.push_back(mybuf[i]); File oldfile = file; file = open_file(filename); //print functions here seem to crash the program if (file.read_success) { update_screen(file, curr_line); clear_save_status(); std::cout << "Successfully opened " << filename << std::endl; clear_directory_status(); std::cout << "Current file: " << filename; //print_directory_status(filename); consoleSelect(&topScreen); //print_save_status("Successfully opened " + filename); } else { file = oldfile; update_screen(file, curr_line); clear_save_status(); std::cout << "Failed to open " << filename << std::endl; consoleSelect(&topScreen); //print_save_status("Failed to open " + filename); } } if (kDown & KEY_DDOWN) { //Move a line down (towards bottom of screen) move_down(file); } if (kHeld & KEY_CPAD_DOWN) { //Move a line down (towards bottom of screen) //as long as down is held move_down(file); } if (kDown & KEY_DUP) { //Move a line up (towards top of screen) move_up(file); } if (kHeld & KEY_CPAD_UP) { //Move a line up (towards top of screen) //as long as up is held move_up(file); } if (didit) { if (button != SWKBD_BUTTON_NONE) { std::vector<char> new_text = char_arr_to_vector(mybuf); if (curr_line >= file.lines.size()) { //Empty line, add a new one. file.add_line(new_text); } else { file.edit_line(new_text, curr_line); } update_screen(file, curr_line); } else printf("swkbd event: %d\n", swkbdGetResult(&swkbd)); } // Flush and swap framebuffers gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } gfxExit(); return 0; } void move_down(File file) { //Move a line down (towards bottom of screen) if (curr_line < file.lines.size() - 1) { if (fast_scroll) { curr_line = file.lines.size()-1; scroll = curr_line - MAX_BOTTOM_SIZE; } else { if ( (curr_line - scroll >= MAX_BOTTOM_SIZE) && (curr_line < file.lines.size() ) ) { scroll++; curr_line++; } else { curr_line++; } } } update_screen(file, curr_line); } void move_up(File file) { //Move a line up (towards top of screen) if (curr_line != 0) { if (fast_scroll) { //Jump to the top curr_line = 0; scroll = 0; } else { curr_line--; if (curr_line - scroll <= 0 && scroll != 0) { scroll--; } } update_screen(file, curr_line); } } <commit_msg>Removed keyboard filtering<commit_after>#include <3ds.h> #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include "file.h" #include "display.h" #include "file_io.h" #define BUFFER_SIZE 60 #define MAX_BOTTOM_SIZE 28 #define VERSION "Notepad3DS Version 1.0" PrintConsole topScreen, bottomScreen; int scroll = 0; bool fast_scroll = false; void move_down(File file); void move_up(File file); unsigned int curr_line = 0; int main(int argc, char **argv) { gfxInitDefault(); consoleInit(GFX_TOP, &topScreen); consoleInit(GFX_BOTTOM, &bottomScreen); consoleSelect(&bottomScreen); //Software keyboard thanks to fincs print_instructions(); print_version(VERSION); File file; //Use as default file update_screen(file, curr_line); while (aptMainLoop()) { hidScanInput(); u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); if (kDown & KEY_START) break; static SwkbdState swkbd; static char mybuf[BUFFER_SIZE]; SwkbdButton button = SWKBD_BUTTON_NONE; bool didit = false; swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1); swkbdSetValidation(&swkbd, SWKBD_ANYTHING, SWKBD_ANYTHING, 2); swkbdSetFeatures(&swkbd, SWKBD_DARKEN_TOP_SCREEN); if (kDown & KEY_A) { //Select current line for editing swkbdSetHintText(&swkbd, "Input text here."); //Iterator to find current selected line auto line = file.lines.begin(); if (curr_line < file.lines.size()) { if (curr_line != 0) advance(line, curr_line); if (curr_line == file.lines.size() - 1) { file.lines.push_back(std::vector<char>{'\n'}); } //Need a char array to output to keyboard char current_text[BUFFER_SIZE] = ""; copy(line->begin(), line->end(), current_text); swkbdSetInitialText(&swkbd, current_text); } didit = true; button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); } if (kDown & KEY_B) { //Create new file //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Confirm creating a new file swkbdSetHintText(&swkbd, "Are you sure you want to open a BLANK file? y/n"); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); if (mybuf[0] == 'y') { File blankFile; file = blankFile; curr_line = 0; scroll = 0; update_screen(file, curr_line); print_save_status("New file created"); } else print_save_status("No new file created"); } if (kDown & KEY_R) { //find a thing //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get term to search for swkbdSetHintText(&swkbd, "Input search term here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); int line = file.find(mybuf); if (line < 0) printf("Could not find %s", mybuf); else { printf("Found %s at %d", mybuf, line); curr_line = line; if (curr_line > MAX_BOTTOM_SIZE) { scroll = curr_line - MAX_BOTTOM_SIZE; } update_screen(file, curr_line); } } if (kHeld & KEY_L) { //If held, allows for jumping to end and start of file fast_scroll = true; } else { fast_scroll = false; } if (kDown & KEY_X) { //Save current file //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get file name swkbdSetHintText(&swkbd, "Input filename here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); std::string filename = ""; for (int i = 0; mybuf[i] != '\0'; i++) filename.push_back(mybuf[i]); //Write out characters to file bool success = write_to_file(filename, file); if (success) { print_save_status("File written to " + filename); print_directory_status(filename); } else { print_save_status("Failed to write " + filename); } } if (kDown & KEY_Y) { //Similar code to pressing X, see about refactoring //Open a file curr_line = 0; scroll = 0; //Clear buffer memset(mybuf, '\0', BUFFER_SIZE); //Get file name swkbdSetHintText(&swkbd, "Input filename here."); button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); std::string filename = ""; for (int i = 0; mybuf[i] != '\0'; i++) filename.push_back(mybuf[i]); File oldfile = file; file = open_file(filename); //print functions here seem to crash the program if (file.read_success) { update_screen(file, curr_line); clear_save_status(); std::cout << "Successfully opened " << filename << std::endl; clear_directory_status(); std::cout << "Current file: " << filename; //print_directory_status(filename); consoleSelect(&topScreen); //print_save_status("Successfully opened " + filename); } else { file = oldfile; update_screen(file, curr_line); clear_save_status(); std::cout << "Failed to open " << filename << std::endl; consoleSelect(&topScreen); //print_save_status("Failed to open " + filename); } } if (kDown & KEY_DDOWN) { //Move a line down (towards bottom of screen) move_down(file); } if (kHeld & KEY_CPAD_DOWN) { //Move a line down (towards bottom of screen) //as long as down is held move_down(file); } if (kDown & KEY_DUP) { //Move a line up (towards top of screen) move_up(file); } if (kHeld & KEY_CPAD_UP) { //Move a line up (towards top of screen) //as long as up is held move_up(file); } if (didit) { if (button != SWKBD_BUTTON_NONE) { std::vector<char> new_text = char_arr_to_vector(mybuf); if (curr_line >= file.lines.size()) { //Empty line, add a new one. file.add_line(new_text); } else { file.edit_line(new_text, curr_line); } update_screen(file, curr_line); } else printf("swkbd event: %d\n", swkbdGetResult(&swkbd)); } // Flush and swap framebuffers gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } gfxExit(); return 0; } void move_down(File file) { //Move a line down (towards bottom of screen) if (curr_line < file.lines.size() - 1) { if (fast_scroll) { curr_line = file.lines.size()-1; scroll = curr_line - MAX_BOTTOM_SIZE; } else { if ( (curr_line - scroll >= MAX_BOTTOM_SIZE) && (curr_line < file.lines.size() ) ) { scroll++; curr_line++; } else { curr_line++; } } } update_screen(file, curr_line); } void move_up(File file) { //Move a line up (towards top of screen) if (curr_line != 0) { if (fast_scroll) { //Jump to the top curr_line = 0; scroll = 0; } else { curr_line--; if (curr_line - scroll <= 0 && scroll != 0) { scroll--; } } update_screen(file, curr_line); } } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <memory> #include <string> #include <stdexcept> #include <vector> #ifdef DURATION #include <chrono> #endif #include "version.h" #include "Histogram.h" #include "thresholding/OtsuMethod.h" #include "thresholding/BalancedHistogramMethod.h" #include "thresholding/IterativeMethod.h" #include "thresholding/AdaptiveGaussMethod.h" #include "thresholding/AdaptiveMeanCMethod.h" using namespace std; using namespace thresholding; struct arguments { string inputPath; string outputPath; int method; int value; bool halfThresholding; arguments() : value(-1), halfThresholding(false) {} void print() { cout << "inputPath: " << inputPath << endl << "outputPath: " << outputPath << endl << "method: " << method << endl << "value: " << value << endl; } string getOutput(const string &methodName = "") { return outputPath + methodName + ".png"; } }; enum argsPosition { name = 0, method, inputImage, outputImage, }; enum thresholdingOption { otsu = 0, adaptiveGauss, adaptiveMeanC, balanced, iterative, manual, all, //must be last }; enum errorCode { noError = 0, invalidArguments, }; map<string, int> thresholdingArgs({{"--otsu", thresholdingOption::otsu}, {"--balanced", thresholdingOption::balanced}, {"--adaptiveGauss", thresholdingOption::adaptiveGauss}, {"--adaptiveMeanC", thresholdingOption::adaptiveMeanC}, {"--iterative", thresholdingOption::iterative}, {"--manual=", thresholdingOption::manual}, {"--all", thresholdingOption::all}}); void printHelp() { cout << "Help for cleanCppApplication " << endl; cout << "Version: " << Version::getVersionLong() << endl; cout << "Author: " << endl; cout << "URL: " << endl; /// @todo Do stuff in here also } int getMethod(char const* argv[]) { auto it = thresholdingArgs.find(argv[argsPosition::method]); if (it == thresholdingArgs.end()) throw invalid_argument("Invalid argument " + string(argv[argsPosition::method])); return it->second; } void parseArguments(int argc, char const** argv, arguments & output) { const int minArgs = 4; const int maxArgs = 5; if (argc < minArgs || argc > maxArgs) throw invalid_argument("Invalid count of arguments.\nExpected 4 arguments"); output.method = getMethod(argv); output.inputPath = argv[argsPosition::inputImage]; output.outputPath = argv[argsPosition::outputImage]; if (argc == maxArgs) if (string("--half") == argv[4]) output.halfThresholding = true; } void performThresholding(cv::Mat& inputImage, Histogram& histogram, arguments& args) { cv::Mat outputImage; cv::namedWindow( "Original", CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( "Original", inputImage ); // Show our image inside it. if(args.method == thresholdingOption::otsu || args.method == thresholdingOption::all) { thresholding::OtsuMethod otsu(inputImage, histogram); otsu.run(outputImage); cv::imwrite(args.outputPath + ".otsu.png", outputImage); cv::namedWindow( otsu.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( otsu.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::balanced || args.method == thresholdingOption::all) { thresholding::BalancedHistogramMethod bht(inputImage, histogram); bht.run(outputImage); cv::imwrite(args.outputPath + ".bht.png", outputImage); cv::namedWindow( bht.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( bht.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::iterative || args.method == thresholdingOption::all) { thresholding::IterativeMethod iterative(inputImage, histogram); iterative.run(outputImage); cv::imwrite(args.outputPath + ".iterative.png", outputImage); cv::namedWindow( iterative.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( iterative.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::manual) { if(args.value < 0) { throw std::invalid_argument("Bad manual threshold argument"); } throw std::runtime_error("Manual thresholding not supported yet"); } cv::waitKey(0); } void saveImageWithTransparentBg(const string& outputFile, const cv::Mat &in) { uint8_t white = 255; cv::Mat outputMat; cv::cvtColor(in, outputMat, CV_GRAY2BGRA); for (int64_t x = 0; x < in.rows; ++x) for (int64_t y = 0; y < in.cols; ++y) { cv::Vec4b & pixel = outputMat.at<cv::Vec4b>(x,y); if (pixel[0] == white && pixel[1] == white && pixel[2] == white) pixel[3] = 0; } imwrite(outputFile, outputMat); } int main(int argc, char const* argv[]) { int retCode = errorCode::noError; cv::Mat inputImage; cv::Mat outputImage; arguments args; unique_ptr<Algorithm> algorithm = nullptr; bool allSet = false; #ifdef DURATION chrono::time_point<chrono::system_clock> start, end; #endif // Print help if no arguments are given try { parseArguments(argc, argv, args); inputImage = cv::imread(args.inputPath, CV_LOAD_IMAGE_GRAYSCALE); Histogram histogram(inputImage); //performThresholding(inputImage, histogram, args); // TODO: nevsimla jsem si metody all, tak asi predelat if (args.method == all) { allSet = true; args.method = 0; } while (args.method < all) { if (allSet && args.method == manual) { args.method++; continue; } switch (args.method) { case thresholdingOption::otsu: algorithm = make_unique<OtsuMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::balanced: algorithm = make_unique<BalancedHistogramMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::iterative: algorithm = make_unique<IterativeMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::adaptiveMeanC: algorithm = make_unique<AdaptiveMeanCMethod>(inputImage, histogram); break; case thresholdingOption::adaptiveGauss: algorithm = make_unique<AdaptiveGaussMethod>(inputImage, histogram); break; default: runtime_error("Invalid method option"); break; } // Run the algorithm #ifdef DURATION start = chrono::system_clock::now(); #endif algorithm->run(outputImage); #ifdef DURATION end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; chrono::microseconds micro = chrono::duration_cast<chrono::microseconds>(elapsedSeconds); cout << micro.count() << endl; #endif if (allSet) { // Write image to the output file saveImageWithTransparentBg(args.getOutput(algorithm->getName()), outputImage); args.method++; } else { saveImageWithTransparentBg(args.getOutput(), outputImage); break; } } } catch (invalid_argument &e) { cerr << e.what() << endl; printHelp(); retCode = errorCode::invalidArguments; } catch (exception &e) { cerr << e.what() << endl; retCode = errorCode::invalidArguments; } return retCode; } <commit_msg>main: add help message<commit_after>#include <iostream> #include <map> #include <memory> #include <string> #include <stdexcept> #include <vector> #ifdef DURATION #include <chrono> #endif //#include "version.h" #include "Histogram.h" #include "thresholding/OtsuMethod.h" #include "thresholding/BalancedHistogramMethod.h" #include "thresholding/IterativeMethod.h" #include "thresholding/AdaptiveGaussMethod.h" #include "thresholding/AdaptiveMeanCMethod.h" using namespace std; using namespace thresholding; struct arguments { string inputPath; string outputPath; int method; int value; bool halfThresholding; arguments() : value(-1), halfThresholding(false) {} void print() { cout << "inputPath: " << inputPath << endl << "outputPath: " << outputPath << endl << "method: " << method << endl << "value: " << value << endl; } string getOutput(const string &methodName = "") { return outputPath + methodName + ".png"; } }; enum argsPosition { name = 0, method, inputImage, outputImage, }; enum thresholdingOption { otsu = 0, adaptiveGauss, adaptiveMeanC, balanced, iterative, manual, all, //must be last }; enum errorCode { noError = 0, invalidArguments, }; map<string, int> thresholdingArgs({{"--otsu", thresholdingOption::otsu}, {"--balanced", thresholdingOption::balanced}, {"--adaptiveGauss", thresholdingOption::adaptiveGauss}, {"--adaptiveMeanC", thresholdingOption::adaptiveMeanC}, {"--iterative", thresholdingOption::iterative}, {"--manual=", thresholdingOption::manual}, {"--all", thresholdingOption::all}}); void printHelp() { cout << "Help for zpo:" << endl << "Arguments: <method> <inputImage> <outputImage> [--half]" << endl << "Methods:" << endl; for (auto it : thresholdingArgs) cout << " " << it.first << endl; } int getMethod(char const* argv[]) { auto it = thresholdingArgs.find(argv[argsPosition::method]); if (it == thresholdingArgs.end()) throw invalid_argument("Invalid argument " + string(argv[argsPosition::method])); return it->second; } void parseArguments(int argc, char const** argv, arguments & output) { const int minArgs = 4; const int maxArgs = 5; if (argc < minArgs || argc > maxArgs) throw invalid_argument("Invalid count of arguments.\nExpected 4 arguments"); output.method = getMethod(argv); output.inputPath = argv[argsPosition::inputImage]; output.outputPath = argv[argsPosition::outputImage]; if (argc == maxArgs) if (string("--half") == argv[4]) output.halfThresholding = true; } void performThresholding(cv::Mat& inputImage, Histogram& histogram, arguments& args) { cv::Mat outputImage; cv::namedWindow( "Original", CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( "Original", inputImage ); // Show our image inside it. if(args.method == thresholdingOption::otsu || args.method == thresholdingOption::all) { thresholding::OtsuMethod otsu(inputImage, histogram); otsu.run(outputImage); cv::imwrite(args.outputPath + ".otsu.png", outputImage); cv::namedWindow( otsu.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( otsu.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::balanced || args.method == thresholdingOption::all) { thresholding::BalancedHistogramMethod bht(inputImage, histogram); bht.run(outputImage); cv::imwrite(args.outputPath + ".bht.png", outputImage); cv::namedWindow( bht.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( bht.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::iterative || args.method == thresholdingOption::all) { thresholding::IterativeMethod iterative(inputImage, histogram); iterative.run(outputImage); cv::imwrite(args.outputPath + ".iterative.png", outputImage); cv::namedWindow( iterative.getName(), CV_WINDOW_AUTOSIZE ); // Create a window for display. cv::imshow( iterative.getName(), outputImage ); // Show our image inside it. } if(args.method == thresholdingOption::manual) { if(args.value < 0) { throw std::invalid_argument("Bad manual threshold argument"); } throw std::runtime_error("Manual thresholding not supported yet"); } cv::waitKey(0); } void saveImageWithTransparentBg(const string& outputFile, const cv::Mat &in) { uint8_t white = 255; cv::Mat outputMat; cv::cvtColor(in, outputMat, CV_GRAY2BGRA); for (int64_t x = 0; x < in.rows; ++x) for (int64_t y = 0; y < in.cols; ++y) { cv::Vec4b & pixel = outputMat.at<cv::Vec4b>(x,y); if (pixel[0] == white && pixel[1] == white && pixel[2] == white) pixel[3] = 0; } imwrite(outputFile, outputMat); } int main(int argc, char const* argv[]) { int retCode = errorCode::noError; cv::Mat inputImage; cv::Mat outputImage; arguments args; unique_ptr<Algorithm> algorithm = nullptr; bool allSet = false; #ifdef DURATION chrono::time_point<chrono::system_clock> start, end; #endif // Print help if no arguments are given try { parseArguments(argc, argv, args); inputImage = cv::imread(args.inputPath, CV_LOAD_IMAGE_GRAYSCALE); Histogram histogram(inputImage); //performThresholding(inputImage, histogram, args); // TODO: nevsimla jsem si metody all, tak asi predelat if (args.method == all) { allSet = true; args.method = 0; } while (args.method < all) { if (allSet && args.method == manual) { args.method++; continue; } switch (args.method) { case thresholdingOption::otsu: algorithm = make_unique<OtsuMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::balanced: algorithm = make_unique<BalancedHistogramMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::iterative: algorithm = make_unique<IterativeMethod>(inputImage, histogram, args.halfThresholding); break; case thresholdingOption::adaptiveMeanC: algorithm = make_unique<AdaptiveMeanCMethod>(inputImage, histogram); break; case thresholdingOption::adaptiveGauss: algorithm = make_unique<AdaptiveGaussMethod>(inputImage, histogram); break; default: runtime_error("Invalid method option"); break; } // Run the algorithm #ifdef DURATION start = chrono::system_clock::now(); #endif algorithm->run(outputImage); #ifdef DURATION end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; chrono::microseconds micro = chrono::duration_cast<chrono::microseconds>(elapsedSeconds); cout << micro.count() << endl; #endif if (allSet) { // Write image to the output file saveImageWithTransparentBg(args.getOutput(algorithm->getName()), outputImage); args.method++; } else { saveImageWithTransparentBg(args.getOutput(), outputImage); break; } } } catch (invalid_argument &e) { cerr << e.what() << endl; printHelp(); retCode = errorCode::invalidArguments; } catch (exception &e) { cerr << e.what() << endl; retCode = errorCode::invalidArguments; } return retCode; } <|endoftext|>
<commit_before>#include <ctrcommon/common.hpp> #include <sstream> #include <iomanip> typedef enum { INSTALL, DELETE } Mode; int main(int argc, char **argv) { if(!platform_init()) { return 0; } std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL; bool netInstall = false; u64 freeSpace = fs_get_free_space(destination); auto onLoop = [&]() { bool breakLoop = false; if(input_is_pressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fs_get_free_space(destination); if(mode == DELETE) { breakLoop = true; } } if(input_is_pressed(BUTTON_R)) { if(mode == INSTALL) { mode = DELETE; } else { mode = INSTALL; } breakLoop = true; } if(input_is_pressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; stream << "Y - Receive an app over the network" << "\n"; std::string str = stream.str(); screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](int progress) { ui_display_progress("Installing", "Press B to cancel.", true, progress); input_poll(); return !input_is_pressed(BUTTON_B); }; while(platform_is_running()) { std::string targetInstall; App targetDelete; bool obtained = false; if(mode == INSTALL) { obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop); } else if(mode == DELETE) { obtained = ui_select_app(&targetDelete, destination, onLoop); } if(netInstall) { netInstall = false; // Clear bottom screen on both buffers. screen_begin_draw(BOTTOM_SCREEN); screen_clear(0, 0, 0); screen_end_draw(); screen_swap_buffers(); screen_begin_draw(BOTTOM_SCREEN); screen_clear(0, 0, 0); screen_end_draw(); screen_swap_buffers(); RemoteFile file = ui_accept_remote_file(); if(file.socket == -1) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(ui_prompt(confirmStream.str(), true)) { int ret = app_install(destination, file.socket, true, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == 0) { resultMsg << "succeeded!"; } else { resultMsg << "failed! Error: 0x" << std::hex << ret; } ui_prompt(resultMsg.str(), false); } socket_close(file.socket); continue; } if(obtained) { std::stringstream prompt; if(mode == INSTALL) { prompt << "Install "; } else if(mode == DELETE) { prompt << "Delete "; } prompt << "the selected title?"; if(ui_prompt(prompt.str(), true)) { int ret = 0; if(mode == INSTALL) { ret = app_install_file(destination, targetInstall, onProgress); } else if(mode == DELETE) { ui_display_message("Deleting title..."); ret = app_delete(targetDelete); } std::stringstream resultMsg; if(mode == INSTALL) { resultMsg << "Install "; } else if(mode == DELETE) { resultMsg << "Delete "; } if(ret == 0) { resultMsg << "succeeded!"; } else { resultMsg << "failed! Error: 0x" << std::hex << ret; } ui_prompt(resultMsg.str(), false); freeSpace = fs_get_free_space(destination); } } } platform_cleanup(); return 0; } <commit_msg>Properly report cancellation.<commit_after>#include <ctrcommon/common.hpp> #include <sstream> #include <iomanip> typedef enum { INSTALL, DELETE } Mode; int main(int argc, char **argv) { if(!platform_init()) { return 0; } std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL; bool netInstall = false; u64 freeSpace = fs_get_free_space(destination); auto onLoop = [&]() { bool breakLoop = false; if(input_is_pressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fs_get_free_space(destination); if(mode == DELETE) { breakLoop = true; } } if(input_is_pressed(BUTTON_R)) { if(mode == INSTALL) { mode = DELETE; } else { mode = INSTALL; } breakLoop = true; } if(input_is_pressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; stream << "Y - Receive an app over the network" << "\n"; std::string str = stream.str(); screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](int progress) { ui_display_progress("Installing", "Press B to cancel.", true, progress); input_poll(); return !input_is_pressed(BUTTON_B); }; while(platform_is_running()) { std::string targetInstall; App targetDelete; bool obtained = false; if(mode == INSTALL) { obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop); } else if(mode == DELETE) { obtained = ui_select_app(&targetDelete, destination, onLoop); } if(netInstall) { netInstall = false; // Clear bottom screen on both buffers. screen_begin_draw(BOTTOM_SCREEN); screen_clear(0, 0, 0); screen_end_draw(); screen_swap_buffers(); screen_begin_draw(BOTTOM_SCREEN); screen_clear(0, 0, 0); screen_end_draw(); screen_swap_buffers(); RemoteFile file = ui_accept_remote_file(); if(file.socket == -1) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(ui_prompt(confirmStream.str(), true)) { int ret = app_install(destination, file.socket, true, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == 0) { resultMsg << "succeeded!"; } else if(ret == -2) { resultMsg << "cancelled!"; } else { resultMsg << "failed! Error: 0x" << std::hex << ret; } ui_prompt(resultMsg.str(), false); } socket_close(file.socket); continue; } if(obtained) { std::stringstream prompt; if(mode == INSTALL) { prompt << "Install "; } else if(mode == DELETE) { prompt << "Delete "; } prompt << "the selected title?"; if(ui_prompt(prompt.str(), true)) { int ret = 0; if(mode == INSTALL) { ret = app_install_file(destination, targetInstall, onProgress); } else if(mode == DELETE) { ui_display_message("Deleting title..."); ret = app_delete(targetDelete); } std::stringstream resultMsg; if(mode == INSTALL) { resultMsg << "Install "; } else if(mode == DELETE) { resultMsg << "Delete "; } if(ret == 0) { resultMsg << "succeeded!"; } else if(ret == -2) { resultMsg << "cancelled!"; } else { resultMsg << "failed! Error: 0x" << std::hex << ret; } ui_prompt(resultMsg.str(), false); freeSpace = fs_get_free_space(destination); } } } platform_cleanup(); return 0; } <|endoftext|>
<commit_before>#include <3ds.h> #include <stdio.h> void shutdown3DS() { Handle ptmSysmHandle = 0; Result result = srvGetServiceHandle(&ptmSysmHandle, "ptm:sysm"); if (result != 0) return; u32 *commandBuffer = getThreadCommandBuffer(); commandBuffer[0] = 0x040700C0; //ptm:s::ShutdownAsync commandBuffer[1] = 0; commandBuffer[2] = 0; commandBuffer[3] = 0; svcSendSyncRequest(ptmSysmHandle); svcCloseHandle(ptmSysmHandle); } int main(int argc, char **argv) { hidScanInput(); // If any key is pressed, cancel the shutdown. if (hidKeysDown() != 0) goto done; shutdown3DS(); done: // Hack: the 3ds crashes ("An error has occcurred.") for some reason // without one iteration of the main loop. aptMainLoop(); return 0; } <commit_msg>Update main.cpp<commit_after>#include <3ds.h> #include <stdio.h> void shutdown3DS() { Handle ptmSysmHandle = 0; Result result = srvGetServiceHandle(&ptmSysmHandle, "ptm:sysm"); if (result != 0) return; u32 *commandBuffer = getThreadCommandBuffer(); commandBuffer[0] = 0x040700C0; //ptm:s::ShutdownAsync commandBuffer[1] = 0; commandBuffer[2] = 0; commandBuffer[3] = 0; svcSendSyncRequest(ptmSysmHandle); svcCloseHandle(ptmSysmHandle); } int main(int argc, char **argv) { hidScanInput(); // If any key is pressed, cancel the shutdown. if (hidKeysDown() != 0) goto done; shutdown3DS(); done: // Hack: the 3ds crashes ("An error has occcurred.") for some reason // without one iteration of the main loop. aptMainLoop(); return 0; } <|endoftext|>