hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
62672e14d458749c6e1b9a35909f974ff437ee79
4,899
cc
C++
src/runtime/registry.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
762
2020-01-16T02:44:50.000Z
2022-03-30T10:03:36.000Z
src/runtime/registry.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
161
2020-01-20T07:47:38.000Z
2022-03-11T15:19:10.000Z
src/runtime/registry.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
77
2020-01-23T17:47:20.000Z
2022-03-28T10:12:19.000Z
/*! * Copyright (c) 2019 by Contributors if not otherwise specified * \file registry.cc * \brief The global registry of packed function. */ #include <dmlc/logging.h> #include <dmlc/thread_local.h> #include <decord/runtime/registry.h> #include <unordered_map> #include <mutex> #include <memory> #include <array> #include "runtime_base.h" namespace decord { namespace runtime { struct Registry::Manager { // map storing the functions. // We delibrately used raw pointer // This is because PackedFunc can contain callbacks into the host languge(python) // and the resource can become invalid because of indeterminstic order of destruction. // The resources will only be recycled during program exit. std::unordered_map<std::string, Registry*> fmap; // vtable for extension type std::array<ExtTypeVTable, kExtEnd> ext_vtable; // mutex std::mutex mutex; Manager() { for (auto& x : ext_vtable) { x.destroy = nullptr; } } static Manager* Global() { // We deliberately leak the Manager instance, to avoid leak sanitizers // complaining about the entries in Manager::fmap being leaked at program // exit. static Manager* inst = new Manager(); return inst; } }; Registry& Registry::set_body(PackedFunc f) { // NOLINT(*) func_ = f; return *this; } Registry& Registry::Register(const std::string& name, bool override) { // NOLINT(*) Manager* m = Manager::Global(); std::lock_guard<std::mutex> lock(m->mutex); auto it = m->fmap.find(name); if (it == m->fmap.end()) { Registry* r = new Registry(); r->name_ = name; m->fmap[name] = r; return *r; } else { CHECK(override) << "Global PackedFunc " << name << " is already registered"; return *it->second; } } bool Registry::Remove(const std::string& name) { Manager* m = Manager::Global(); std::lock_guard<std::mutex> lock(m->mutex); auto it = m->fmap.find(name); if (it == m->fmap.end()) return false; m->fmap.erase(it); return true; } const PackedFunc* Registry::Get(const std::string& name) { Manager* m = Manager::Global(); std::lock_guard<std::mutex> lock(m->mutex); auto it = m->fmap.find(name); if (it == m->fmap.end()) return nullptr; return &(it->second->func_); } std::vector<std::string> Registry::ListNames() { Manager* m = Manager::Global(); std::lock_guard<std::mutex> lock(m->mutex); std::vector<std::string> keys; keys.reserve(m->fmap.size()); for (const auto &kv : m->fmap) { keys.push_back(kv.first); } return keys; } ExtTypeVTable* ExtTypeVTable::Get(int type_code) { CHECK(type_code > kExtBegin && type_code < kExtEnd); Registry::Manager* m = Registry::Manager::Global(); ExtTypeVTable* vt = &(m->ext_vtable[type_code]); CHECK(vt->destroy != nullptr) << "Extension type not registered"; return vt; } ExtTypeVTable* ExtTypeVTable::RegisterInternal( int type_code, const ExtTypeVTable& vt) { CHECK(type_code > kExtBegin && type_code < kExtEnd); Registry::Manager* m = Registry::Manager::Global(); std::lock_guard<std::mutex> lock(m->mutex); ExtTypeVTable* pvt = &(m->ext_vtable[type_code]); pvt[0] = vt; return pvt; } } // namespace runtime } // namespace decord /*! \brief entry to to easily hold returning information */ struct DECORDFuncThreadLocalEntry { /*! \brief result holder for returning strings */ std::vector<std::string> ret_vec_str; /*! \brief result holder for returning string pointers */ std::vector<const char *> ret_vec_charp; }; /*! \brief Thread local store that can be used to hold return values. */ typedef dmlc::ThreadLocalStore<DECORDFuncThreadLocalEntry> DECORDFuncThreadLocalStore; int DECORDExtTypeFree(void* handle, int type_code) { API_BEGIN(); decord::runtime::ExtTypeVTable::Get(type_code)->destroy(handle); API_END(); } int DECORDFuncRegisterGlobal( const char* name, DECORDFunctionHandle f, int override) { API_BEGIN(); decord::runtime::Registry::Register(name, override != 0) .set_body(*static_cast<decord::runtime::PackedFunc*>(f)); API_END(); } int DECORDFuncGetGlobal(const char* name, DECORDFunctionHandle* out) { API_BEGIN(); const decord::runtime::PackedFunc* fp = decord::runtime::Registry::Get(name); if (fp != nullptr) { *out = new decord::runtime::PackedFunc(*fp); // NOLINT(*) } else { *out = nullptr; } API_END(); } int DECORDFuncListGlobalNames(int *out_size, const char*** out_array) { API_BEGIN(); DECORDFuncThreadLocalEntry *ret = DECORDFuncThreadLocalStore::Get(); ret->ret_vec_str = decord::runtime::Registry::ListNames(); ret->ret_vec_charp.clear(); for (size_t i = 0; i < ret->ret_vec_str.size(); ++i) { ret->ret_vec_charp.push_back(ret->ret_vec_str[i].c_str()); } *out_array = dmlc::BeginPtr(ret->ret_vec_charp); *out_size = static_cast<int>(ret->ret_vec_str.size()); API_END(); }
29.690909
88
0.676669
[ "vector" ]
627224039141977553250e66d6c48d4795d7511b
8,552
cpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/boundary.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/boundary.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/libs/locale/src/icu/boundary.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_LOCALE_SOURCE #include <unicode/uversion.h> #include <boost/locale/boundary.hpp> #include <boost/locale/generator.hpp> #include <boost/locale/hold_ptr.hpp> #if U_ICU_VERSION_MAJOR_NUM * 100 + U_ICU_VERSION_MINOR_NUM >= 306 #include <unicode/utext.h> #endif #include "all_generator.hpp" #include "cdata.hpp" #include "icu_util.hpp" #include "uconv.hpp" #include <unicode/brkiter.h> #include <unicode/rbbi.h> namespace boost { namespace locale { namespace boundary { namespace impl_icu { using namespace boost::locale::impl_icu; index_type map_direct(boundary_type t, icu::BreakIterator* it, int reserve) { index_type indx; indx.reserve(reserve); #if U_ICU_VERSION_MAJOR_NUM >= 52 icu::BreakIterator* rbbi = it; #else icu::RuleBasedBreakIterator* rbbi = dynamic_cast<icu::RuleBasedBreakIterator*>(it); #endif indx.push_back(break_info()); it->first(); int pos = 0; while ((pos = it->next()) != icu::BreakIterator::DONE) { indx.push_back(break_info(pos)); /// Character does not have any specific break types if (t != character && rbbi) { // // There is a collapse for MSVC: int32_t defined by both // boost::cstdint and icu... So need to pick one ;( // std::vector<::int32_t> buffer; ::int32_t membuf[8] = { 0}; // try not to use memory allocation if possible ::int32_t* buf = membuf; UErrorCode err = U_ZERO_ERROR; int n = rbbi->getRuleStatusVec(buf, 8, err); if (err == U_BUFFER_OVERFLOW_ERROR) { buf = &buffer.front(); buffer.resize(n, 0); n = rbbi->getRuleStatusVec(buf, buffer.size(), err); } check_and_throw_icu_error(err); for (int i = 0; i < n; i++) { switch (t) { case word: if (UBRK_WORD_NONE <= buf[i] && buf[i] < UBRK_WORD_NONE_LIMIT) indx.back().rule |= word_none; else if (UBRK_WORD_NUMBER <= buf[i] && buf[i] < UBRK_WORD_NUMBER_LIMIT) indx.back().rule |= word_number; else if (UBRK_WORD_LETTER <= buf[i] && buf[i] < UBRK_WORD_LETTER_LIMIT) indx.back().rule |= word_letter; else if (UBRK_WORD_KANA <= buf[i] && buf[i] < UBRK_WORD_KANA_LIMIT) indx.back().rule |= word_kana; else if (UBRK_WORD_IDEO <= buf[i] && buf[i] < UBRK_WORD_IDEO_LIMIT) indx.back().rule |= word_ideo; break; case line: if (UBRK_LINE_SOFT <= buf[i] && buf[i] < UBRK_LINE_SOFT_LIMIT) indx.back().rule |= line_soft; else if (UBRK_LINE_HARD <= buf[i] && buf[i] < UBRK_LINE_HARD_LIMIT) indx.back().rule |= line_hard; break; case sentence: if (UBRK_SENTENCE_TERM <= buf[i] && buf[i] < UBRK_SENTENCE_TERM_LIMIT) indx.back().rule |= sentence_term; else if (UBRK_SENTENCE_SEP <= buf[i] && buf[i] < UBRK_SENTENCE_SEP_LIMIT) indx.back().rule |= sentence_sep; break; default:; } } } else { indx.back().rule |= character_any; // Baisc mark... for character } } return indx; } icu::BreakIterator* get_iterator(boundary_type t, icu::Locale const& loc) { UErrorCode err = U_ZERO_ERROR; hold_ptr<icu::BreakIterator> bi; switch (t) { case character: bi.reset(icu::BreakIterator::createCharacterInstance(loc, err)); break; case word: bi.reset(icu::BreakIterator::createWordInstance(loc, err)); break; case sentence: bi.reset(icu::BreakIterator::createSentenceInstance(loc, err)); break; case line: bi.reset(icu::BreakIterator::createLineInstance(loc, err)); break; default: throw std::runtime_error("Invalid iteration type"); } check_and_throw_icu_error(err); if (!bi.get()) throw std::runtime_error("Failed to create break iterator"); return bi.release(); } template <typename CharType> index_type do_map(boundary_type t, CharType const* begin, CharType const* end, icu::Locale const& loc, std::string const& encoding) { index_type indx; hold_ptr<icu::BreakIterator> bi(get_iterator(t, loc)); #if U_ICU_VERSION_MAJOR_NUM * 100 + U_ICU_VERSION_MINOR_NUM >= 306 UErrorCode err = U_ZERO_ERROR; if (sizeof(CharType) == 2 || (sizeof(CharType) == 1 && encoding == "UTF-8")) { UText* ut = 0; try { if (sizeof(CharType) == 1) ut = utext_openUTF8(0, reinterpret_cast<char const*>(begin), end - begin, &err); else // sizeof(CharType)==2 ut = utext_openUChars(0, reinterpret_cast<UChar const*>(begin), end - begin, &err); check_and_throw_icu_error(err); err = U_ZERO_ERROR; if (!ut) throw std::runtime_error("Failed to create UText"); bi->setText(ut, err); check_and_throw_icu_error(err); index_type res = map_direct(t, bi.get(), end - begin); indx.swap(res); } catch (...) { if (ut) utext_close(ut); throw; } if (ut) utext_close(ut); } else #endif { icu_std_converter<CharType> cvt(encoding); icu::UnicodeString str = cvt.icu(begin, end); bi->setText(str); index_type indirect = map_direct(t, bi.get(), str.length()); indx = indirect; for (size_t i = 1; i < indirect.size(); i++) { size_t offset_inderect = indirect[i - 1].offset; size_t diff = indirect[i].offset - offset_inderect; size_t offset_direct = indx[i - 1].offset; indx[i].offset = offset_direct + cvt.cut(str, begin, end, diff, offset_inderect, offset_direct); } } return indx; } // do_map template <typename CharType> class boundary_indexing_impl : public boundary_indexing<CharType> { public: boundary_indexing_impl(cdata const& data) : locale_(data.locale), encoding_(data.encoding) { } index_type map(boundary_type t, CharType const* begin, CharType const* end) const { return do_map<CharType>(t, begin, end, locale_, encoding_); } private: icu::Locale locale_; std::string encoding_; }; } // namespace impl_icu } // namespace boundary namespace impl_icu { std::locale create_boundary(std::locale const& in, cdata const& cd, character_facet_type type) { using namespace boost::locale::boundary::impl_icu; switch (type) { case char_facet: return std::locale(in, new boundary_indexing_impl<char>(cd)); case wchar_t_facet: return std::locale(in, new boundary_indexing_impl<wchar_t>(cd)); #ifdef BOOST_LOCALE_ENABLE_CHAR16_T case char16_t_facet: return std::locale(in, new boundary_indexing_impl<char16_t>(cd)); #endif #ifdef BOOST_LOCALE_ENABLE_CHAR32_T case char32_t_facet: return std::locale(in, new boundary_indexing_impl<char32_t>(cd)); #endif default: return in; } } } // namespace impl_icu } // namespace locale } // namespace boost // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
32.150376
80
0.536483
[ "vector" ]
6276be0946b9c991d81f393ed4851dd83b865df8
10,508
cpp
C++
src/HMPdetector.cpp
Yeshasvitvs/HMP
cdaa4cf2a9eaa0ebe4708d965b110b44698ef666
[ "MIT" ]
null
null
null
src/HMPdetector.cpp
Yeshasvitvs/HMP
cdaa4cf2a9eaa0ebe4708d965b110b44698ef666
[ "MIT" ]
null
null
null
src/HMPdetector.cpp
Yeshasvitvs/HMP
cdaa4cf2a9eaa0ebe4708d965b110b44698ef666
[ "MIT" ]
null
null
null
//===============================================================================// // Name : HMPdetector.cpp // Author(s) : Barbara Bruno // Affiliation : University of Genova, Italy - dept. DIBRIS // Version : 1.1 // Description : Human Motion Primitives and Fall detection system //===============================================================================// #include <getopt.h> #include <ros/ros.h> #include <signal.h> #include <std_msgs/Char.h> #include "HMPdetector/creator.hpp" #include "HMPdetector/classifier.hpp" #include "HMPdetector/reasoner.hpp" #include "HMPdetector/FallDetector.hpp" #include "HMPdetector/SerialStream.h" using namespace boost::posix_time; using namespace ros; //Variables for ROS implementation std_msgs::Char letter_detected; ros::Publisher gesture_pub; //void gesture_receive(int); void mySigintHandler(int sig) { // All the default sigint handler does is call shutdown() ros::shutdown(); } //! perform on-line full analysis of a data stream void completeHMPdetector(char* port, Reasoner oneR, FallDetector oneF) { string raw_data; // current raw data acquired via USB int nS = 0; // number of acquired samples mat actsample; // current sample in matrix format int ax, ay, az; // accelerometer current sample components int gx, gy, gz; // gyroscope current sample components char dev; // flag --> device type string motion; // flag --> level of motion at the wrist vector<float> poss; // models possibilities vector<float> past_poss; // models previous possibilities string waste = " "; // instantiate and initialize a Classifier string dF = oneR.datasetFolder.substr(0,oneR.datasetFolder.length()-1); dF = dF.substr(9); Classifier hC(dF); mat window = zeros<mat>(hC.window_size, 3); mat gravity = zeros<mat>(hC.window_size, 3); mat body = zeros<mat>(hC.window_size, 3); // initialize the possibilities and past possibilities for(int i = 0; i < oneR.nbM; i++) { poss.push_back(0); past_poss.push_back(0); } // setup the serial communication (read-only) SerialOptions options; options.setDevice(port); options.setBaudrate(9600); options.setTimeout(seconds(0)); options.setParity(SerialOptions::noparity); options.setCsize(8); options.setFlowControl(SerialOptions::noflow); options.setStopBits(SerialOptions::one); SerialStream serial(options); serial.exceptions(ios::badbit | ios::failbit); // classify the stream of raw acceleration & gyroscope data while(peiskmt_isRunning()) { try { // acquire the data received by the XBee getline(serial,raw_data); switch (raw_data[0]) { // call the FallDetector if the raw_data begin with "F" // --> data format: F Fall [Posture] [Motion] case 'F': oneF.publishFall(raw_data); break; // call the Reasoner if the raw_data begin with "H" // --> data format: H [ax] [ay] [ax] [gx] [gy] [gz] [Motion] case 'H': istringstream stream(raw_data); stream >>dev >>ax >> ay >>az >>gx >>gy >>gz >>motion; actsample <<ax <<ay <<az; // update the window of samples to be analyzed hC.createWindow(actsample, window, hC.window_size, nS); if (nS >= hC.window_size) { // analyze the window and compute the models possibilities for(int i = 0; i < oneR.nbM; i++) past_poss[i] = poss[i]; hC.analyzeWindow(window, gravity, body); hC.compareAll(gravity, body, poss); // publish the dynamic tuples hC.publishDynamic(poss); // extract/update activation intervals for each activity for(int i = 0; i < oneR.nbM; i++) oneR.updateInterval(i,nS,poss[i],past_poss[i],1,waste); } break; } } catch(TimeoutException&) { serial.clear(); cerr<<"Timeout occurred"<<endl; } } } //! Program help void print_help() { cout<<endl; cout<<"\t\t -------------- HMP DETECTOR --------------" <<endl; cout<<"Detailed help is in the Documentation inside the docs folder." <<endl; cout<<"Typical calls use the following instructions:" <<endl; cout<<"01) -h --help \t\t\t : program help." <<endl; cout<<"02) -m --model [dataset] \t : [dataset] models creation." <<endl; cout<<"03) -l --load [dataset] \t : load models in [dataset]." <<endl; cout<<"04) -v --validate [model] [set] [n]:" <<" validate [model] with [n] trials of [set]." <<endl; cout<<"05) -t --test [trial] \t\t :" <<" off-line classification of [trial]." <<endl; cout<<"06) -c --classify [port] \t :" <<" on-line classification of [port] stream." <<endl; cout<<"07) -r --reason [path] [possFile] :" <<" off-line reasoning on [path]/[possFile]." <<endl; cout<<"08) -i --interval [port] \t :" <<" on-line reasoning on [port] stream." <<endl; cout<<"09) -f --fall [port] \t\t :" <<" on-line fall detection in [port] stream." <<endl; cout<<"10) -u --ultimate [port] \t :" <<" on-line full analysis of [port] stream." <<endl; cout<<endl; cout<<"Functions calls examples:" <<endl; cout<<"01) ./HMPdetector -h" <<endl; cout<<"02.1) ./HMPdetector -m" <<endl; cout<<"02.2) ./HMPdetector -m Ovada" <<endl; cout<<"03) ./HMPdetector -l Ovada" <<endl; cout<<"04) ./HMPdetector -v climb Ovada 6" <<endl; cout<<"05) ./HMPdetector -t drink_drink_stand_sit_drink.txt" <<endl; cout<<"06) ./HMPdetector -c /dev/ttyUSB0" <<endl; cout<<"07) ./HMPdetector -r " <<"./Results/longTest/ res_drink_drink_stand_sit_drink.txt" <<endl; cout<<"08) ./HMPdetector -i /dev/ttyUSB0" <<endl; cout<<"09) ./HMPdetector -f /dev/ttyUSB0" <<endl; cout<<"10) ./HMPdetector -u /dev/ttyUSB0" <<endl; cout<<endl; cout<<"Enjoy!"<<endl; cout<<endl; } void gesture_receive(char new_value){ //cout<<"new_value : "<<new_value<<endl; letter_detected.data=new_value; //ROS code for publishing the detected gesture //cout<<"Letter Received : "<<letter_detected.data<<endl; gesture_pub.publish(letter_detected); } int main(int argc, char* argv[]) //int main(int argc, char** argv) { //ROS functionality cout<<"ArgC Value : "<<argc<<endl; //cout<<*argv[0]<<" "<<*argv[1]<<" "<<*argv[2]<<endl; //ROS Initialization ros::init(argc,argv,"HMPdetector"); ROS_INFO("HMP Node creation"); ros::NodeHandle n_hmp; //Publishing gesture_pub=n_hmp.advertise<std_msgs::Char>("/gesture_detected",1); // instantiate & initialize the PEIS component peiskmt_initialize(&argc, argv); // retrieve componentID from the component int componentID = peiskmt_peisid(); printf("componentID: %d\n", componentID); // instantiate & initialize the HMPdetector components string dF = "Letters"; cout<<"Initializing HMPdetector..."<<endl; Creator one_creator(dF); Classifier one_classifier(dF); //ROS process dying HERE -- Fixed this by correcting the path config files //DEBUG: one_classifier.printSetInfo(); Reasoner one_reasoner(dF); //DEBUG: one_reasoner.printSetStatus(); cout<<endl <<"DONE" <<endl; cout<<"Dataset folder: " <<one_reasoner.datasetFolder <<endl; FallDetector one_falldetector; //// models - Orebro //model Climb("Climb", 5, 13, 16); // format: ax ay az gx gy gz ////model Drink("Drink", 5, 8, 11); // format: ax ay az //model PickUpDrink("PickUpDrink", 5, 8, 11); // format: ax ay az //model PutDownDrink("PutDownDrink", 5, 8, 11); // format: ax ay az ////model Pour("Pour", 5, 8, 11); // format: ax ay az gx gy gz //model PickUpPour("PickUpPour", 5, 8, 11); // format: ax ay az gx gy gz //model PutDownPour("PutDownPour", 5, 8, 11); // format: ax ay az gx gy gz //model Sit("Sit", 5, 6, 6); // format: ax ay az gx gy gz //model Stand("Stand", 5, 7, 6); // format: ax ay az gx gy gz //model Walk("Walk", 5, 13, 21); // format: ax ay az gx gy gz // available options (short-form) const char *short_options = "v:r:ufictl:mh"; // available options (long-form) static struct option long_options[] = { {"validate", required_argument, 0, 'v'}, {"reason", required_argument, 0, 'r'}, {"ultimate", required_argument, 0, 'u'}, {"fall", required_argument, 0, 'f'}, {"interval", required_argument, 0, 'i'}, {"classify", required_argument, 0, 'c'}, {"test", required_argument, 0, 't'}, {"load", required_argument, 0, 'l'}, {"model", optional_argument, 0, 'm'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} //required line }; // retrieve & execute the chosen option char c; c = getopt_long(argc, argv, short_options, long_options, NULL); //while(ros::ok()){ do { switch (c) { case 'h': //ROS implementation works print_help(); return EXIT_SUCCESS; break; case 'm': //ROS implementation works if(argv[2]) one_creator.setDatasetFolder(argv[2]); one_creator.generateAllModels(); cout<<"modelling dataset in: "<<one_creator.datasetFolder <<endl; return EXIT_SUCCESS; break; case 'l': //ROS implementation works one_classifier.buildSet(argv[2]); cout<<"loaded dataset of: "<<one_classifier.datasetFolder <<endl; return EXIT_SUCCESS; break; case 'v': //ROS implementation works one_classifier.validateModel(argv[2], argv[3], atoi(argv[4])); //one_classifier.printSetInfo(); //Debug Code cout<<"results in: ./Results/" <<argv[3] <<"/" <<endl; return EXIT_SUCCESS; break; case 't': //ROS implementation not done one_classifier.longTest(argv[2]); cout<<"results in: ./Results/longTest/" <<endl; return EXIT_SUCCESS; break; case 'c': //ROS implementation works cout<<"use 'tupleview' to monitor the system" <<endl; one_classifier.onlineTest(argv[2]); //signal(SIGINT, mySigintHandler); return EXIT_SUCCESS; break; case 'r': //ROS implementation not done one_reasoner.offlineReasoner(argv[2], argv[3]); cout<<"results in: " <<argv[2] <<endl; return EXIT_SUCCESS; break; case 'i': //ROS implementation not done cout<<"use 'tupleview' to monitor the system" <<endl; one_reasoner.onlineReasoner(argv[2]); return EXIT_SUCCESS; break; case 'f': //ROS implementation not done cout<<"use 'tupleview' to monitor the system" <<endl; one_falldetector.standaloneFall(argv[2]); return EXIT_SUCCESS; break; case 'u': //ROS implementation not done cout<<"use 'tupleview' to monitor the system" <<endl; completeHMPdetector(argv[2], one_reasoner, one_falldetector); return EXIT_SUCCESS; break; default: print_help(); return EXIT_SUCCESS; break; } }while (c != -1); //}//End of ROS Ok while loop return 0; }
31.842424
106
0.644271
[ "vector", "model" ]
627aa3a0ed1acca2b791208da4873c5b01a24e4d
2,001
cpp
C++
solutions/LeetCode/C++/890.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/890.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/890.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission #include <iostresam> #include <vector> class Solution { public: string toPattern(string word) { map<char,char> M; int curr = 97; // a = 97 for ( char& w : word ) { if ( M.count(w) == 0 ) M[w] = (char) curr++; } for ( int i = 0 ; i < word.length() ; i++) { word[i] = M[word[i]]; } return word; } vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string> result; string p = toPattern (pattern); for (string& word: words) if (toPattern(word).compare(p) == 0) { result.push_back(word); } return result; } }; __________________________________________________________________________________________________ sample 9028 kb submission static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { public: std::vector<std::string> findAndReplacePattern( std::vector<std::string>& words, std::string pattern) { const std::string pattern_sig = signatur(pattern); std::vector<std::string> res; res.reserve(words.size()); for (const string& word : words) { if (pattern_sig == signatur(word)) { res.push_back(word); } } return res; } private: std::string signatur(const std::string& s) { char i ='\1'; std::array<char, 256> m = {0}; std::string res; res.reserve(s.size()); for (char ch : s) { if (m[ch] == '\0') { m[ch] = i++; } res.push_back(m[ch]); } return res; } }; __________________________________________________________________________________________________
30.784615
98
0.563218
[ "vector" ]
627ac31f476e82994771f6a35229c7f624d0483b
1,051
hpp
C++
src/main/cpp/lemon/log/sink.hpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
1
2018-01-12T05:13:58.000Z
2018-01-12T05:13:58.000Z
src/main/cpp/lemon/log/sink.hpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
src/main/cpp/lemon/log/sink.hpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
#ifndef LEMON_LOG_SINK_HPP #define LEMON_LOG_SINK_HPP #include <vector> #include <string> #include <unordered_set> #include <lemon/nocopy.hpp> namespace lemon{ namespace log{ /** * the predeclared of message structure */ struct message; class sink { public: sink():_apply_all(true){} sink(const std::vector<std::string> & sources) :_apply_all(false),_apply_sources(sources.begin(),sources.end()) { } virtual void write(const message & msg) = 0; virtual ~sink(){} bool apply_all() const { return _apply_all; } bool apply(const std::string & source) const { return _apply_all || _apply_sources.count(source) == 1; } private: bool _apply_all; std::unordered_set<std::string> _apply_sources; }; /** * this is the console log sink implement */ class console : public sink,private nocopy { public: console() = default; console(const std::vector<std::string> & sources) :sink(sources) { } void write(const message & msg) final; }; }} #endif //LEMON_LOG_SINK_HPP
15.924242
67
0.669838
[ "vector" ]
627cfe1abe1b0b2b170bc3143aab134f34ace777
1,089
cpp
C++
04. Arrays/Subarrays_with_k_different_integers.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
225
2021-10-01T03:09:01.000Z
2022-03-11T11:32:49.000Z
04. Arrays/Subarrays_with_k_different_integers.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
252
2021-10-01T03:45:20.000Z
2021-12-07T18:32:46.000Z
04. Arrays/Subarrays_with_k_different_integers.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
911
2021-10-01T02:55:19.000Z
2022-02-06T09:08:37.000Z
/* Problem : Given an integer array and an integer k, return the number of subarrays of given arrays having exactly k different integers. Example: Input: n = 5 ,arr = [1,3,1,3,4] , k = 2 Output: 7 Explanation: subarrays with exactly 2 different integers are: [1,3] , [3,1] , [1,3] , [3,4], [1,3,1], [3,1,3] , [1,3,1,3] */ #include<bits/stdc++.h> using namespace std; int atleast(vector<int>&nums , int k) { unordered_map<int,int>m; int diff = 0; int total = 0; int l = 0; int r = 0; int n = nums.size(); for(;r<n;r++) { if(m[nums[r]] == 0) { diff++; } m[nums[r]]++; if(diff<=k) { total+=(r-l+1); } else { while(l<=r && diff > k) { m[nums[l]]--; if(m[nums[l]] == 0)diff--; l++; } total+=(r-l+1); } } return total; } int subarraysWithKDistinct(vector<int>& nums, int k) { return atleast(nums,k) - atleast(nums,k-1); } int main() { int n; cin>>n; vector<int>nums(n); for(int i=0;i<n;i++) cin>>nums[i]; int k; cin>>k; cout<<subarraysWithKDistinct(nums,k); }
17.015625
134
0.536272
[ "vector" ]
627e902072b539809c451a3007a0d37212cea677
2,303
cc
C++
popravek_pozicije_aero_gel_plosc/distribution_cerphotons/script_distrib_photons.cc
rokgm/Shift-of-Aerogel-panels-ArichBelle2
7258328ba2e43ed1898a96375ee562e32a5f9ea0
[ "Apache-2.0" ]
1
2020-12-02T16:59:50.000Z
2020-12-02T16:59:50.000Z
popravek_pozicije_aero_gel_plosc/distribution_cerphotons/script_distrib_photons.cc
rokgm/Shift-of-Aerogel-panels-ArichBelle2
7258328ba2e43ed1898a96375ee562e32a5f9ea0
[ "Apache-2.0" ]
null
null
null
popravek_pozicije_aero_gel_plosc/distribution_cerphotons/script_distrib_photons.cc
rokgm/Shift-of-Aerogel-panels-ArichBelle2
7258328ba2e43ed1898a96375ee562e32a5f9ea0
[ "Apache-2.0" ]
null
null
null
struct TrackHit { Int_t PDG; Float_t x; Float_t y; Float_t z; Float_t p; Float_t theta; Float_t phi; }; void script_distrib_photons() { TChain *trx = new TChain("arich"); trx->Add("/afs/f9.ijs.si/data/belle/data/arich/arich_mumu_proc11*.root"); TChain *trs = new TChain("arich"); trs->Add("/afs/f9.ijs.si/data/belle/data/arich/arich_mumu_mc13a*.root"); std::vector<Belle2::ARICHPhoton>* photonsx = 0; trx->SetBranchAddress("photons",&photonsx); std::vector<Belle2::ARICHPhoton>* photonss = 0; trs->SetBranchAddress("photons",&photonss); TrackHit recHitx; trx->SetBranchAddress("recHit",&recHitx); TrackHit recHits; trs->SetBranchAddress("recHit",&recHits); Int_t nentriesx = (Int_t)trx->GetEntries(); Int_t nentriess = (Int_t)trs->GetEntries(); TH1D *distphx = new TH1D("distphx", "Distribution of CerPhotons", 66, -0.5, 65.5); TH1D *distphs = new TH1D("distphs", "Distribution of CerPhotons", 66, -0.5, 65.5); for(int j=0; j<nentriesx; j++){ trx->GetEntry(j); int i=0; if(recHitx.p < 6) continue; if(65 < sqrt(recHitx.x * recHitx.x + recHitx.y * recHitx.y) && 100 > sqrt(recHitx.x * recHitx.x + recHitx.y * recHitx.y)){ for(auto &photon : *photonsx){ if(photon.getMirror() != 0) continue; i++; } } if(i!=0){ distphx->Fill(i); } } for(int j=0; j<nentriess; j++){ trs->GetEntry(j); int i=0; if(recHitx.p < 6) continue; if(65 < sqrt(recHits.x * recHits.x + recHits.y * recHits.y) && 100 > sqrt(recHits.x * recHits.x + recHits.y * recHits.y)){ for(auto &photon : *photonss){ if(photon.getMirror() != 0) continue; i++; } } if(i!=0){ distphs->Fill(i); } } distphs->Draw(); distphx->Draw("same"); distphs->SetLineColor(2); TLegend* leg = new TLegend(0.78,0.65,0.98,0.75); leg->AddEntry(distphx, "experiment"); leg->AddEntry(distphs, "simulation"); leg->Draw(); }
27.746988
134
0.521928
[ "vector" ]
62845227f501d143a0f7036740db1954bcd9e665
3,437
cpp
C++
PixelVFO/hotspot.cpp
rzzzwilson/KiCad_Projects
12066e85b066484b9db3202b1ee599748992091f
[ "MIT" ]
null
null
null
PixelVFO/hotspot.cpp
rzzzwilson/KiCad_Projects
12066e85b066484b9db3202b1ee599748992091f
[ "MIT" ]
13
2017-07-18T03:29:05.000Z
2017-11-08T06:32:20.000Z
PixelVFO/hotspot.cpp
rzzzwilson/KiCad_Projects
12066e85b066484b9db3202b1ee599748992091f
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // A "hotspot" system for PixelVFO. // // The idea is to define rectangular extents on the screen with associated // handler functions and arguments. Given a touchscreen touch event with // associated (x, y) coordinates, call the appropriate handler (if any). //////////////////////////////////////////////////////////////////////////////// #include "PixelVFO.h" #include "hotspot.h" //---------------------------------------- // Format one HotSpot struct into a display string. // hs address of the HotSpot to dump // Debug function. //---------------------------------------- const char *hs_display(HotSpot *hs) { static char buffer[128]; sprintf(buffer, "hs: x=%3d, y=%3d, w=%3d, h=%3d, handler=%p, arg=%d", hs->x, hs->y, hs->w, hs->h, hs->handler, hs->arg); return buffer; } //---------------------------------------- // Dump the hotspot array to the console. // msg message to label dump with // hs_array address of the HotSpot array to dump // len length of array // Debug function. //---------------------------------------- void hs_dump(char const *msg, HotSpot *hs_array, int len) { Serial.printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); Serial.printf("HotSpot array: %s\n", msg); for (int i = 0; i < len; ++i) { HotSpot *hs = &hs_array[i]; Serial.printf(" %d: %s\n", i, hs_display(hs)); } Serial.printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); } //---------------------------------------- // Handle a touch on a hotspot. // touch_x X coord of screen touch // touch_y Y coord of screen touch // hs base address of array of HotSpots // hs_len length of 'hs_array' // Returns the boolean value returned by the hotspot handler. //---------------------------------------- bool hs_handletouch(int touch_x, int touch_y, HotSpot *hs, int hs_len) { for (int i = 0; i < hs_len; ++hs, ++i) { DEBUG("***** hs: x=%d, y=%d, arg=%s\n", hs->x, hs->y, hs->arg); if ((touch_x >= hs->x) && (touch_x < hs->x + hs->w) && (touch_y >= hs->y) && (touch_y < hs->y + hs->h)) { bool result = (hs->handler)(hs); DEBUG("hs_handletouch: called hs->handler=%p, result='%s'\n", hs->handler, (result) ? "true" : "false"); return result; } } DEBUG("hs_handletouch: no hotspot found, returning 'false'\n"); return false; } //---------------------------------------- // Determine if a screen touch was on a hotspot. // touch_x X coord of screen touch // touch_y Y coord of screen touch // hs base address of array of HotSpots // hs_len length of 'hs_array' // Returns NULL if no hotspot touched, else the address of the hotspot. //---------------------------------------- HotSpot * hs_touched(int touch_x, int touch_y, HotSpot *hs, int hs_len) { HotSpot *result = NULL; // bool result = (hs->handler)(hs, (void *) NULL); for (int i = 0; i < hs_len; ++hs, ++i) { if ((touch_x >= hs->x) && (touch_x < hs->x + hs->w) && (touch_y >= hs->y) && (touch_y < hs->y + hs->h)) { result = hs; DEBUG("hs_touched: hotspot found (%p)->%s\n", result, hs_display(result)); break; } } DEBUG("hs_touched: returning hs->%s\n", (result) ? hs_display(result) : "NULL"); return result; }
32.121495
82
0.491417
[ "3d" ]
628d72eda6c6f537fc54f0bbb1d23ac791a86cdf
1,133
cpp
C++
src/warping_test.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
3
2015-04-29T11:38:29.000Z
2018-08-31T01:32:13.000Z
src/warping_test.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
null
null
null
src/warping_test.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
null
null
null
#include "splines.h" class TestWarpFwd : public FunctionAndDeriv { public: virtual float value (float t_large) const { float t_small = 0.5f * (1 - cos(M_PI * t_large)); return t_small; } virtual float deriv (float t_large) const { float t_small = M_PI * 0.5f * sin(M_PI * t_large); return t_small; } }; void test_warping (size_t large_size = 1000, size_t small_size = 300) { LOG("building warping object : " << large_size << " --> " << small_size); TestWarpFwd warp_fwd; Spline w(large_size, small_size, warp_fwd); LOG("defining input sequence"); Vector<float> large_in(large_size); Vector<float> small_out(small_size); Vector<float> large_out(large_size); for (size_t i = 0; i < large_size; ++i) { float t = (0.5f + i) / large_size; large_in[i] = sin(4 * 2 * M_PI * t) * t + 0.1 * random_std(); } LOG("transforming forward and backward"); w.transform_fwd(large_in, small_out); w.transform_bwd(small_out, large_out); LOG("RMS inversion error = " << rms_error(large_in, large_out) << " (should be ~ 0.1)"); } int main () { test_warping(); return 0; }
21.788462
75
0.64872
[ "object", "vector" ]
628e00c919e1349edd55ad24c7d6afb9f15229b3
34,080
cpp
C++
src/prod/src/Reliability/LoadBalancing/PLBScheduler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-06-28T02:13:54.000Z
2018-06-28T02:13:54.000Z
src/prod/src/Reliability/LoadBalancing/PLBScheduler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/Reliability/LoadBalancing/PLBScheduler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "PLBScheduler.h" #include "ISystemState.h" #include "PLBConfig.h" #include "PLBEventSource.h" #include "FailoverUnitMovement.h" #include "SystemState.h" #include "ServiceDomain.h" #include "PLBDiagnostics.h" using namespace std; using namespace Common; using namespace Reliability::LoadBalancingComponent; PLBScheduler::PLBScheduler( wstring const& serviceDomainId, PLBEventSource const & trace, bool constraintCheckEnabled, bool balancingEnabled, StopwatchTime lastNodeDown, StopwatchTime lastBalancing, StopwatchTime lastNewNode) : serviceDomainId_(serviceDomainId), trace_(trace), constraintCheckEnabled_(constraintCheckEnabled), balancingEnabled_(balancingEnabled), lastStateChange_(StopwatchTime::Zero), lastLoadChange_(StopwatchTime::Zero), lastNodeDown_(lastNodeDown), lastNewNode_(lastNewNode), currentAction_(), placementAction_(), balancingAction_(), lastActionTime_(StopwatchTime::Zero), lastPlacement_(StopwatchTime::Zero), lastConstraintCheck_(StopwatchTime::Zero), lastBalancing_(lastBalancing), hasLastBalancingAvgStdDev_(false), lastBalancingAvgStdDev_(), movementCounterPerFU_() { placementAction_.SetAction(PLBSchedulerActionType::Creation); balancingAction_.SetAction(PLBSchedulerActionType::FastBalancing); } PLBScheduler::PLBScheduler(PLBScheduler && other) : serviceDomainId_(other.serviceDomainId_), trace_(other.trace_), constraintCheckEnabled_(other.constraintCheckEnabled_), balancingEnabled_(other.balancingEnabled_), lastStateChange_(other.lastStateChange_), lastLoadChange_(other.lastLoadChange_), lastNodeDown_(other.lastNodeDown_), lastNewNode_(other.lastNewNode_), currentAction_(other.currentAction_), placementAction_(other.placementAction_), balancingAction_(other.balancingAction_), lastActionTime_(other.lastActionTime_), lastPlacement_(other.lastPlacement_), lastConstraintCheck_(other.lastConstraintCheck_), lastBalancing_(other.lastBalancing_), hasLastBalancingAvgStdDev_(other.hasLastBalancingAvgStdDev_), lastBalancingAvgStdDev_(other.lastBalancingAvgStdDev_), movementCounterPerFU_(move(other.movementCounterPerFU_)) { } void PLBScheduler::OnNodeUp(StopwatchTime timeStamp) { SystemStateChanged(timeStamp); lastNewNode_ = timeStamp; } void PLBScheduler::OnNodeDown(StopwatchTime timeStamp) { SystemStateChanged(timeStamp); lastNodeDown_ = timeStamp; } void PLBScheduler::OnNodeChanged(StopwatchTime timeStamp) { SystemStateChanged(timeStamp); } void PLBScheduler::OnServiceTypeChanged(StopwatchTime timeStamp) { SystemStateChanged(timeStamp); } void PLBScheduler::OnServiceChanged(StopwatchTime timeStamp) { SystemStateChanged(timeStamp); } void PLBScheduler::OnServiceDeleted(StopwatchTime timeStamp) { timeStamp; } void PLBScheduler::OnFailoverUnitAdded(StopwatchTime timeStamp, Guid fuId) { fuId; SystemStateChanged(timeStamp); } void PLBScheduler::OnFailoverUnitChanged(StopwatchTime timeStamp, Guid fuId) { fuId; SystemStateChanged(timeStamp); } void PLBScheduler::OnFailoverUnitDeleted(StopwatchTime timeStamp, Common::Guid fuId) { SystemStateChanged(timeStamp); movementCounterPerFU_.erase(fuId); } void PLBScheduler::OnLoadChanged(StopwatchTime timeStamp) { lastLoadChange_ = timeStamp; } void PLBScheduler::OnDomainInterrupted(StopwatchTime timeStamp) { // If search was interrupted, we will allow one more round of balancing SystemStateChanged(timeStamp); } void PLBScheduler::SetAction(PLBSchedulerActionType::Enum action) { currentAction_.SetAction(action); } void PLBScheduler::RefreshAction(ISystemState const & systemState, StopwatchTime timeStamp, SchedulingDiagnostics::ServiceDomainSchedulerStageDiagnosticsSPtr stageDiagnosticsSPtr /* = nullptr */) { RefreshTimedCounters(timeStamp); // To handle the Test cases in plbscheduler.test.cpp if (stageDiagnosticsSPtr == nullptr) { stageDiagnosticsSPtr = make_shared<ServiceDomainSchedulerStageDiagnostics>(); } currentAction_.IsSkip = false; PLBConfig & config = PLBConfig::GetConfig(); Common::TimeSpan minConstraintCheckInterval = GetMinConstraintCheckInterval(); Common::TimeSpan minPlacementInterval = GetMinPlacementInterval(); // This list takes all actions that are due to run. vector<pair<Common::StopwatchTime, SchedulerStage::Stage>> expiredActions; //Diagnostics { stageDiagnosticsSPtr->newReplicaNeeded_ = systemState.HasNewReplica(); stageDiagnosticsSPtr->upgradeNeeded_ = systemState.HasPartitionWithReplicaInUpgrade(); stageDiagnosticsSPtr->dropNeeded_ = systemState.HasExtraReplicas(); } bool isCreationActionNeeded = systemState.HasNewReplica() || systemState.HasPartitionWithReplicaInUpgrade() || systemState.HasExtraReplicas(); bool const constraintCheckEnabledLocalConfig = PLBConfig::GetConfig().ConstraintCheckEnabled; bool const loadBalancingEnabledLocalConfig = PLBConfig::GetConfig().LoadBalancingEnabled; bool const canBalanceDueToAppUpgrade = !systemState.HasPartitionInAppUpgrade() || PLBConfig::GetConfig().AllowBalancingDuringApplicationUpgrade; //Diagnostics { TESTASSERT_IF(stageDiagnosticsSPtr->CreationActionNeeded() != isCreationActionNeeded, "Diagnostics CreationActionNeeded Method must be updated to match, failed for sd {0}", serviceDomainId_); stageDiagnosticsSPtr->constraintCheckEnabledConfig_ = constraintCheckEnabledLocalConfig; stageDiagnosticsSPtr->constraintCheckPaused_ = !constraintCheckEnabled_; stageDiagnosticsSPtr->balancingEnabledConfig_ = loadBalancingEnabledLocalConfig; //there will be a messaged surfaced that upgrades caused balancing not to run //in the first case it is due to fabric upgrade //in the second it is due to app upgrade stageDiagnosticsSPtr->balancingPaused_ = !balancingEnabled_ || !canBalanceDueToAppUpgrade; } bool isBalancingEnabled = loadBalancingEnabledLocalConfig && balancingEnabled_ && canBalanceDueToAppUpgrade; bool isConstraintCheckEnabled = constraintCheckEnabledLocalConfig && constraintCheckEnabled_; bool const placementExpired = (timeStamp >= lastPlacement_ + minPlacementInterval); bool const constraintCheckExpired = (timeStamp >= lastConstraintCheck_ + minConstraintCheckInterval); bool const balancingExpired = (timeStamp >= lastBalancing_ + config.MinLoadBalancingInterval); bool const hasMovableReplica = systemState.HasMovableReplica(); //Diagnostics { TESTASSERT_IF( (stageDiagnosticsSPtr->constraintCheckEnabledConfig_ && !stageDiagnosticsSPtr->constraintCheckPaused_) != isConstraintCheckEnabled, "Diagnostics must match isConstraintCheckEnabled"); TESTASSERT_IF( (stageDiagnosticsSPtr->balancingEnabledConfig_ && !stageDiagnosticsSPtr->balancingPaused_) != isBalancingEnabled, "Diagnostics must match isBalancingEnabled"); stageDiagnosticsSPtr->placementExpired_ = placementExpired; stageDiagnosticsSPtr->constraintCheckExpired_ = constraintCheckExpired; stageDiagnosticsSPtr->balancingExpired_ = balancingExpired; stageDiagnosticsSPtr->hasMovableReplica_ = hasMovableReplica; } if (placementExpired) { expiredActions.push_back(make_pair(lastPlacement_ + minPlacementInterval, SchedulerStage::Stage::Placement)); } if (hasMovableReplica && isConstraintCheckEnabled && constraintCheckExpired) { expiredActions.push_back(make_pair(lastConstraintCheck_ + minConstraintCheckInterval, SchedulerStage::Stage::ConstraintCheck)); } if (hasMovableReplica && isBalancingEnabled && balancingExpired) { expiredActions.push_back(make_pair(lastBalancing_ + config.MinLoadBalancingInterval, SchedulerStage::Stage::Balancing)); } bool const noExpiredTimerActions = expiredActions.empty(); //Diagnostics { stageDiagnosticsSPtr->noExpiredTimerActions_ = noExpiredTimerActions; } // If no timers have expired, exit with no action needed if (noExpiredTimerActions) { trace_.Scheduler(serviceDomainId_, wformatString("There are no action eligible for execution in service domain {0}", serviceDomainId_)); currentAction_.End(); //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::NoneExpired; stageDiagnosticsSPtr->decisionScheduled_ = false; } return; } // Look at the actions in order: from the one that waited the longest stable_sort(expiredActions.begin(), expiredActions.end(), [](std::pair<Common::StopwatchTime, SchedulerStage::Stage> first, std::pair<Common::StopwatchTime, SchedulerStage::Stage> second){ return first.first < second.first; }); bool const creationWithMoveEnabled = config.MoveExistingReplicaForPlacement; for (auto it = expiredActions.begin(); it != expiredActions.end(); it++) { SchedulerStage::Stage actionToDo = it->second; std::vector<std::shared_ptr<IConstraintDiagnosticsData>> constraintsDiagnosticsData; switch (actionToDo) { case SchedulerStage::Stage::Placement: // Placement stage lastPlacement_ = timeStamp; if (isCreationActionNeeded) { if (systemState.HasPartitionWithReplicaInUpgrade()) { SystemState const& state = dynamic_cast<SystemState const&>(systemState); ServiceDomain& domain = state.serviceDomain_; if (!domain.PartitionsInUpgrade.empty()) { trace_.Scheduler(serviceDomainId_, wformatString("Service domain partition {0} is in upgrade", *domain.PartitionsInUpgrade.begin())); } } //Re-evaluate throttling conditions for creationwithmove... if (placementAction_.IsCreationWithMove() && IsCreationWithMoveThrottled(systemState)) { // Creation with move is throttled, fall back to creation placementAction_.SetAction(PLBSchedulerActionType::Creation); } // Select this action (Creation or CreationWithMove) to run for this service domain currentAction_ = placementAction_; // Advance the creation action, so that we can switch to CreationWithMove if enabled. // This value will be looked at only after MinPlacementInterval passes again placementAction_.IncreaseIteration(); if (!placementAction_.CanRetry()) { if (placementAction_.Action == PLBSchedulerActionType::Creation && creationWithMoveEnabled) { // Creation has reached maximum number of attempts, try CreationWithMove after MinPlacementInterval passes placementAction_.SetAction(PLBSchedulerActionType::CreationWithMove); } else { // Creation with move can't retry, fall back to creation placementAction_.SetAction(PLBSchedulerActionType::Creation); } } //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::Placement; stageDiagnosticsSPtr->decisionScheduled_ = true; } trace_.Scheduler(serviceDomainId_, wformatString("Current action is {0}; system state has new replica? {1}, has upgrade partition? {2}", L"Placement", systemState.HasNewReplica(), systemState.HasPartitionWithReplicaInUpgrade())); return; } else { // Placement stage is not needed, just pass onto next eligible action trace_.SchedulerActionSkip(serviceDomainId_, L"Placement", L"it is not needed"); placementAction_.SetAction(PLBSchedulerActionType::Creation); } break; case SchedulerStage::Stage::ConstraintCheck: // ConstraintCheck stage lastConstraintCheck_ = timeStamp; stageDiagnosticsSPtr->wasConstraintCheckRun_ = true; if (systemState.IsConstraintSatisfied(constraintsDiagnosticsData)) { // ConstraintCheck stage is not needed. Set lastConstraintCheck_ and goto check next stage trace_.SchedulerActionSkip(serviceDomainId_, L"ConstraintCheck", L"it is not needed"); } else { //Diagnostics { stageDiagnosticsSPtr->constraintsDiagnosticsData_ = move(constraintsDiagnosticsData); } bool nodeThrottled = IsConstraintCheckThrottled(timeStamp); bool allViolationsSkippable = stageDiagnosticsSPtr->AllViolationsSkippable(); if (!nodeThrottled) { // Select ConstraintCheck action to run for this service domain. No tracing here, since PLBDomainStart will trace the action. currentAction_.SetAction(PLBSchedulerActionType::ConstraintCheck); //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::ConstraintCheck; stageDiagnosticsSPtr->decisionScheduled_ = true; } return; } else { //Diagnostics { stageDiagnosticsSPtr->isConstraintCheckNodeChangeThrottled_ = true; } if (!allViolationsSkippable) { // Select ConstraintCheck action to run for this service domain. No tracing here, since PLBDomainStart will trace the action. currentAction_.SetAction(PLBSchedulerActionType::ConstraintCheck); currentAction_.SetConstraintCheckLightness(true); //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::ConstraintCheck; stageDiagnosticsSPtr->decisionScheduled_ = true; } return; } } } break; case SchedulerStage::Stage::Balancing: // Balancing stage if (IsBalancingThrottled(timeStamp, systemState)) { //Diagnostics { stageDiagnosticsSPtr->isbalanced_ = false; stageDiagnosticsSPtr->isBalancingNodeChangeThrottled_ = true; } // Goto next check, do not update timestamp since we want to give balancing a chance if it is throttled by node up/down events continue; } if (systemState.IsBalanced()) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", L"system is balanced"); lastBalancing_ = timeStamp; // FastBalancing did the job, no need to move towards SlowBalancing balancingAction_.SetAction(PLBSchedulerActionType::FastBalancing); //Diagnostics { stageDiagnosticsSPtr->isbalanced_ = true; } continue; } if (ThrottleBalancingForSmallStdDevChange(systemState)) { lastBalancing_ = timeStamp; //Diagnostics { stageDiagnosticsSPtr->isbalanced_ = false; stageDiagnosticsSPtr->isBalancingSmallChangeThrottled_ = true; } } else { // Choose current balancing action to be run for this service domain lastBalancing_ = timeStamp; currentAction_ = balancingAction_; //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::Balancing; stageDiagnosticsSPtr->decisionScheduled_ = true; } // Advance the balancing action, so that we can switch to SlowBalancing if FastBalancing does not find a solution. // This value will be looked at only after MinLoadBalancingInterval passes again balancingAction_.IncreaseIteration(); if (!balancingAction_.CanRetry()) { if (balancingAction_.Action == PLBSchedulerActionType::FastBalancing) { // After we do FastBalancing for PLBActionRetryTimes times, switch to slow after MinBalancingIntervalExpires. balancingAction_.SetAction(PLBSchedulerActionType::SlowBalancing); } else { // After we do SlowBalancing for PLBActionRetryTimes times, switch to fast after MinBalancingIntervalExpires. balancingAction_.SetAction(PLBSchedulerActionType::FastBalancing); } } // Select balancing action for this domain. No tracing here, since PLBDomainStart will trace the action. return; } break; } } // If there is no action selected after checking all states, exit with no action needed // No tracing is done here, RunSearcher() will trace PLBDomainSkip since we are returing NoActionNeeded. currentAction_.End(); //Diagnostics { stageDiagnosticsSPtr->stage_ = SchedulerStage::Stage::Skip; stageDiagnosticsSPtr->decisionScheduled_ = false; } } Common::TimeSpan PLBScheduler::GetNextRefreshInterval(Common::StopwatchTime timestamp) { PLBConfig & config = PLBConfig::GetConfig(); // Set the timers for placement and constraint check, based on their values or based on refresh interval. Common::TimeSpan minConstraintCheckInterval = GetMinConstraintCheckInterval(); Common::TimeSpan minPlacementInterval = GetMinPlacementInterval(); Common::StopwatchTime nextStageTime = lastPlacement_ + minPlacementInterval; nextStageTime = min(nextStageTime, lastConstraintCheck_ + minConstraintCheckInterval); nextStageTime = min(nextStageTime, lastBalancing_ + config.MinLoadBalancingInterval); Common::TimeSpan interval = nextStageTime < timestamp ? Common::TimeSpan::Zero : nextStageTime - timestamp; return interval; } void PLBScheduler::OnMovementGenerated(StopwatchTime timeStamp, double newAvgStdDev, map<Guid, FailoverUnitMovement> const& movementList) { if (currentAction_.Action == PLBSchedulerActionType::NoActionNeeded || currentAction_.IsSkip) { return; } bool isBalancing = currentAction_.IsBalancing(); bool existDefragMetric = false; for (auto defragMetric : PLBConfig::GetConfig().DefragmentationMetrics) { existDefragMetric |= defragMetric.second; } for (auto placementStrategy : PLBConfig::GetConfig().PlacementStrategy) { existDefragMetric |= (placementStrategy.second != Metric::PlacementStrategy::Balancing); } if (!existDefragMetric) { ASSERT_IF(isBalancing && newAvgStdDev < 0.0, "Executed action is Balancing but no or bad newAvgStdDev provided."); } lastActionTime_ = timeStamp; if (isBalancing) { hasLastBalancingAvgStdDev_ = true; lastBalancingAvgStdDev_ = newAvgStdDev; UpdateMovements(timeStamp, movementList); } } void PLBScheduler::Merge(StopwatchTime timeStamp, PLBScheduler && other) { lastNodeDown_ = max(lastNodeDown_, other.lastNodeDown_); lastNewNode_ = max(lastNewNode_, other.lastNewNode_); lastLoadChange_ = max(lastLoadChange_, other.lastLoadChange_); lastActionTime_ = max(lastActionTime_, other.lastActionTime_); lastBalancing_ = max(lastBalancing_, other.lastBalancing_); // if two schedulers are getting merged, we assume the system has changed so we update lastStateChange_ to the current timestamp lastStateChange_ = timeStamp; currentAction_.Reset(); placementAction_.SetAction(PLBSchedulerActionType::Creation); balancingAction_.SetAction(PLBSchedulerActionType::FastBalancing); hasLastBalancingAvgStdDev_ = false; lastBalancingAvgStdDev_ = 0.0; movementCounterPerFU_.insert(other.movementCounterPerFU_.begin(), other.movementCounterPerFU_.end()); } void PLBScheduler::SetConstraintCheckEnabled(bool constraintCheckEnabled, StopwatchTime timeStamp) { if (constraintCheckEnabled_ != constraintCheckEnabled) { trace_.Scheduler(serviceDomainId_, wformatString("ConstraintCheck enabled for service domain {0}: {1}", serviceDomainId_, constraintCheckEnabled)); constraintCheckEnabled_ = constraintCheckEnabled; SystemStateChanged(timeStamp); } } void PLBScheduler::SetBalancingEnabled(bool balancingEnabled, StopwatchTime timeStamp) { if (balancingEnabled_ != balancingEnabled) { trace_.Scheduler(serviceDomainId_, wformatString("Balancing enabled for service domain {0}: {1}", serviceDomainId_, balancingEnabled)); balancingEnabled_ = balancingEnabled; SystemStateChanged(timeStamp); } } void PLBScheduler::RefreshTimedCounters(StopwatchTime timeStamp) { for (auto it = movementCounterPerFU_.begin(); it != movementCounterPerFU_.end(); ) { it->second.Refresh(timeStamp); if (0 == it->second.GetCount()) { it = movementCounterPerFU_.erase(it); } else { ++it; } } } set<Guid> PLBScheduler::GetMovementThrottledFailoverUnits() const { set<Guid> throttled; uint threshold = PLBConfig::GetConfig().MovementPerPartitionThrottleThreshold; for (auto it = movementCounterPerFU_.begin(); it != movementCounterPerFU_.end(); it++) { if (it->second.GetCount() >= threshold) { throttled.insert(it->first); } } return throttled; } bool PLBScheduler::IsSystemChangedSince(StopwatchTime timeStamp) const { return (lastStateChange_ > timeStamp || lastLoadChange_ > timeStamp); } // private members bool PLBScheduler::IsConstraintCheckThrottled(StopwatchTime timeStamp) { PLBConfig const & config = PLBConfig::GetConfig(); if (timeStamp < lastNodeDown_ + config.ConstraintFixPartialDelayAfterNodeDown) { trace_.SchedulerActionSkip(serviceDomainId_, L"ConstraintCheckPartial", L"it has not been long enough since the last node down event"); return true; } else if (timeStamp < lastNewNode_ + config.ConstraintFixPartialDelayAfterNewNode) { trace_.SchedulerActionSkip(serviceDomainId_, L"ConstraintCheckPartial", L"it has not been long enough since the last new node event"); return true; } return false; } bool PLBScheduler::IsBalancingThrottled(StopwatchTime timeStamp, ISystemState const & systemState) { PLBConfig const & config = PLBConfig::GetConfig(); if (timeStamp < lastNodeDown_ + config.BalancingDelayAfterNodeDown) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", L"it has not been long enough since the last node down event"); return true; } else if (timeStamp < lastNewNode_ + config.BalancingDelayAfterNewNode) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", L"it has not been long enough since the last new node event"); return true; } else if (ThrottleGlobalMovements(systemState, L"Balancing") || ThrottleGlobalBalancingMovements(systemState) || (config.MaxPercentageToMove == 0.0)) { return true; } else if (ThrottleBalancingForPerFUMovements(systemState)) { return true; } return false; } bool PLBScheduler::IsCreationWithMoveThrottled(ISystemState const & systemState) { if (ThrottleGlobalMovements(systemState, L"CreationWithMove") || ThrottleGlobalPlacementMovements(systemState)) { return true; } else if (PLBConfig::GetConfig().MaxPercentageToMoveForPlacement == 0.0) { return true; } return false; } void PLBScheduler::SystemStateChanged(StopwatchTime timeStamp) { placementAction_.SetAction(PLBSchedulerActionType::Creation); lastStateChange_ = timeStamp; } Common::TimeSpan PLBScheduler::GetMinConstraintCheckInterval() { // Calculate correct value for constraint check interval: // If user has specified PLBRefreshInterval then use that value, otherwise use MinConstraintCheckInterval // NOTE: This will exist until we deprecate PLBRefreshInterval, and user cannot specify both values (manifest check will fail). PLBConfig & config = PLBConfig::GetConfig(); Common::TimeSpan minConstraintCheckInterval = config.MinConstraintCheckInterval; if (config.MinConstraintCheckIntervalEntry.DefaultValue == minConstraintCheckInterval && config.PLBRefreshIntervalEntry.DefaultValue != config.PLBRefreshInterval) { // If user has changed refresh interval, but not MinConstraintCheckInterval, use refresh instead minConstraintCheckInterval = config.PLBRefreshInterval; } return minConstraintCheckInterval; } Common::TimeSpan PLBScheduler::GetMinPlacementInterval() { // Calculate correct value for placement interval: // If user has specified PLBRefreshInterval then use that value, otherwise use MinPlacementInterval // NOTE: This will exist until we deprecate PLBRefreshInterval, and user cannot specify both values (manifest check will fail). PLBConfig & config = PLBConfig::GetConfig(); Common::TimeSpan minPlacementInterval = config.MinPlacementInterval; if (config.MinPlacementIntervalEntry.DefaultValue == minPlacementInterval && config.PLBRefreshIntervalEntry.DefaultValue != config.PLBRefreshInterval) { // If user has changed refresh interval, but not MinPlacementInterval, use refresh instead minPlacementInterval = config.PLBRefreshInterval; } return minPlacementInterval; } bool PLBScheduler::ThrottleBalancingForSmallStdDevChange(ISystemState const & systemState) const { if (lastStateChange_ > lastBalancing_) { // don't throttle balancing if there is any state change since the last balancing return false; } if (lastStateChange_ < lastBalancing_ && lastLoadChange_ < lastBalancing_) { // there is no system state change since the last balancing thus there is no need for balancing. trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", L"there is no system change since last balancing"); return true; } double avgStdDevDeltaThrottleThreshold = PLBConfig::GetConfig().AvgStdDevDeltaThrottleThreshold; if (avgStdDevDeltaThrottleThreshold >= 0.0 && hasLastBalancingAvgStdDev_ && systemState.GetAvgStdDev() <= lastBalancingAvgStdDev_ * (1 + avgStdDevDeltaThrottleThreshold)) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", wformatString("the current AvgStdDev ({0}) is not much worse than the AvgStdDev from the last balancing ({1})", systemState.GetAvgStdDev(), lastBalancingAvgStdDev_)); return true; } return false; } bool PLBScheduler::AreMovementsThrottled(ISystemState const & systemState, size_t currentMovementCount, double allowedPercentageToMove, uint maxReplicasToMove) { size_t maxMovements = SIZE_T_MAX; // First check if we have a throttle on absolute number of movements. if (maxReplicasToMove != 0) { maxMovements = maxReplicasToMove; } // Then check if we have a throttle on percentage of replicas in the cluster. if (allowedPercentageToMove > 0.0) { size_t maxMovementsByPercentage = static_cast<size_t> (ceil(allowedPercentageToMove * systemState.ExistingReplicaCount())); // If we have both throttles, pick the one that is more conservative. if (maxMovementsByPercentage < maxMovements) { maxMovements = maxMovementsByPercentage; } } // If we have already moved more than threshold, then throttle. return currentMovementCount >= maxMovements; } bool PLBScheduler::ThrottleGlobalBalancingMovements(ISystemState const & systemState) { // global throttle PLBConfig const& config = PLBConfig::GetConfig(); size_t balancingMovements = systemState.BalancingMovementCount(); uint balancingThreshold = config.GlobalMovementThrottleThresholdForBalancing; if (AreMovementsThrottled(systemState, balancingMovements, config.GlobalMovementThrottleThresholdPercentageForBalancing, balancingThreshold)) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", wformatString("The number of movements for Balancing ({0}) in the past {1}) has reached or exceeded the threshold (absolute: {2} percentage: {3})", balancingMovements, config.GlobalMovementThrottleCountingInterval, balancingThreshold, static_cast<size_t>(ceil(systemState.ExistingReplicaCount() * config.GlobalMovementThrottleThresholdPercentageForBalancing)))); return true; } return false; } bool PLBScheduler::ThrottleGlobalPlacementMovements(ISystemState const & systemState) { // global throttle PLBConfig const& config = PLBConfig::GetConfig(); size_t placementMovements = systemState.PlacementMovementCount(); uint placementThreshold = config.GlobalMovementThrottleThresholdForPlacement; if (AreMovementsThrottled(systemState, placementMovements, config.GlobalMovementThrottleThresholdPercentageForPlacement, placementThreshold)) { trace_.SchedulerActionSkip(serviceDomainId_, L"Placement", wformatString("The number of movements for Placement ({0}) in the past {1}) has reached or exceeded the threshold (absolute: {2} percentage: {3})", placementMovements, config.GlobalMovementThrottleCountingInterval, placementThreshold, static_cast<size_t>(ceil(systemState.ExistingReplicaCount() * config.GlobalMovementThrottleThresholdPercentageForPlacement)))); return true; } return false; } bool PLBScheduler::ThrottleGlobalMovements(ISystemState const & systemState, std::wstring const& action) { // global throttle PLBConfig const& config = PLBConfig::GetConfig(); size_t totalMovements = systemState.BalancingMovementCount() +systemState.PlacementMovementCount(); uint threshold = config.GlobalMovementThrottleThreshold; if (AreMovementsThrottled(systemState, totalMovements, config.GlobalMovementThrottleThresholdPercentage, threshold)) { trace_.SchedulerActionSkip(serviceDomainId_, action, wformatString("the total number of failover unit movements ({0}) in the past {1}) has reached or exceeded the threshold (absolute: {2} percentage: {3})", totalMovements, config.GlobalMovementThrottleCountingInterval, threshold, static_cast<size_t>(ceil(systemState.ExistingReplicaCount() * config.GlobalMovementThrottleThresholdPercentage)))); return true; } return false; } bool PLBScheduler::ThrottleBalancingForPerFUMovements(ISystemState const & systemState) { PLBConfig const& config = PLBConfig::GetConfig(); // per-FailoverUnit throttle auto throttledFailoverUnits = GetMovementThrottledFailoverUnits(); auto imbalancedFailoverUnits = systemState.GetImbalancedFailoverUnits(); for (auto it = throttledFailoverUnits.begin(); it != throttledFailoverUnits.end(); ) { if (imbalancedFailoverUnits.find(*it) == imbalancedFailoverUnits.end()) { it = throttledFailoverUnits.erase(it); } else { ++it; } } if (throttledFailoverUnits.size() > imbalancedFailoverUnits.size() * config.MovementThrottledPartitionsPercentageThreshold) { trace_.SchedulerActionSkip(serviceDomainId_, L"Balancing", wformatString("the number of movement throttled failover units ({0}) has exceeded {1}% of the number of imbalanced failover units ({2})", throttledFailoverUnits.size(), config.MovementThrottledPartitionsPercentageThreshold * 100, imbalancedFailoverUnits.size())); return true; } return false; } void PLBScheduler::UpdateMovements(StopwatchTime timeStamp, FailoverUnitMovementTable const& movementList) { PLBConfig const& config = PLBConfig::GetConfig(); TimeSpan interval = config.MovementPerPartitionThrottleCountingInterval; for (auto it = movementList.begin(); it != movementList.end(); ++it) { auto counterIt = movementCounterPerFU_.find(it->first); if (counterIt == movementCounterPerFU_.end()) { counterIt = movementCounterPerFU_.insert(make_pair(it->first, TimedCounter(interval, FUMovementCounterWindowCount))).first; } counterIt->second.Record(1, timeStamp); } }
41.109771
233
0.685945
[ "vector" ]
62957126bd6877698270b4e3b451d893e28b5d87
5,741
cpp
C++
services/game_console/server/checksystem.cpp
vient/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
2
2020-04-22T19:36:16.000Z
2020-09-16T07:45:54.000Z
services/game_console/server/checksystem.cpp
vient/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
3
2021-03-31T19:21:51.000Z
2021-06-08T20:31:48.000Z
services/game_console/server/checksystem.cpp
leetchicken/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
3
2019-10-26T00:25:03.000Z
2019-11-23T21:10:10.000Z
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <thread> #include <mutex> #include <map> #include "checksystem.h" #include "network.h" #include "../common.h" #include "log.h" struct HwConsole { HwConsole() = default; std::mutex mutex; Socket* socket = nullptr; IPAddr addr = ~0u; bool checkInProgress = false; uint32_t rasterResult = 0; bool checkResult = false; void StartCheck(); void Reset(); }; static std::map<NetworkAddr, HwConsole> GConsoles; static std::thread GNetworkThread; static Point2D GeneratePoint(Point2D& encodedV) { Point2D ret; ret.x = rand() % kScreenSize; ret.y = rand() % kScreenSize; encodedV.x = (rand() << kBitsForCoord) | ret.x; encodedV.y = (rand() << kBitsForCoord) | ret.y; return ret; } void HwConsole::StartCheck() { std::lock_guard<std::mutex> guard(mutex); if(checkInProgress || !socket) return; Point2D v[3]; Point2D encodedV[3]; for(uint32_t i = 0; i < 3; i++) v[i] = GeneratePoint(encodedV[i]); int doubleTriArea = EdgeFunction(v[0], v[1], v[2]); if(doubleTriArea < 0) { std::swap(v[0], v[1]); std::swap(encodedV[0], encodedV[1]); } socket->sendBufferSize = sizeof(encodedV); socket->sendBufferOffset = 0; memcpy(socket->sendBuffer, encodedV, sizeof(encodedV)); socket->state = Socket::kStateSending; socket->lastTouchTime = GetTime(); rasterResult = Rasterize(v); checkResult = false; checkInProgress = true; } void HwConsole::Reset() { socket->Close(); socket = nullptr; addr = ~0u; checkResult = false; checkInProgress = false; } static bool AcceptConnection(Socket* socket, const sockaddr_in& clientAddr) { Log("CHECKSYSTEM: Accepted connection from: %s\n", inet_ntoa(clientAddr.sin_addr)); NetworkAddr netAddr = SockaddrToNetworkAddr(clientAddr.sin_addr); auto iter = GConsoles.find(netAddr); if(iter == GConsoles.end()) { Log("CHECKSYSTEM: unknown network, close connection\n"); return false; } HwConsole* console = &iter->second; { std::lock_guard<std::mutex> guard(console->mutex); if(console->socket) { Log("CHECKSYSTEM: close previous connection\n"); console->socket->Close(); } console->socket = socket; console->addr = clientAddr.sin_addr.s_addr; console->checkInProgress = false; console->checkResult = false; } socket->userData = console; console->StartCheck(); socket->updateCallback = [](Socket* socket){ if(socket->state == Socket::kStateSending) { if(socket->sendBufferOffset == socket->sendBufferSize) { socket->state = Socket::kStateReceiving; socket->recvBufferSize = sizeof(uint32_t); socket->recvBufferOffset = 0; } } else if(socket->state == Socket::kStateReceiving) { if(socket->recvBufferOffset == socket->recvBufferSize) { uint32_t result; memcpy(&result, socket->recvBuffer, sizeof(uint32_t)); HwConsole* console = (HwConsole*)socket->userData; std::lock_guard<std::mutex> guard(console->mutex); if(console->rasterResult == result) { Log("CHECKSYSTEM: OK\n"); socket->state = Socket::kStateReady; console->checkResult = true; } else { Log("CHECKSYSTEM: Does no match\n"); console->Reset(); } console->checkInProgress = false; } } }; socket->timeoutCallback = [](Socket* socket){ Log("CHECKSYSTEM: socket timeout\n"); HwConsole* console = (HwConsole*)socket->userData; std::lock_guard<std::mutex> guard(console->mutex); console->Reset(); }; socket->closedByPeerCallback = [](Socket* socket){ Log("CHECKSYSTEM: connection closed by peer\n"); HwConsole* console = (HwConsole*)socket->userData; std::lock_guard<std::mutex> guard(console->mutex); console->Reset(); }; socket->errorCallback = [](Socket* socket){ Log("CHECKSYSTEM: socket error: %s\n", strerror(errno)); HwConsole* console = (HwConsole*)socket->userData; std::lock_guard<std::mutex> guard(console->mutex); console->Reset(); }; return true; } void InitChecksystem(const std::vector<NetworkAddr>& teamsNet) { for(auto& net : teamsNet) GConsoles[net]; GNetworkThread = std::thread(NetworkManager, AcceptConnection, kChecksystemPort); } IPAddr GetHwConsoleIp(NetworkAddr teamNet) { auto iter = GConsoles.find(teamNet); if(iter == GConsoles.end()) return ~0u; return iter->second.addr; } bool Check(NetworkAddr teamNet) { auto iter = GConsoles.find(teamNet); if(iter == GConsoles.end()) { Log("CHECKSYSTEM: unkown network passed\n"); return false; } HwConsole* console = &iter->second; console->StartCheck(); uint32_t iteration = 0; while(1) { { std::lock_guard<std::mutex> guard(console->mutex); if(!console->checkInProgress) return console->checkResult; } if(iteration % 1000 == 0) Log("CHECKSYSTEM: waiting for check result '%s', iteration %u\n", inet_ntoa(teamNet), iteration); usleep(1000); iteration++; } return false; }
25.86036
109
0.585438
[ "vector" ]
6296d28da7ae75981f63485ec006fd5e8f115434
10,067
cpp
C++
engine/src/render/utils/ResourceCache.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
engine/src/render/utils/ResourceCache.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
engine/src/render/utils/ResourceCache.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copryright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution /////////// - StormKit::engine - /////////// #include "../../Log.hpp" #include <storm/engine/render/utils/ResourceCache.hpp> /////////// - StormKit::log - /////////// #include <storm/log/LogHandler.hpp> /////////// - StormKit::render - /////////// #include <storm/render/core/Device.hpp> /////////// - StormKit::engine - /////////// #include <storm/engine/Engine.hpp> //#include <storm/engine/render/Material.hpp> using namespace storm; using namespace storm::engine; template<typename... Args> core::Hash64 hashParams(Args &&...args) { auto hash = core::Hash64 { 0u }; (core::hashCombine(hash, std::forward<Args>(args)), ...); return hash; } static constexpr auto DESCRIPTOR_COUNT = 1000; template<typename T, auto Maker, typename... Args> T &requestResource(core::HashMap<core::Hash64, T> &cache, core::Hash64 hash, Args &&...args) noexcept { auto is_in_cache = core::ranges::any_of(cache, [&hash](const auto &pair) { return pair.first == hash; }); if (is_in_cache) return cache.at(hash); const auto type = typeid(T).name(); const auto id = std::size(cache); dlog("Build cache for {} ({})", type, id); auto resource = Maker(std::forward<Args>(args)...); return cache.emplace(hash, std::move(resource)).first->second; } ///////////////////////////////////// ///////////////////////////////////// ResourceCache::ResourceCache(const Engine &engine) : m_engine { engine }, m_descriptor_pool { engine.device(), { { storm::render::DescriptorType::Sampler, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Combined_Texture_Sampler, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Sampled_Image, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Storage_Image, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Uniform_Texel_Buffer, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Storage_Texel_Buffer, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Uniform_Buffer, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Storage_Buffer, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Uniform_Buffer_Dynamic, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Storage_Buffer_Dynamic, DESCRIPTOR_COUNT }, { storm::render::DescriptorType::Input_Attachment, DESCRIPTOR_COUNT }, }, DESCRIPTOR_COUNT } { m_pipeline_cache = engine.device().createPipelineCachePtr(); } ///////////////////////////////////// ///////////////////////////////////// ResourceCache::~ResourceCache() = default; ///////////////////////////////////// ///////////////////////////////////// ResourceCache::ResourceCache(ResourceCache &&) noexcept = default; ///////////////////////////////////// ///////////////////////////////////// ResourceCache &ResourceCache::operator=(ResourceCache &&) noexcept = default; ///////////////////////////////////// ///////////////////////////////////// render::DescriptorSetLayout &ResourceCache::requestDescriptorSetLayout( render::DescriptorSetLayoutBindingConstSpan bindings) { constexpr auto maker = [](const Engine &engine, render::DescriptorSetLayoutBindingConstSpan bindings) { auto layout = engine.device().createDescriptorSetLayout(); for (const auto &binding : bindings) layout.addBinding(binding); layout.bake(); return layout; }; const auto hash = hashParams(bindings); #ifdef STORMKIT_COMPILER_CLANG return requestResource<render::DescriptorSetLayout, +maker>(m_descriptor_set_layout_cache, hash, engine(), bindings); #else return requestResource<render::DescriptorSetLayout, maker>(m_descriptor_set_layout_cache, hash, engine(), bindings); #endif } ///////////////////////////////////// ///////////////////////////////////// render::DescriptorSet & ResourceCache::requestDescriptorSet(const render::DescriptorSetLayout &layout, render::DescriptorConstSpan descriptors, bool force_update) { constexpr auto maker = [](render::DescriptorPool &pool, const render::DescriptorSetLayout &layout, render::DescriptorConstSpan descriptors) { auto descriptor_set = pool.allocateDescriptorSet(layout); descriptor_set.update(descriptors); return descriptor_set; }; const auto hash = hashParams(layout, descriptors); #ifdef STORMKIT_COMPILER_CLANG auto &resource = requestResource<render::DescriptorSet, +maker>(m_descriptor_set_cache, hash, m_descriptor_pool, layout, descriptors); #else auto &resource = requestResource<render::DescriptorSet, maker>(m_descriptor_set_cache, hash, m_descriptor_pool, layout, descriptors); #endif resource.update(descriptors); return resource; } ///////////////////////////////////// ///////////////////////////////////// render::Shader &ResourceCache::requestShader(render::ShaderStage stage, core::ByteConstSpan data) { constexpr auto maker = [](const Engine &engine, render::ShaderStage stage, core::ByteConstSpan data) { return engine.device().createShader(data, stage); }; const auto hash = hashParams(stage, data); #ifdef STORMKIT_COMPILER_CLANG return requestResource<render::Shader, +maker>(m_shader_cache, hash, engine(), stage, data); #else return requestResource<render::Shader, maker>(m_shader_cache, hash, engine(), stage, data); #endif } ///////////////////////////////////// ///////////////////////////////////// render::Shader &ResourceCache::requestShader(render::ShaderStage stage, core::span<const render::SpirvID> data) { return requestShader(stage, { reinterpret_cast<const core::Byte *>(std::data(data)), std::size(data) * sizeof(render::SpirvID) }); } ///////////////////////////////////// ///////////////////////////////////// render::HardwareBuffer &ResourceCache::requestGeometryBuffer(core::ByteConstSpan vertex_array, core::ByteConstSpan index_array) { constexpr auto maker = [](const Engine &engine, core::ByteConstSpan vertex_array, core::ByteConstSpan index_array) { return engine.device().createVertexBuffer(std::size(vertex_array) + std::size(index_array), render::MemoryProperty::Device_Local, true); }; const auto hash = hashParams(vertex_array, index_array); #ifdef STORMKIT_COMPILER_CLANG return requestResource<render::HardwareBuffer, +maker>(m_geometry_data_cache, hash, engine(), vertex_array, index_array); #else return requestResource<render::HardwareBuffer, maker>(m_geometry_data_cache, hash, engine(), vertex_array, index_array); #endif } ///////////////////////////////////// ///////////////////////////////////// render::GraphicsPipeline & ResourceCache::requestGraphicsPipeline(const render::GraphicsPipelineState &state, const render::RenderPass &render_pass) { return m_pipeline_cache->getPipeline(state, render_pass); } ///////////////////////////////////// ///////////////////////////////////// render::RenderPass &ResourceCache::requestRenderPass(render::RenderPassDescription description) { constexpr auto maker = [](const Engine &engine, render::RenderPassDescription &&description) { return engine.device().createRenderPass(std::move(description)); }; const auto hash = hashParams(description); #ifdef STORMKIT_COMPILER_CLANG return requestResource<render::RenderPass, +maker>(m_render_pass_cache, hash, engine(), std::move(description)); #else return requestResource<render::RenderPass, maker>(m_render_pass_cache, hash, engine(), std::move(description)); #endif }
42.65678
99
0.492997
[ "render" ]
62a16f624b9c556eeeaf86aef4848f346816d7b3
8,394
cc
C++
tools/RMK/SerializationMap.cc
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
1
2015-07-14T10:05:52.000Z
2015-07-14T10:05:52.000Z
tools/RMK/SerializationMap.cc
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
null
null
null
tools/RMK/SerializationMap.cc
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
1
2019-12-03T15:58:53.000Z
2019-12-03T15:58:53.000Z
#ifdef Parallel #include <mpi.h> #endif #include "tarch/Assertions.h" #include "SerializationMap.h" peano::parallel::SerializationMap& peano::parallel::SerializationMap::getInstance() { static SerializationMap singleton; return singleton; } peano::parallel::SerializationMap::~SerializationMap() { } peano::parallel::SerializationMap::SerializationMap() { } peano::parallel::SerializationMap::ValueType& peano::parallel::SerializationMap::operator[](int rank) { BufferMap::iterator it = _bufferMap.find(rank); if (it == _bufferMap.end()) { // object does not exist yet, insert a new set of buffers Serialization::SendBuffer sendbuffer_temp(true); Serialization::ReceiveBuffer recvbuffer_temp(true); peano::parallel::SerializationMap::SendBufferArrayType sendbuffer_array = {sendbuffer_temp, sendbuffer_temp}; peano::parallel::SerializationMap::ReceiveBufferArrayType recvbuffer_array = {recvbuffer_temp, recvbuffer_temp}; peano::parallel::SerializationMap::ValueType maptype( sendbuffer_array, recvbuffer_array ); std::pair<const int, peano::parallel::SerializationMap::ValueType> temp_value(rank, maptype); std::pair<BufferMap::iterator, bool> result = _bufferMap.insert(temp_value); it = result.first; } return it->second; } peano::parallel::SerializationMap::SendBufferArrayType& peano::parallel::SerializationMap::getSendBuffer(int rank) { return this->operator[](rank).first; } peano::parallel::SerializationMap::ReceiveBufferArrayType& peano::parallel::SerializationMap::getReceiveBuffer(int rank) { return this->operator[](rank).second; } void peano::parallel::SerializationMap::exchangeDataWithNeighbors() { #ifdef Parallel // first determine maximum number of buffer pairs (some might have no data, though) // and allocate a MPI_RequestBuffer of twice the size (one for each send AND receive buffer) std::vector<MPI_Request> requestBuffer(2*numberOfBufferPairs(), MPI_REQUEST_NULL); // initiate MPI calls for deterministic buffers size_t requestBufferPosition = 0; for (BufferMap::iterator it = begin(); it != end(); it++) { int neighbourRank = it->first; ValueType& bufferPair = it->second; // deterministic buffers: we are able to determine the size for the required receive buffers // independently from other processes Serialization::SendBuffer& deterministicSendBuffer = bufferPair.first[0]; Serialization::ReceiveBuffer& deterministicReceiveBuffer = bufferPair.second[0]; assertion(deterministicSendBuffer.verifyBlocks()); // nondeterministic buffers: the opposite of deterministic buffers, hence we need some // additional information to set an appropriate buffer size // in our case: we will put the size of the non deterministic buffer as payload inside the // deterministic buffer stream Serialization::SendBuffer& nondeterministicSendBuffer = bufferPair.first[1]; Serialization::ReceiveBuffer& nondeterministicReceiveBuffer = bufferPair.second[1]; assertion(nondeterministicSendBuffer.verifyBlocks()); Serialization::Block block = deterministicSendBuffer.reserveBlock(sizeof(size_t)); const size_t nondeterministicSendBufferSize = nondeterministicSendBuffer.size(); block << nondeterministicSendBufferSize; deterministicReceiveBuffer.reset(deterministicSendBuffer.size()); //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ SENDING DETERMINISTIC TO " << neighbourRank << " size " << deterministicSendBuffer.size() << std::endl; //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ EXPECTING DETERMINISTIC FROM " << neighbourRank << " size " << deterministicSendBuffer.size() << std::endl; if (deterministicSendBuffer.size() > 0) { MPI_Isend(deterministicSendBuffer.data(), deterministicSendBuffer.size(), MPI_CHAR, neighbourRank, 1337, MPI_COMM_WORLD, requestBuffer.data()+2*requestBufferPosition); MPI_Irecv(deterministicReceiveBuffer.data(), deterministicSendBuffer.size(), MPI_CHAR, neighbourRank, 1337, MPI_COMM_WORLD, requestBuffer.data()+2*requestBufferPosition+1); } requestBufferPosition++; } // wait for MPI actions to finish data exchange of deterministic buffers MPI_Waitall(2*numberOfBufferPairs(), requestBuffer.data(), MPI_STATUSES_IGNORE); #ifdef Asserts for (BufferMap::iterator it = begin(); it != end(); it++) { int neighbourRank = it->first; ValueType& bufferPair = it->second; Serialization::ReceiveBuffer& deterministicReceiveBuffer = bufferPair.second[0]; assertion(deterministicReceiveBuffer.verifyBlocks()); } #endif // clear deterministic send buffer, keep determinisitc receive buffers, // and initiate non deterministic MPI actions requestBufferPosition = 0; for (BufferMap::iterator it = begin(); it != end(); it++) { int neighbourRank = it->first; ValueType& bufferPair = it->second; Serialization::SendBuffer& deterministicSendBuffer = bufferPair.first[0]; Serialization::ReceiveBuffer& deterministicReceiveBuffer = bufferPair.second[0]; Serialization::SendBuffer& nondeterministicSendBuffer = bufferPair.first[1]; Serialization::ReceiveBuffer& nondeterministicReceiveBuffer = bufferPair.second[1]; deterministicSendBuffer.reset(); // extract size for nondeterministic buffer from deterministic reveive buffer assertion1(deterministicReceiveBuffer.isBlockAvailable(), "block for nondeterministic buffer size is missing!"); Serialization::Block block = deterministicReceiveBuffer.nextBlock(); assertion2(block.size() == sizeof(size_t), "block for nondeterministic buffer size has wrong size", block.size()); size_t nondeterministicReceiveBufferSize = 0; block >> nondeterministicReceiveBufferSize; nondeterministicReceiveBuffer.reset(nondeterministicReceiveBufferSize); if (nondeterministicSendBuffer.size() > 0) { //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ SENDING NONDETERMINISTIC TO " << neighbourRank << " size " << nondeterministicSendBuffer.size() << std::endl; MPI_Isend(nondeterministicSendBuffer.data(), nondeterministicSendBuffer.size(), MPI_CHAR, neighbourRank, 1337, MPI_COMM_WORLD, requestBuffer.data()+2*requestBufferPosition); } else { //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ NOT SENDING NONDETERMINISTIC TO " << neighbourRank << std::endl; requestBuffer[2*requestBufferPosition] = MPI_REQUEST_NULL; } if (nondeterministicReceiveBuffer.size() > 0) { //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ EXPECTING NONDETERMINISTIC FROM " << neighbourRank << " size " << nondeterministicReceiveBuffer.size() << std::endl; MPI_Irecv(nondeterministicReceiveBuffer.data(), nondeterministicReceiveBuffer.size(), MPI_CHAR, neighbourRank, 1337, MPI_COMM_WORLD, requestBuffer.data()+2*requestBufferPosition+1); } else { //std::cout << "my rank " << tarch::parallel::Node::getInstance().getRank() << " ------------ NOT EXPECTING NONDETERMINISTIC FROM " << neighbourRank << std::endl; requestBuffer[2*requestBufferPosition+1] = MPI_REQUEST_NULL; } requestBufferPosition++; } // wait for MPI actions to finish data exchange of nondeterministic buffers MPI_Waitall(2*numberOfBufferPairs(), requestBuffer.data(), MPI_STATUSES_IGNORE); // clear nondeterministic send buffer requestBufferPosition = 0; for (BufferMap::iterator it = begin(); it != end(); it++) { peano::parallel::SerializationMap::ValueType& bufferPair = it->second; Serialization::SendBuffer& nondeterministicSendBuffer = bufferPair.first[1]; nondeterministicSendBuffer.reset(); #ifdef Asserts Serialization::ReceiveBuffer& nondeterministicReceiveBuffer = bufferPair.second[1]; assertion(nondeterministicReceiveBuffer.verifyBlocks()); #endif } #endif }
47.965714
222
0.705147
[ "object", "vector" ]
62b01885c2dcd9315215c5f89f563a6a3e6f9788
2,230
cpp
C++
source/test/TestIssues.cpp
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
30
2020-08-01T07:29:23.000Z
2022-03-30T13:21:43.000Z
source/test/TestIssues.cpp
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
48
2019-01-02T18:19:41.000Z
2020-04-26T02:53:23.000Z
source/test/TestIssues.cpp
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
5
2019-08-30T08:41:17.000Z
2020-05-19T01:17:15.000Z
#include <string> #include <vector> #include <gtest/gtest.h> #include "../Common.h" #include "../TraceMemo.h" // clang-format off namespace TestIssue { TEST(Issue55, FirstLineIsAnInvalidPathOnLinux) { // https://github.com/dougpuob/cppnamelint/issues/55 const std::string SourceCode = "\ // \n\ // 1.1.cpp \n\ // \n\ // chapter 1 introduction \n\ // modern cpp tutorial \n\ // \n\ // created by changkun at changkun.de \n\ // https://github.com/changkun/modern-cpp-tutorial \n\ // \n\ \n\ #include \"foo.h/\" \n\ #include <iostream> \n\ #include <functional> \n\ \n\ int main() { \n\ // use lambda expression \n\ [out = std::ref(std::cout << \"Result from C code: \" << add(1, 2))](){ \n\ out.get() << \".\n\"; \n\ }(); \n\ return 0; \n\ }"; AppCxt &AppCxt = AppCxt::getInstance(); MemoBoard &MemoBoard = AppCxt.MemoBoard; MemoBoard.Clear(); EXPECT_EQ(true, 0 == RunCheckFormStream(MemoBoard, SourceCode)); } } // clang-format on
49.555556
85
0.270404
[ "vector" ]
62b81e9dfbfece5f8aaa3dfb64a284cf9d061457
1,862
cpp
C++
src/platform/qt/NativePlatform.cpp
Tencent/libpag
aec151f3fa8d651a6671fc4a47af5edaec00d694
[ "BSL-1.0", "CC0-1.0", "MIT" ]
1,546
2022-01-14T02:09:47.000Z
2022-03-31T10:38:42.000Z
src/platform/qt/NativePlatform.cpp
Tencent/libpag
aec151f3fa8d651a6671fc4a47af5edaec00d694
[ "BSL-1.0", "CC0-1.0", "MIT" ]
86
2022-01-14T04:50:28.000Z
2022-03-31T01:54:31.000Z
src/platform/qt/NativePlatform.cpp
Tencent/libpag
aec151f3fa8d651a6671fc4a47af5edaec00d694
[ "BSL-1.0", "CC0-1.0", "MIT" ]
207
2022-01-14T02:09:52.000Z
2022-03-31T08:34:49.000Z
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 "NativePlatform.h" #include <vector> #include "pag/pag.h" namespace pag { const Platform* Platform::Current() { static const NativePlatform platform = {}; return &platform; } bool NativePlatform::registerFallbackFonts() const { std::vector<std::string> fallbackList; #ifdef WIN32 fallbackList = {"Microsoft YaHei", "Times New Roman", "Microsoft Sans Serif", "Microsoft JhengHei", "Leelawadee UI", "MS Gothic", "Malgun Gothic", "STSong"}; #else fallbackList = {"PingFang SC", "Apple SD Gothic Neo", "Apple Color Emoji", "Helvetica", "Myanmar Sangam MN", "Thonburi", "Mishafi", "Menlo", "Kailasa", "Kefa", "Kohinoor Telugu", "Hiragino Maru Gothic ProN"}; #endif PAGFont::SetFallbackFontNames(fallbackList); return true; } } // namespace pag
39.617021
97
0.585929
[ "vector" ]
62bc3e0209811cff0b05f84b016b18d1b5cf0a10
12,550
cpp
C++
Ex1/Shape.cpp
MaximV88/Battleship
dbd389814943ae1fb7276623987c773405c971be
[ "MIT" ]
null
null
null
Ex1/Shape.cpp
MaximV88/Battleship
dbd389814943ae1fb7276623987c773405c971be
[ "MIT" ]
null
null
null
Ex1/Shape.cpp
MaximV88/Battleship
dbd389814943ae1fb7276623987c773405c971be
[ "MIT" ]
null
null
null
/************************************************************ * Student Name: Maxim Vainshtein * * Exercise Name: Ex1 * * File description: Implementation of Shape Class * ***********************************************************/ #include "Shape.h" // --- PRIVATE FUNCTIONS --- // /********************************************************************************************** * function name: copyVertices * * The Input: const Shape object (reference) * * The output: none * * The Function Opertion: Iterates through the vertices contained in the input object, and * * copies them into the current object's collection (vector). * * *******************************************************************************************/ void Shape::copyVertices(const Shape &cShape) { for (std::vector<Vertex*>::const_iterator iter = cShape.internals().begin() ; iter != cShape.internals().end() ; iter++) { //Add a copy of the vertex to the collection collect(new Vertex(**iter)); } } // --- PROTECTED FUNCTIONS --- // /********************************************************************************************** * function name: getVertex * * The Input: const Coordinate object (reference) * * The output: Vertex object (pointer) * * The Function Opertion: Iterates through the vertices contained in the current object, and * * checks every one if its equal a given coordiante that is * * has been recieved in the input. Returns the Vertex if * * found, Null otherwise. * * *******************************************************************************************/ Vertex* Shape::getVertex(const Coordinate &cCoordinate) { //Go through all of the vertices contained for (std::vector<Vertex*>::iterator iter = mutables().begin() ; iter != mutables().end() ; iter++) { //And return the one that overlaps the coordinate if (**iter == cCoordinate) return (*iter); } //Otherwise dont return anything return NULL; } /********************************************************************************************** * function name: getVertex * * The Input: const Coordinate object (reference) * * The output: const Vertex object (pointer) * * The Function Opertion: Iterates through the vertices contained in the current object, and * * checks every one if its equal a given coordiante that is * * has been recieved in the input. Returns the Vertex if * * found, Null otherwise. * * *******************************************************************************************/ const Vertex* Shape::getVertex(const Coordinate &cCoordinate) const { //Go through all of the vertices contained for (std::vector<Vertex*>::const_iterator iter = internals().begin() ; iter != internals().end() ; iter++) { //And return the one that overlaps the coordinate if (**iter == cCoordinate) return (*iter); } //Otherwise dont return anything return NULL; } // --- PUBLIC FUNCTIONS --- // /************************************************************************************************ * function name: Shape Constructor * * The Input: int, int * * The output: none * * The Function Opertion: Initializes the object. * * *********************************************************************************************/ Shape::Shape() { } /************************************************************************************************ * function name: Shape Copy Constructor * * The Input: const Shape object (reference) * * The output: none * * The Function Opertion: Copies all of the input's vertices. * * *********************************************************************************************/ Shape::Shape(const Shape& cShape) { //Copy all of the vertices contained in the shape copyVertices(cShape); } /********************************************************************************************** * function name: Shape Destructor * * The Input: none * * The output: none * * The Function Opertion: Destroys the current object. * * *******************************************************************************************/ Shape::~Shape() { } /********************************************************************************************** * function name: operator= * * The Input: const Shape object (reference) * * The output: Shape object (reference) * * The Function Opertion: Checks if the current object is the input by comparing address of * * pointer. If so then returns the object to avoid redundant work. * * Otherwise cleans the current object's Vertex vector (collection), * * and copies the vertices from the input object. * * *******************************************************************************************/ Shape& Shape::operator=(const Shape &cShape) { //We check to avoid redundant work if (this != &cShape) { //Copy the contents of the shape Collection<Vertex>::operator=(cShape); //Remove all of the vertices stored clearCollection(); //Copy all of the vertices from the input copyVertices(cShape); } return *this; } /************************************************************************************ * function name: setRepresentation * * The Input: char * * The output: none * * The Function Opertion: Iterates through all of the contained vertices in the * * shape and for every one it sets the representation to that* * of the input. * * *********************************************************************************/ void Shape::setRepresentation(char chRepresentation) { //Go through every vertex in the shape for (std::vector<Vertex*>::iterator iter = mutables().begin() ; iter != mutables().end() ; iter++) { //And change it's representation to chRepresentation (*iter)->setRepresentation(chRepresentation); } } /************************************************************************************ * function name: getRepresentation * * The Input: const Coordinate object (reference) * * The output: char * * The Function Opertion: Gets the vertex from the specified input Coordiante * * and checks if exists. If yes then it returns it's char * * representation. Otherwise returns '\0'. * * *********************************************************************************/ char Shape::getRepresentation(const Coordinate &cCoordinate) { //Get the vertex from the collection Vertex* cVertex = getVertex(cCoordinate); if (cVertex != NULL) return char(cVertex->getRepresentation()); //Otherwise return '\0'; } /************************************************************************************ * function name: setRepresentation * * The Input: const Coordinate object (reference), char * * The output: none * * The Function Opertion: Gets the specified Vertex from the input Coordiante * * and if it exists it sets it representation to input char. * * *********************************************************************************/ void Shape::setRepresentation(const Coordinate &cCoordinate, char chRepresentation) { //Get the vertex from the collection Vertex* cPulledVert = getVertex(cCoordinate); if (cPulledVert) cPulledVert->setRepresentation(chRepresentation); } /********************************************************************************************** * function name: isOverlap * * The Input: const Shape object (reference), const Coordinate object (reference) * * The output: bool * * The Function Opertion: Iterates through all of the vertices in the input object. * * It checks everyone for overlapping with an input coordinate * * adjustment (the summation) who represent the position of the input * * shape. Returns true if found an overlap, false otherwise. * * *******************************************************************************************/ bool Shape::isOverlap(const Shape& cShape, const Coordinate& cCoordinate) const { //Check if any of the vertices in the given shape have the same values as ours for (std::vector<Vertex*>::const_iterator iter = cShape.internals().begin() ; iter != cShape.internals().end() ; iter++) { //Check to see if the current vertex overlaps if (isOverlap(**iter + cCoordinate)) return true; } return false; } /********************************************************************************************** * function name: isOverlap * * The Input: const Coordinate object (reference) * * The output: bool * * The Function Opertion: If it can get a vertex from the input Coordinate, and that vertex * * exists it returns true, false otherwise. * * *******************************************************************************************/ bool Shape::isOverlap(const Coordinate& cCoordinate) const { //Use the comparison that is given from the Coordinate class if (getVertex(cCoordinate) != NULL) return true; return false; }
49.215686
130
0.367251
[ "object", "shape", "vector" ]
4985e2e26940f5a2f4d165b730750369b5e0b380
1,409
cpp
C++
android-31/android/app/AuthenticationRequiredException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/app/AuthenticationRequiredException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/app/AuthenticationRequiredException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./PendingIntent.hpp" #include "../os/Parcel.hpp" #include "../../JThrowable.hpp" #include "./AuthenticationRequiredException.hpp" namespace android::app { // Fields JObject AuthenticationRequiredException::CREATOR() { return getStaticObjectField( "android.app.AuthenticationRequiredException", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } // QJniObject forward AuthenticationRequiredException::AuthenticationRequiredException(QJniObject obj) : java::lang::SecurityException(obj) {} // Constructors AuthenticationRequiredException::AuthenticationRequiredException(JThrowable arg0, android::app::PendingIntent arg1) : java::lang::SecurityException( "android.app.AuthenticationRequiredException", "(Ljava/lang/Throwable;Landroid/app/PendingIntent;)V", arg0.object<jthrowable>(), arg1.object() ) {} // Methods jint AuthenticationRequiredException::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } android::app::PendingIntent AuthenticationRequiredException::getUserAction() const { return callObjectMethod( "getUserAction", "()Landroid/app/PendingIntent;" ); } void AuthenticationRequiredException::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::app
25.160714
121
0.735273
[ "object" ]
498660c882c1b69319e5768d8fde2c94ce3acba9
4,140
cpp
C++
src/onnx/verify_onnx.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
src/onnx/verify_onnx.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
src/onnx/verify_onnx.cpp
aaronenyeshi/AMDMIGraphX
87528938188f0247f3dfcc6ab9b83c22187109fd
[ "MIT" ]
null
null
null
#include <migraphx/onnx.hpp> #include <migraphx/cpu/target.hpp> #include <migraphx/gpu/target.hpp> #include <migraphx/gpu/hip.hpp> #include <migraphx/generate.hpp> #include <migraphx/verify_args.hpp> #include <migraphx/instruction.hpp> template <class T> auto get_hash(const T& x) { return std::hash<T>{}(x); } template <class F> migraphx::argument run_cpu(F f) { auto p = f(); p.compile(migraphx::cpu::target{}); migraphx::program::parameter_map m; for(auto&& x : p.get_parameter_shapes()) { m[x.first] = migraphx::generate_argument(x.second, get_hash(x.first)); } auto out = p.eval(m); std::cout << p << std::endl; return out; } template <class F> migraphx::argument run_gpu(F f) { auto p = f(); p.compile(migraphx::gpu::target{}); migraphx::program::parameter_map m; for(auto&& x : p.get_parameter_shapes()) { m[x.first] = migraphx::gpu::to_gpu(migraphx::generate_argument(x.second, get_hash(x.first))); } auto out = migraphx::gpu::from_gpu(p.eval(m)); std::cout << p << std::endl; return migraphx::gpu::from_gpu(out); } template <class F> void verify_program(const std::string& name, F f, double tolerance = 100) { auto x = run_cpu(f); auto y = run_gpu(f); migraphx::verify_args(name, x, y, tolerance); // std::cout << "cpu: " << x << std::endl; // std::cout << "gpu: " << y << std::endl; } void verify_instructions(const migraphx::program& prog, double tolerance = 80) { for(auto&& ins : prog) { if(ins.name().front() == '@') continue; if(ins.name() == "broadcast") continue; if(ins.name() == "transpose") continue; if(ins.name() == "reshape") continue; auto create_program = [&] { migraphx::program p; std::vector<migraphx::instruction_ref> inputs; for(auto&& arg : ins.inputs()) { if(arg->name() == "@literal") inputs.push_back(p.add_literal(arg->get_literal())); else inputs.push_back( p.add_parameter(std::to_string(inputs.size()), arg->get_shape())); } p.add_instruction(ins.get_operator(), inputs); return p; }; try { std::cout << "Verify: " << ins.name() << std::endl; std::cout << create_program() << std::endl; verify_program(ins.name(), create_program, tolerance); } catch(...) { std::cout << "Instruction " << ins.name() << " threw an exception." << std::endl; throw; } } } template <class F> void verify_reduced(F f, int n, double tolerance = 80) { auto create_program = [&] { migraphx::program p = f(); auto last = std::prev(p.end(), n + 1); p.remove_instructions(last, p.end()); return p; }; std::cout << "Verify: " << std::endl; std::cout << create_program() << std::endl; verify_program(std::to_string(n), create_program, tolerance); } template <class F> void verify_reduced_program(F f, double tolerance = 80) { migraphx::program p = f(); auto n = std::distance(p.begin(), p.end()); for(std::size_t i = 0; i < n; i++) { verify_reduced(f, i, tolerance); } } int main(int argc, char const* argv[]) { std::vector<std::string> args(argv + 1, argv + argc); if(not args.empty()) { std::string file = args.front(); auto p = migraphx::parse_onnx(file); std::cout << p << std::endl; if(std::any_of(args.begin(), args.end(), [](const auto& s) { return s == "-i"; })) { verify_instructions(p); } else if(std::any_of(args.begin(), args.end(), [](const auto& s) { return s == "-r"; })) { verify_reduced_program([&] { return migraphx::parse_onnx(file); }); } else { verify_program(file, [&] { return migraphx::parse_onnx(file); }); } } }
27.972973
95
0.537681
[ "vector" ]
498d1aad6ce5bdb46efbb8f6df51826ab118ee97
1,049
cpp
C++
tools/vcflib/src/dumpContigsFromHeader.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
1
2019-09-04T08:07:46.000Z
2019-09-04T08:07:46.000Z
tools/vcflib/src/dumpContigsFromHeader.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
2
2018-10-08T23:44:16.000Z
2019-05-10T08:04:09.000Z
tools/vcflib/src/dumpContigsFromHeader.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
3
2017-12-19T09:10:28.000Z
2018-10-08T17:07:44.000Z
#include "Variant.h" #include "split.h" #include "var.hpp" #include <string> #include <iostream> #include <stdlib.h> #include <stdio.h> #include <getopt.h> using namespace vcflib; int main(int argc, char** argv) { string filename = argv[1]; VariantCallFile variantFile; variantFile.open(filename); vector<string> headerLines = split (variantFile.header, "\n"); for(vector<string>::iterator it = headerLines.begin(); it != headerLines.end(); it++){ // cerr << "h:" << (*it) << endl; if((*it).substr(0,8) == "##contig"){ string contigInfo = (*it).substr(10, (*it).length() -11); // cerr << contigInfo << endl; vector<string> info = split(contigInfo, ","); for(vector<string>::iterator sub = info.begin(); sub != info.end(); sub++){ // cerr << "s:" << (*sub) << endl; vector<string> subfield = split((*sub), "="); if(subfield[0] == "ID"){ cout << subfield[1] << "\t"; } if(subfield[0] == "length"){ cout << subfield[1] << endl; } } } } }
21.854167
88
0.560534
[ "vector" ]
498d32fec4b9c3cb8fff4010335cb40bf36189d3
932
cpp
C++
CPP_Classes/Plot_OpenCV.cpp
bobdavies2000/OpenCVB
1d339a94643a97e2d34f82dc7776677a8566d71d
[ "MIT" ]
69
2019-07-17T21:20:37.000Z
2022-03-23T08:38:03.000Z
CPP_Classes/Plot_OpenCV.cpp
bobdavies2000/OpenCVB
1d339a94643a97e2d34f82dc7776677a8566d71d
[ "MIT" ]
5
2021-02-05T05:48:50.000Z
2022-03-12T01:43:15.000Z
CPP_Classes/Plot_OpenCV.cpp
bobdavies2000/OpenCVB
1d339a94643a97e2d34f82dc7776677a8566d71d
[ "MIT" ]
6
2019-12-24T05:36:52.000Z
2021-02-19T15:55:13.000Z
#include <cstdlib> #include <cstdio> #include <iostream> #include <algorithm> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/plot.hpp> using namespace std; using namespace cv; // https://github.com/opencv/opencv_contrib/blob/master/modules/plot/samples/plot_demo.cpp extern "C" __declspec(dllexport) void Plot_OpenCVBasics(double *inX, double *inY, int len, int* dstptr, int rows, int cols) { Mat srcX = Mat(1, len, CV_64F, inX); Mat srcY = Mat(1, len, CV_64F, inY); Mat output = Mat(rows, cols, CV_8UC3, dstptr); Mat result; Ptr<plot::Plot2d> plot = plot::Plot2d::create(srcX, srcY); plot->setInvertOrientation(true); plot->setShowText(true); plot->setShowGrid(false); plot->setPlotBackgroundColor(Scalar(255, 200, 200)); plot->setPlotLineColor(Scalar(255, 0, 0)); plot->setPlotLineWidth(2); plot->render(result); resize(result, output, output.size()); }
30.064516
90
0.73176
[ "render" ]
49948f5900e981cbc95ecb215cec020dd3467ba3
717
cpp
C++
plugins/community/repos/Valley/src/DynamicLight.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/Valley/src/DynamicLight.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/Valley/src/DynamicLight.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "ValleyWidgets.hpp" void DynamicModuleLightWidget::step() { if(visibility != nullptr) { if(*visibility) { visible = true; } else { visible = false; } if(viewMode == ACTIVE_LOW_VIEW) { visible = !visible; } } else { visible = true; } assert(module); assert(module->lights.size() >= firstLightId + baseColors.size()); std::vector<float> values(baseColors.size()); for (size_t i = 0; i < baseColors.size(); i++) { float value = module->lights[firstLightId + i].getBrightness(); value = clamp(value, 0.0, 1.0); values[i] = value; } setValues(values); }
23.9
71
0.532775
[ "vector" ]
4994da8ebbcfbd44d76745bcf531bdce617f0ba3
2,694
cpp
C++
src/operations.cpp
itsMaru/nfsu2-magazine-worker
871cf0ca007d541a5d424a009210f7e69e058821
[ "WTFPL" ]
1
2020-08-12T15:49:08.000Z
2020-08-12T15:49:08.000Z
src/operations.cpp
itsMaru/nfsu2-magazine-worker
871cf0ca007d541a5d424a009210f7e69e058821
[ "WTFPL" ]
null
null
null
src/operations.cpp
itsMaru/nfsu2-magazine-worker
871cf0ca007d541a5d424a009210f7e69e058821
[ "WTFPL" ]
null
null
null
#include <vector> #include <cstdint> #include <iostream> #include <algorithm> #include "../libs/lodepng/lodepng.h" #include "operations.h" #include "magazine.h" static constexpr auto MAGAZINE_EXPORT_NAME = "magazine"; std::uint32_t Operations::exportMagazineToPNG( const std::vector< std::string >& pathList, bool preserveAlpha ) { static const size_t magazineCount = pathList.size(); std::vector< std::uint8_t > magazine; std::vector< std::uint8_t > pngOutput; for( std::uint32_t i = 0; i < magazineCount; i++ ) { std::cout << "Exporting " + std::string( pathList[i] ) << std::endl; auto error = lodepng::load_file( magazine, pathList[i] ); if( error != 0 ) { std::cout << "Failed to load file. (" + std::to_string( error ) + ")" << std::endl; return error; } transformRawImage( magazine, true, preserveAlpha ); error = lodepng::encode( pngOutput, magazine, MAGAZINE_WIDTH, MAGAZINE_HEIGHT ); if( error != 0 ) { std::cout << "Failed to encode image. (" + std::to_string( error ) + ")" << std::endl; return error; } error = lodepng::save_file( pngOutput, std::string( MAGAZINE_EXPORT_NAME + std::to_string( i ) ) + ".png" ); if( error != 0 ) { std::cout << "Failed to save image. (" + std::to_string( error ) + ")" << std::endl; return error; } } return 0; } std::uint32_t Operations::importPNGIntoMagazine( const std::vector< std::string >& pathList ) { std::vector< std::uint8_t > png; std::vector< std::uint8_t > image; std::vector< std::uint8_t > magazine; std::uint32_t width, height; std::cout << "Importing PNG " + std::string( pathList[0] ) + " into magazine " + std::string( pathList[1] ) << std::endl; auto error = lodepng::load_file( png, pathList[0] ); if( error != 0 ) { std::cout << "Failed to load file. (" + std::to_string( error ) + ")" << std::endl; return 0; } error = lodepng::decode( image, width, height, png ); if( error ) std::cout << "decoder error " << error << ": " << lodepng_error_text( error ) << std::endl; if( width != 512 || height != 512 ) std::cout << "Warning - PNG image does not match magazine size (512x512)" << std::endl; transformRawImage( image, false, false ); error = lodepng::load_file( magazine, pathList[1] ); if( error != 0 ) { std::cout << "Failed to load file. (" + std::to_string( error ) + ")" << std::endl; return 0; } std::fill( magazine.begin() + 0x24, magazine.end(), 0 ); std::copy( image.begin(), image.end(), magazine.begin() + 0x24 ); error = lodepng::save_file( magazine, pathList[1] ); if( error != 0 ) { std::cout << "Failed to save image. (" + std::to_string( error ) + ")" << std::endl; return 0; } return 0; }
26.94
122
0.62732
[ "vector" ]
49950bb083765a0f810e9525b39c264c088e690b
1,236
hpp
C++
algorithms/p406/406.hpp
baishuai/leetcode_go
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
9
2017-06-05T15:10:35.000Z
2021-06-08T03:10:46.000Z
algorithms/p406/406.hpp
baishuai/leetcode
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
3
2017-07-12T14:08:39.000Z
2017-10-11T03:08:15.000Z
algorithms/p406/406.hpp
baishuai/leetcode_go
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
1
2017-07-21T03:51:51.000Z
2017-07-21T03:51:51.000Z
// // Created by bai on 17-6-30. // #ifndef LEETCODE_406_HPP #define LEETCODE_406_HPP #include <iostream> #include <queue> #include <algorithm> #include <vector> #include <unordered_map> #include <unordered_set> #include <numeric> using namespace std; /** Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] */ class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>> &people) { sort(people.begin(), people.end(), [](const pair<int, int> &lhs, const pair<int, int> &rhs) -> bool { return lhs.first > rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }); vector<pair<int, int >> res; for (auto &p:people) { res.insert(res.begin() + p.second, p); } return res; } }; #endif //LEETCODE_406_HPP
22.888889
109
0.630259
[ "vector" ]
4996fd6a27a09248e5e5af9699bb8c326fc34368
2,914
cpp
C++
Core/Source/fbxSettings.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
17
2018-03-29T15:24:40.000Z
2022-01-10T05:01:09.000Z
Core/Source/fbxSettings.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
null
null
null
Core/Source/fbxSettings.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
3
2018-04-07T06:02:05.000Z
2019-01-21T00:37:18.000Z
// Copyright 2018 E*D Films. All Rights Reserved. /** * fbxSettings.cpp * * A collection of user settings and enumerations * * @author dotBunny <hello@dotbunny.com> * @version 1 * @since 1.0.0 */ #include "fbxSettings.h" namespace SceneTrackFbx { const char* sFbxFileVersionStr[] = { "FBX_53_MB55", "FBX_60_MB60", "FBX_200508_MB70", "FBX_200602_MB75", "FBX_200608", "FBX_200611", "FBX_200900", "FBX_200900v7", "FBX_201000", "FBX_201100", "FBX_201200", "FBX_201300", "FBX_201400", "FBX_201600" }; const char* sAxisOrderStr[] = { "XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX" }; const char* sFbxFrameRateStr[] = { "Default", "Custom", "23.976 FPS", "24 FPS", "30 FPS", "30 FPS", "48 FPS", "50 FPS", "59.94 FPS", "60 FPS", "72 FPS", "96 FPS", "100 FPS", "120 FPS", "1000 FPS", "PAL", "NTSC", "NTSC (Drop)" }; namespace Settings { FbxFileVersion sFbxFileVersion = FbxFileVersion::LATEST; ReferenceFrame sReferenceFrame = ReferenceFrame::Local; std::set<std::string> sAssetSearchPaths; FbxFrameRate sFbxFrameRate = FbxFrameRate::Default; f64 sFbxFrameRateCustomValue = 0.0; namespace Trs { ::SceneTrackFbx::Trs::TrsSystem sTransform = ::SceneTrackFbx::Trs::TrsSystem(); ::SceneTrackFbx::Trs::TrsSystem sMesh = ::SceneTrackFbx::Trs::TrsSystem(); AxisOrder sRotationAxisOrder; } TriangleWindingOrder sTriangleWinding = TriangleWindingOrder::AsIs; void PrintSettings() { STFBX_PRINT_INFOF("Settings.FileFormat = %s", sFbxFileVersionStr[(size_t) sFbxFileVersion]); STFBX_PRINT_INFOF("Settings.ReferenceFrame = %s", sReferenceFrame == ReferenceFrame::Local ? "Local" : "World"); if (sFbxFrameRate == FbxFrameRate::Custom) { STFBX_PRINT_INFOF("Settings.FrameRate = %f (Custom)", sFbxFrameRateCustomValue); } else { STFBX_PRINT_INFOF("Settings.FrameRate = %s", sFbxFrameRateStr[(size_t) sFbxFrameRate]); } switch(sTriangleWinding) { case TriangleWindingOrder::AsIs: STFBX_PRINT_INFO("Settings.ReverseTriangleWinding = AsIs"); break; case TriangleWindingOrder::Reverse: STFBX_PRINT_INFO("Settings.ReverseTriangleWinding = Reverse"); break; case TriangleWindingOrder::Both: STFBX_PRINT_INFO("Settings.ReverseTriangleWinding = Both"); break; } Settings::Trs::sTransform.Print(Node::Transform); Settings::Trs::sMesh.Print(Node::Mesh); u32 idx = 0; STFBX_UNUSED(idx); for(auto path : Settings::sAssetSearchPaths) { STFBX_PRINT_INFOF("Settings.AssetSearchPath[%i] = %s", idx++, path.c_str()); } } } }
25.12069
118
0.605353
[ "mesh", "transform" ]
499c0c636128b6e70e8585f1b3cfd25aede6c421
733
cpp
C++
main.cpp
tzhenghao/KnightBoard
d11e70119e62f2bd37ea2c8847f41e991c381ac8
[ "MIT" ]
null
null
null
main.cpp
tzhenghao/KnightBoard
d11e70119e62f2bd37ea2c8847f41e991c381ac8
[ "MIT" ]
null
null
null
main.cpp
tzhenghao/KnightBoard
d11e70119e62f2bd37ea2c8847f41e991c381ac8
[ "MIT" ]
null
null
null
// Zheng Hao Tan // Date: December 25, 2015 #include <iostream> #include <vector> #include "KnightEngine.h" using namespace std; // Prototypes. int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Invalid file arguments\n"; cerr << "Please run:\n"; cerr << "./knightboard <test case file>"; return -1; } Position start(0, 1); //Position stop(1, 3); //Position stop(4, 1); Position stop(2, 20); KnightEngine knightEngine(start, stop, argv[1]); // File argument. //knightEngine.task1(); int cost = knightEngine.findBestPath(start, stop); if (cost == -1) { cerr << "Path cannot be found!\n" << endl; return 1; } cout << "Total cost: " << cost << "\n"; knightEngine.printPath(); return 0; }
17.452381
67
0.623465
[ "vector" ]
49a2f0a29967865fa3690f950cd719625859bcba
7,586
cpp
C++
CaWE/MapEditor/SurfaceInfo.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/MapEditor/SurfaceInfo.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/MapEditor/SurfaceInfo.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "SurfaceInfo.hpp" #include "TextParser/TextParser.hpp" #include "Math3D/Matrix3x3.hpp" #include "Math3D/Misc.hpp" #include <ostream> SurfaceInfoT::SurfaceInfoT() : TexCoordGenMode(Custom), Rotate(0.0f), UAxis(), VAxis(), LightmapScale(16.0f) { Scale[0]=1.0f; Scale[1]=1.0f; Trans[0]=0.0f; Trans[1]=0.0f; } SurfaceInfoT::SurfaceInfoT(const Plane3fT& Plane, bool FaceAligned) : TexCoordGenMode(PlaneProj), Rotate(0.0f), UAxis(), VAxis(), LightmapScale(16.0f) { Scale[0]=1.0f; Scale[1]=1.0f; Trans[0]=0.0f; Trans[1]=0.0f; ResetUVAxes(Plane, FaceAligned); } SurfaceInfoT SurfaceInfoT::Create_cmap(TextParserT& TP) { SurfaceInfoT SI; TP.AssertAndSkipToken("("); SI.TexCoordGenMode=TexCoordGenModeT(TP.GetNextTokenAsInt()); if (SI.TexCoordGenMode==MatFit) { SI.Trans[0]=TP.GetNextTokenAsFloat(); SI.Trans[1]=TP.GetNextTokenAsFloat(); SI.Scale[0]=TP.GetNextTokenAsFloat(); SI.Scale[1]=TP.GetNextTokenAsFloat(); SI.Rotate =TP.GetNextTokenAsFloat(); } if (SI.TexCoordGenMode==PlaneProj) { SI.Trans[0]=TP.GetNextTokenAsFloat(); SI.Trans[1]=TP.GetNextTokenAsFloat(); SI.Rotate =TP.GetNextTokenAsFloat(); TP.AssertAndSkipToken("("); SI.UAxis.x=TP.GetNextTokenAsFloat(); SI.UAxis.y=TP.GetNextTokenAsFloat(); SI.UAxis.z=TP.GetNextTokenAsFloat(); TP.AssertAndSkipToken(")"); TP.AssertAndSkipToken("("); SI.VAxis.x=TP.GetNextTokenAsFloat(); SI.VAxis.y=TP.GetNextTokenAsFloat(); SI.VAxis.z=TP.GetNextTokenAsFloat(); TP.AssertAndSkipToken(")"); // Restore the scale values and renormalize the axes. const float LenU=length(SI.UAxis); const float LenV=length(SI.VAxis); SI.UAxis/=LenU; SI.VAxis/=LenV; SI.Scale[0]=1.0f/LenU; SI.Scale[1]=1.0f/LenV; } TP.AssertAndSkipToken(")"); return SI; } namespace { // rnz means "round near zero", turning a vector like (0 -4.89843e-016 8) into (0 0 8). // Even though a certain kind of rounding is implied by limiting the output precision of // floats to 6 decimal digits in the code below, it is also worthwhile to implement a // "fixed" rounding near zero. float rnz(float f) { return fabs(f) < 0.00001f ? 0.0f : f; } } void SurfaceInfoT::Save_cmap(std::ostream& OutFile) const { // Temporarily reduce the precision from 9 to 6 decimal digits. // Initially we only used this for the six SaveU and SaveV values below, see svn log -r 155 for the details // (we do math with the these numbes between loading and saving, introducing subtle rounding errors). // However, using the implied rounding of the 6 digits precision also with the other numbers (Trans, Scale // and Rotate) with their typically well-known, limited range of values seems to be a good idea as well. const std::streamsize OldPrecision=OutFile.precision(std::numeric_limits<float>::digits10); OutFile << "( " << TexCoordGenMode; if (TexCoordGenMode==MatFit) { OutFile << " " << rnz(Trans[0]) << " " << rnz(Trans[1]) << " " << rnz(Scale[0]) << " " << rnz(Scale[1]) << " " << rnz(Rotate); } else if (TexCoordGenMode==PlaneProj) { OutFile << " " << rnz(Trans[0]) << " " << rnz(Trans[1]) << " " << rnz(Rotate); // Include the scale factors into their axes. const Vector3fT SaveU = UAxis / Scale[0]; const Vector3fT SaveV = VAxis / Scale[1]; OutFile << " ( " << rnz(SaveU.x) << " " << rnz(SaveU.y) << " " << rnz(SaveU.z) << " )"; OutFile << " ( " << rnz(SaveV.x) << " " << rnz(SaveV.y) << " " << rnz(SaveV.z) << " )"; } OutFile << " )\n"; // Restore original precision mode. OutFile.precision(OldPrecision); } static unsigned int GetMainAxis(const Vector3fT& PlaneNormal) { unsigned int MainAxis=0; float MaxVal =fabs(PlaneNormal[0]); for (unsigned int AxisNr=1; AxisNr<3; AxisNr++) { if (fabs(PlaneNormal[AxisNr]) > MaxVal) { MaxVal =fabs(PlaneNormal[AxisNr]); MainAxis=AxisNr; } } return MainAxis; } void SurfaceInfoT::ResetUVAxes(const Plane3fT& Plane, bool FaceAligned) { assert(TexCoordGenMode==PlaneProj); // Always initialize the axes world-aligned first. const unsigned int MainAxis=GetMainAxis(Plane.Normal); UAxis=Vector3fT(1, 0, 0); VAxis=Vector3fT(0, 0, -1); if (MainAxis==0) UAxis=Vector3fT(0, 1, 0); if (MainAxis==2) VAxis=Vector3fT(0, -1, 0); // Now "modify" the world-aligned axes so that they become face-aligned. if (FaceAligned) { UAxis=normalizeOr0(cross(Plane.Normal, VAxis)); VAxis=normalizeOr0(cross(UAxis, Plane.Normal)); } RotateUVAxes(Rotate); } void SurfaceInfoT::WrapTranslations() { assert(TexCoordGenMode==PlaneProj); Trans[0]=fmod(Trans[0], 1.0f); Trans[1]=fmod(Trans[1], 1.0f); } void SurfaceInfoT::RotateUVAxes(float Angle) { if (TexCoordGenMode!=PlaneProj) return; if (Angle==0.0f) return; const cf::math::Matrix3x3T<float> Matrix=cf::math::Matrix3x3T<float>::GetRotateMatrix(Angle, cross(VAxis, UAxis)); UAxis=Matrix*UAxis; VAxis=Matrix*VAxis; } void SurfaceInfoT::AlignMaterial(const char* AlignKey, const ArrayT<Vector3fT>& Vertices) { assert(TexCoordGenMode==PlaneProj); TexCoordT TopLeft; TexCoordT BottomRight; // Project each vertex into the texture plane in order to determine the "texture-space bounding-box" // of the vertices (that is, the 2D bounding-box over all texture coordinates). // Note that the projection includes scale, but not translation (which is computed below) or rotation. for (unsigned long VertexNr=0; VertexNr<Vertices.Size(); VertexNr++) { TexCoordT Test; Test[0]=dot(Vertices[VertexNr], UAxis)*Scale[0]; Test[1]=dot(Vertices[VertexNr], VAxis)*Scale[1]; if (VertexNr==0) { TopLeft =Test; BottomRight=Test; } else { if (Test[0]< TopLeft[0]) TopLeft[0]=Test[0]; if (Test[1]< TopLeft[1]) TopLeft[1]=Test[1]; if (Test[0]>BottomRight[0]) BottomRight[0]=Test[0]; if (Test[1]>BottomRight[1]) BottomRight[1]=Test[1]; } } switch (AlignKey[0]) { case 't': // Top. Trans[1]=-TopLeft[1]; break; case 'b': // Bottom. Trans[1]=-BottomRight[1] + 1.0f; break; case 'l': // Left. Trans[0]=-TopLeft[0]; break; case 'r': // Right. Trans[0]=-BottomRight[0] + 1.0f; break; case 'c': // Center. Trans[0]=-(TopLeft[0]+BottomRight[0])/2.0f + 0.5f; Trans[1]=-(TopLeft[1]+BottomRight[1])/2.0f + 0.5f; break; case 'f': // Fit. { if (TopLeft[0]!=BottomRight[0]) Scale[0]/=BottomRight[0] - TopLeft[0]; if (TopLeft[1]!=BottomRight[1]) Scale[1]/=BottomRight[1] - TopLeft[1]; AlignMaterial("top", Vertices); AlignMaterial("left", Vertices); break; } } WrapTranslations(); }
27.485507
118
0.597416
[ "vector" ]
49aa67bce85c95bad0dd28fbad40e7018c462574
6,328
cc
C++
src/system/zone-render-system.cc
emptyland/nyaa
e2092a086869342b14de51c2afc1246500dbf47d
[ "BSD-2-Clause" ]
null
null
null
src/system/zone-render-system.cc
emptyland/nyaa
e2092a086869342b14de51c2afc1246500dbf47d
[ "BSD-2-Clause" ]
null
null
null
src/system/zone-render-system.cc
emptyland/nyaa
e2092a086869342b14de51c2afc1246500dbf47d
[ "BSD-2-Clause" ]
null
null
null
#include "system/zone-render-system.h" #include "system/geometry-transform-system.h" #include "component/zone-component.h" #include "resource/shader-library.h" #include "resource/texture-library.h" #include "game/game.h" #include "game/matrix.h" #include <GL/glew.h> namespace nyaa { namespace sys { const float ZoneRenderSystem::kVertices[] = { // top 0, 0, 1, /*normal*/ 0, 0, 1, /*uv*/ 0, 0, // :format 0, 1, 1, /*normal*/ 0, 0, 1, /*uv*/ 0, 0, // :format 1, 1, 1, /*normal*/ 0, 0, 1, /*uv*/ 0, 0, // :format 1, 0, 1, /*normal*/ 0, 0, 1, /*uv*/ 0, 0, // :format // bottom 0, 0, 0, /*normal*/ 0, 0, -1, /*uv*/ 0, 0, // :format 0, 1, 0, /*normal*/ 0, 0, -1, /*uv*/ 0, 0, // :format 1, 1, 0, /*normal*/ 0, 0, -1, /*uv*/ 0, 0, // :format 1, 0, 0, /*normal*/ 0, 0, -1, /*uv*/ 0, 0, // :format // :front 0, 0, 0, /*normal*/ 0, -1, 0, /*uv*/ 0, 0, // :format 0, 0, 1, /*normal*/ 0, -1, 0, /*uv*/ 0, 0, // :format 1, 0, 1, /*normal*/ 0, -1, 0, /*uv*/ 0, 0, // :format 1, 0, 0, /*normal*/ 0, -1, 0, /*uv*/ 0, 0, // :format // :back 0, 1, 0, /*normal*/ 0, 1, 0, /*uv*/ 0, 0, // :format 1, 1, 0, /*normal*/ 0, 1, 0, /*uv*/ 0, 0, // :format 1, 1, 1, /*normal*/ 0, 1, 0, /*uv*/ 0, 0, // :format 0, 1, 1, /*normal*/ 0, 1, 0, /*uv*/ 0, 0, // :format // :left 0, 0, 0, /*normal*/ -1, 0, 0, /*uv*/ 0, 0, // :format 0, 1, 0, /*normal*/ -1, 0, 0, /*uv*/ 0, 0, // :format 0, 1, 1, /*normal*/ -1, 0, 0, /*uv*/ 0, 0, // :format 0, 0, 1, /*normal*/ -1, 0, 0, /*uv*/ 0, 0, // :format // :right 1, 0, 0, /*normal*/ 1, 0, 0, /*uv*/ 0, 0, // :format 1, 0, 1, /*normal*/ 1, 0, 0, /*uv*/ 0, 0, // :format 1, 1, 1, /*normal*/ 1, 0, 0, /*uv*/ 0, 0, // :format 1, 1, 0, /*normal*/ 1, 0, 0, /*uv*/ 0, 0, // :format }; ZoneRenderSystem::ZoneRenderSystem() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { vbo_[i][j].coord = {-1, -1}; vbo_[i][j].buffer = 0; vbo_[i][j].count = 0; } } } void ZoneRenderSystem::Reset() { if (vbo_[1][1].buffer) { glDeleteBuffers(1, &vbo_[1][1].buffer); vbo_[1][1].buffer = 0; } } void ZoneRenderSystem::RenderTerrain(com::ZoneComponent *zone) { if (!vbo_[1][1].buffer) { GenBuffer(zone->mutable_region(), 1, 1); } //------------------------------------------------------------------------------------------------------------------ glFrontFace(GL_CW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); //------------------------------------------------------------------------------------------------------------------ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tile_tex_id()); res::BlockShaderProgram *shader = Game::This()->shader_lib()->block_program(); Matrix<float> mat; mat.Translate(-zone->viewport().center_coord().x, -zone->viewport().center_coord().y, 0); shader->SetModelMatrix(mat); glBindBuffer(GL_ARRAY_BUFFER, vbo_[1][1].buffer); shader->Enable(); glDrawArrays(GL_QUADS, 0, vbo_[1][1].count); shader->Disable(); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisable(GL_CULL_FACE); } void ZoneRenderSystem::GenBuffer(com::RegionComponent *region, int i, int j) { glDeleteBuffers(1, &vbo_[i][j].buffer); glGenBuffers(1, &vbo_[i][j].buffer); glBindBuffer(GL_ARRAY_BUFFER, vbo_[i][j].buffer); std::vector<GLfloat> buf; Vector3f p0{0, 0, 0}; for (int y = 0; y < kRegionSize; y++) { for (int x = 0; x < kRegionSize; x++) { p0.x = x * cube_size_; p0.y = y * cube_size_; for (int z = kTerrainSurfaceLevel; z < kTerrainMaxLevels; z++) { com::CubeComponent *cube = &region->floor(z)->cubes[x][y]; if (cube->IsTransparent()) { continue; } if (cube->IsPlant()) { continue; } res::Cube *def = DCHECK_NOTNULL(Game::This()->cube_lib()->cube(cube->kind())); p0.z = (-1 + (z - kTerrainSurfaceLevel)) * cube_size_; MakeCube(def, p0, z == kTerrainSurfaceLevel, &buf); } } } glBufferData(GL_ARRAY_BUFFER, buf.size() * sizeof(float), &buf[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); vbo_[i][j].count = buf.size() / 8; vbo_[i][j].coord = region->global_coord(); } void ZoneRenderSystem::MakeCube(const res::Cube *cube, const Vector3f &p0, bool surface, std::vector<float> *buf) { // float half_size = cube_size_ / 2; int n_vertices = surface ? 4 : 24; size_t pos = buf->size(); buf->resize(pos + n_vertices * 8); float *vertices = &(*buf)[pos]; for (int i = 0; i < n_vertices; i++) { vertices[i * 8 + 0] = p0.x + kVertices[i * 8 + 0] * cube_size_; vertices[i * 8 + 1] = p0.y + kVertices[i * 8 + 1] * cube_size_; vertices[i * 8 + 2] = p0.z + kVertices[i * 8 + 2] * cube_size_; vertices[i * 8 + 3] = kVertices[i * 8 + 3]; vertices[i * 8 + 4] = kVertices[i * 8 + 4]; vertices[i * 8 + 5] = kVertices[i * 8 + 5]; } for (int i = 0; i < 4; i++) { vertices[i * 8 + 6] = cube->top_tex()->coord(i).x; vertices[i * 8 + 7] = cube->top_tex()->coord(i).y; } if (!surface) { for (int i = 4; i < 24; i++) { vertices[i * 8 + 6] = cube->edge_tex()->coord(i % 4).x; vertices[i * 8 + 7] = cube->edge_tex()->coord(i % 4).y; } } // int n_vertices = 24; // size_t pos = buf->size(); // buf->resize(pos + n_vertices * 8); // float *vertices = &(*buf)[pos]; // for (int i = 0; i < n_vertices; i++) { // vertices[i * 8 + 0] = p0.x + kVertices[i * 8 + 0] * cube_size_; // vertices[i * 8 + 1] = p0.y + kVertices[i * 8 + 1] * cube_size_; // vertices[i * 8 + 2] = p0.z + kVertices[i * 8 + 2] * cube_size_; // vertices[i * 8 + 3] = kVertices[i * 8 + 3]; // vertices[i * 8 + 4] = kVertices[i * 8 + 4]; // vertices[i * 8 + 5] = kVertices[i * 8 + 5]; // } // for (int i = 0; i < n_vertices; i++) { // vertices[i * 8 + 6] = cube->top_tex()->coord(i % 4).x; // vertices[i * 8 + 7] = cube->top_tex()->coord(i % 4).y; // } } } // namespace sys } // namespace nyaa
36.790698
120
0.484987
[ "geometry", "render", "vector", "transform" ]
49b70ef683f703155c1409eb4150b7d694cad651
3,726
cpp
C++
game_main.cpp
TTimo/es_core
c966baaa6b3466645d0d298900752fed70e4f644
[ "BSD-3-Clause" ]
72
2015-02-03T15:30:22.000Z
2021-12-07T00:18:43.000Z
game_main.cpp
TTimo/es_core
c966baaa6b3466645d0d298900752fed70e4f644
[ "BSD-3-Clause" ]
null
null
null
game_main.cpp
TTimo/es_core
c966baaa6b3466645d0d298900752fed70e4f644
[ "BSD-3-Clause" ]
11
2015-08-08T10:48:21.000Z
2021-01-18T17:56:28.000Z
/* Copyright (c) 2013, Timothee Besset 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 Timothee Besset nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Timothee Besset 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 <stdlib.h> #include <time.h> #include <math.h> #include "SDL.h" #include "SDL_thread.h" #include "OgreVector2.h" #include "OgreVector3.h" #include "czmq.h" // includes common to all projects #include "game_main.h" // per project includes: // those headers are in each project subdirectory #include "shared_render_state.h" #include "game.h" int game_thread( void * _parms ) { GameThreadParms * parms = (GameThreadParms*)_parms; GameThreadSockets gsockets; GameState gs; SharedRenderState srs; gsockets.zmq_control_socket = zsocket_new( parms->zmq_context, ZMQ_PAIR ); { int ret = zsocket_connect( gsockets.zmq_control_socket, "inproc://control_game" ); assert( ret == 0 ); } gsockets.zmq_render_socket = zsocket_new( parms->zmq_context, ZMQ_PAIR ); zsocket_bind( gsockets.zmq_render_socket, "inproc://game_render" ); gsockets.zmq_input_req = zsocket_new( parms->zmq_context, ZMQ_REQ ); { int ret = zsocket_connect( gsockets.zmq_input_req, "inproc://input" ); assert( ret == 0 ); } game_init( gsockets, gs, srs ); unsigned int baseline = SDL_GetTicks(); unsigned int framenum = 0; while ( true ) { unsigned int now = SDL_GetTicks(); unsigned int target_frame = ( now - baseline ) / GAME_DELAY; if ( framenum <= target_frame ) { framenum++; // NOTE: build the state of the world at t = framenum * GAME_DELAY, // under normal conditions that's a time in the future // (the exception to that is if we are catching up on ticking game frames) game_tick( gsockets, gs, srs, now ); // notify the render thread that a new game state is ready. // on the next render frame, it will start interpolating between the previous state and this new one emit_render_state( gsockets.zmq_render_socket, baseline + framenum * GAME_DELAY, srs ); } else { int ahead = framenum * GAME_DELAY - ( now - baseline ); assert( ahead > 0 ); printf( "game sleep %d ms\n", ahead ); SDL_Delay( ahead ); } char * cmd = zstr_recv_nowait( gsockets.zmq_control_socket ); if ( cmd != NULL ) { assert( strcmp( cmd, "stop" ) == 0 ); free( cmd ); break; } } return 0; }
36.891089
106
0.71766
[ "render" ]
49bddacee334e8adf29a45213c6019f691e2e63c
57,206
cpp
C++
test/Mandelbulb/Mandelbulb.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
2
2020-05-31T19:54:19.000Z
2021-09-14T12:00:12.000Z
test/Mandelbulb/Mandelbulb.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
null
null
null
test/Mandelbulb/Mandelbulb.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
null
null
null
#include "MandelBulb.hpp" #include "TextureFactory.hpp" #include <CompilerSpirV/compileSpirV.hpp> #include <ShaderWriter/Intrinsics/Intrinsics.hpp> #include <ShaderWriter/Source.hpp> #include "imgui.h" #include "imgui_impl_glfw.h" #include "my_imgui_impl_vulkan.h" #include <array> #include <iostream> #include <stdexcept> constexpr size_t POINT_COUNT = 2000; #define mandelbulbTexScale 1 constexpr uint32_t width = 1280 * mandelbulbTexScale; constexpr uint32_t height = 720 * mandelbulbTexScale; constexpr float widthf = 1280.0f * mandelbulbTexScale; constexpr float heightf = 720.0f * mandelbulbTexScale; namespace cdm { static constexpr float Pi{ 3.14159265359f }; void Mandelbulb::Config::copyTo(void* ptr) { stepSize = std::min(1.0f / (volumePrecision * density), sceneRadius / 2.0f); std::memcpy(ptr, this, sizeof(*this)); } template <typename T> class MandelbulbShaderLib : public T { public: const sdw::Float Pi; const sdw::Float Height; const sdw::Float Width; sdw::Ubo ubo; sdw::Function<sdw::Float, sdw::InOutFloat> randomFloat; sdw::Function<sdw::Mat3, sdw::InVec3> rotationMatrix; sdw::Function<sdw::Float, sdw::InVec3> maxV; sdw::Function<sdw::Vec3, sdw::InOutFloat> randomDir; sdw::Function<sdw::Vec3, sdw::InVec3> backgroundColor; sdw::Function<sdw::Float, sdw::InVec3, sdw::OutVec3, sdw::OutVec3> distanceEstimation; sdw::Function<sdw::Vec3, sdw::InVec3, sdw::InOutFloat> directLight; sdw::Function<sdw::Vec3, sdw::InVec3, sdw::InVec3, sdw::InOutFloat> pathTrace; sdw::Function<sdw::Vec2, sdw::InInt, sdw::InFloat, sdw::InOutFloat> sampleAperture; MandelbulbShaderLib(Mandelbulb::Config const& config) : T(), Pi(declConstant<sdw::Float>("Pi", sdw::Float{ cdm::Pi })), Width(declConstant<sdw::Float>("Width", sdw::Float{ float(width) })), Height( declConstant<sdw::Float>("Height", sdw::Float{ float(height) })), ubo(sdw::Ubo(*this, "ubo", 1, 0)) { using namespace sdw; (void)ubo.declMember<Float>("camAperture"); (void)ubo.declMember<Float>("camFocalDistance"); (void)ubo.declMember<Float>("camFocalLength"); (void)ubo.declMember<Float>("density"); (void)ubo.declMember<Float>("maxAbso"); (void)ubo.declMember<Float>("maxShadowAbso"); (void)ubo.declMember<Float>("power"); (void)ubo.declMember<Float>("samples"); (void)ubo.declMember<Float>("sceneRadius"); (void)ubo.declMember<Float>("seed"); (void)ubo.declMember<Float>("stepSize"); (void)ubo.declMember<Float>("stepsSkipShadow"); (void)ubo.declMember<Float>("volumePrecision"); (void)ubo.declMember<Int>("maxSteps"); (void)ubo.declMember<Vec3>("camRot"); (void)ubo.declMember<Vec3>("lightColor"); (void)ubo.declMember<Vec3>("lightDir"); (void)ubo.declMember<Float>("bloomAscale1"); (void)ubo.declMember<Float>("bloomAscale2"); (void)ubo.declMember<Float>("bloomBscale1"); (void)ubo.declMember<Float>("bloomBscale2"); (void)ubo.declMember<Int>("iterations"); (void)ubo.declMember<Int>("mouseX"); (void)ubo.declMember<Int>("mouseY"); (void)ubo.declMember<Int>("mousePressed"); ubo.end(); randomFloat = implementFunction<Float>( "randomFloat", [&](Float seed) { auto res = declLocale("res", fract(sin(seed) * 43758.5453_f)); seed = seed + 1.0_f; returnStmt(res); }, InOutFloat{ *this, "seed" }); rotationMatrix = implementFunction<Mat3>( "rotationMatrix", [&](const Vec3& rotEuler) { auto c = declLocale("c", cos(rotEuler.x())); auto s = declLocale("s", sin(rotEuler.x())); auto rx = declLocale( "rx", mat3(vec3(1.0_f, 0.0_f, 0.0_f), vec3(0.0_f, c, -s), vec3(0.0_f, s, c))); rx = transpose(rx); c = cos(rotEuler.y()); s = sin(rotEuler.y()); auto ry = declLocale( "ry", mat3(vec3(c, 0.0_f, -s), vec3(0.0_f, 1.0_f, 0.0_f), vec3(s, 0.0_f, c))); ry = transpose(ry); c = cos(rotEuler.z()); s = sin(rotEuler.z()); auto rz = declLocale( "rz", mat3(vec3(c, -s, 0.0_f), vec3(s, c, 0.0_f), vec3(0.0_f, 0.0_f, 1.0_f))); rz = transpose(rz); returnStmt(rz * rx * ry); }, InVec3{ *this, "rotEuler" }); maxV = implementFunction<Float>( "maxV", [&](const Vec3& v) { returnStmt(ternary(v.x() > v.y(), ternary(v.x() > v.z(), v.x(), v.z()), ternary(v.y() > v.z(), v.y(), v.z()))); }, InVec3{ *this, "v" }); randomDir = implementFunction<Vec3>( "randomDir", [&](Float seed) { returnStmt( vec3(1.0_f, 0.0_f, 0.0_f) * rotationMatrix(vec3(randomFloat(seed) * 2.0_f * Pi, 0.0_f, randomFloat(seed) * 2.0_f * Pi))); }, InOutFloat{ *this, "seed" }); backgroundColor = implementFunction<Vec3>( "backgroundColor", [&](const Vec3&) { returnStmt(vec3(0.0_f)); }, InVec3{ *this, "unused" }); distanceEstimation = implementFunction<Float>( "distanceEstimation", [&](const Vec3& pos_arg, Vec3 volumeColor, Vec3 emissionColor) { // Vec3 pos = declLocale<Vec3>*this, ("pos_local"); auto pos = declLocale("pos", pos_arg); auto basePos = declLocale("basePos", vec3(0.0_f)); auto scale = declLocale("scale", 1.0_f); // pos = pos_arg; // Vec3 basePos = declLocale<Vec3>*this, ("basePos"); // basePos = vec3(0.0_f); // Float scale = 1.0_f; // pos /= scale; // pos += basePos; volumeColor = vec3(0.0_f); emissionColor = vec3(0.0_f); pos.yz() = vec2(pos.z(), pos.y()); auto r = declLocale("r", length(pos)); auto z = declLocale("z", pos); auto c = declLocale("c", pos); auto dr = declLocale("dr", 1.0_f); auto theta = declLocale("theta", 0.0_f); auto phi = declLocale("phi", 0.0_f); auto orbitTrap = declLocale("orbitTrap", vec3(1.0_f)); // Float r = length(pos); // Vec3 z = pos; // Vec3 c = pos; // Float dr = 1.0_f, theta = 0.0_f, phi = 0.0_f; // Vec3 orbitTrap = vec3(1.0_f); auto SceneRadius = declLocale( "SceneRadius", ubo.getMember<Float>("sceneRadius")); auto Power = declLocale("Power", ubo.getMember<Float>("power")); auto Iterations = declLocale("Iteration", ubo.getMember<Int>("iterations")); // FOR(*this, Int, i, 0_i, i < 8_i, ++i) //{ // r = length(z); // IF(*this, r > SceneRadius) { loopBreakStmt(); } // FI; // orbitTrap = min(abs(z) * 1.2_f, orbitTrap); // theta = acos(z.y() / r); // // phi = atan(z.z(), z.x()); // phi = atan2(z.z(), z.x()); // dr = pow(r, Power - 1.0_f) * Power * dr + 1.0_f; // theta *= Power; // phi *= Power; // z = pow(r, Power) * vec3(sin(theta) * cos(phi), cos(theta), // sin(phi) * sin(theta)) + // c; //} // ROF; //[{r = Sqrt[x^2 + y^2 + z^2], theta = n ArcTan[x, y], phi}, // phi = n ArcSin[z/r]; r^n{Cos[theta]Cos[phi], // Sin[theta]Cos[phi], Sin[phi]}]; // TriplexPow[{x_, y_, z_}, n_] := // Module[{ // r = Sqrt[x^2 + y^2 + z^2], // theta = n ArcTan[x, y], // phi}, // phi = n ArcSin[z/r]; // r^n { Cos[theta] Cos[phi] , Sin[theta] Cos[phi], Sin[phi] } // ]; FOR(*this, Int, i, 0_i, i < Iterations, ++i) { r = length(z); IF(*this, r > SceneRadius) { loopBreakStmt(); } FI; orbitTrap = min(abs(z) * 1.2_f, orbitTrap); theta = atan2(z.x(), z.z()); phi = asin(z.z() / r); dr = pow(r, Power - 1.0_f) * Power * dr + 1.0_f; theta *= Power; phi *= Power; z = pow(r, Power) * vec3(cos(theta) * cos(phi), sin(theta) * cos(phi), sin(phi)) + c; } ROF; auto dist = declLocale("dist", 0.5_f * log(r) * r / dr * scale); volumeColor = (1.0_f - orbitTrap) * 0.98_f; emissionColor = vec3(ternary(orbitTrap.z() < 0.0001_f, 20.0_f, 0.0_f)); returnStmt(dist); }, InVec3{ *this, "pos_arg" }, OutVec3{ *this, "volumeColor" }, OutVec3{ *this, "emissionColor" }); directLight = implementFunction<Vec3>( "directLight", [&](const Vec3& pos_arg, Float seed) { auto pos = declLocale("pos", pos_arg); auto absorption = declLocale("absorption", vec3(1.0_f)); auto volumeColor = declLocale("volumeColor", vec3(0.0_f)); auto emissionColor = declLocale("emissionColor", vec3(0.0_f)); auto dist = declLocale<Float>("dist"); auto MaxSteps = declLocale("MaxSteps", ubo.getMember<Int>("maxSteps")); auto StepSize = declLocale("StepSize", ubo.getMember<Float>("stepSize")); auto SceneRadius = declLocale( "SceneRadius", ubo.getMember<Float>("sceneRadius")); auto LightDir = declLocale("LightDir", ubo.getMember<Vec3>("lightDir")); auto LightColor = declLocale( "LightColor", ubo.getMember<Vec3>("lightColor")); auto MaxShadowAbso = declLocale( "MaxShadowAbso", ubo.getMember<Float>("maxShadowAbso")); auto Density = declLocale("Density", ubo.getMember<Float>("density")); LightDir = normalize(LightDir); FOR(*this, Int, i, 0_i, i < MaxSteps, ++i) { // auto dist = declLocale( //"dist", dist = distanceEstimation(pos, volumeColor, emissionColor); pos -= LightDir * max(dist, StepSize); IF(*this, dist < StepSize) { auto abStep = declLocale("abStep", StepSize * randomFloat(seed)); pos -= LightDir * (abStep - StepSize); IF(*this, dist < 0.0_f) { auto absorbance = declLocale( "absorbance", exp(-Density * abStep)); absorption *= absorbance; IF(*this, maxV(absorption) < 1.0_f - MaxShadowAbso) { loopBreakStmt(); } FI; } FI; } FI; IF(*this, length(pos) > SceneRadius) { loopBreakStmt(); } FI; } ROF; returnStmt( LightColor * max((absorption + MaxShadowAbso - 1.0_f) / MaxShadowAbso, vec3(0.0_f))); }, InVec3{ *this, "pos_arg" }, InOutFloat{ *this, "seed" }); pathTrace = implementFunction<Vec3>( "pathTrace", [&](const Vec3& rayPos_arg, const Vec3& rayDir_arg, Float seed) { auto rayPos = declLocale("rayPos", rayPos_arg); auto rayDir = declLocale("rayDir", rayDir_arg); auto MaxSteps = declLocale("MaxSteps", ubo.getMember<Int>("maxSteps")); auto StepsSkipShadow = declLocale( "StepsSkipShadow", ubo.getMember<Int>("stepsSkipShadow")); auto StepSize = declLocale("StepSize", ubo.getMember<Float>("stepSize")); auto SceneRadius = declLocale( "SceneRadius", ubo.getMember<Float>("sceneRadius")); auto Density = declLocale("Density", ubo.getMember<Float>("density")); auto MaxAbso = declLocale("MaxAbso", ubo.getMember<Float>("maxAbso")); rayPos += rayDir * max(length(rayPos) - SceneRadius, 0.0_f); auto outColor = declLocale("outColor", vec3(0.0_f)); auto absorption = declLocale("absorption", vec3(1.0_f)); auto volumeColor = declLocale("volumeColor", vec3(0.0_f)); auto emissionColor = declLocale("emissionColor", vec3(0.0_f)); auto dist = declLocale<Float>("dist"); FOR(*this, Int, i, 0_i, i < MaxSteps, ++i) { // auto dist = declLocale( "dist", dist = distanceEstimation(rayPos, volumeColor, emissionColor); rayPos += rayDir * max(dist, StepSize); IF(*this, dist < StepSize && length(rayPos) < SceneRadius) { auto abStep = declLocale("abStep", StepSize * randomFloat(seed)); rayPos += rayDir * (abStep - StepSize); IF(*this, dist < 0.0_f) { auto absorbance = declLocale( "absorbance", exp(-Density * abStep)); auto transmittance = declLocale( "transmittance", 1.0_f - absorbance); // surface glow for a nice additional effect // if(dist > -.0001) outColor += absorption * // vec3(.2, .2, .2); // if(randomFloat() < ShadowRaysPerStep) // emissionColor // += 1.0/ShadowRaysPerStep * volumeColor * // directLight(rayPos); auto i_f = declLocale("i_f", cast<Float>(i)); IF(*this, mod(i_f, Float(StepsSkipShadow)) == 0.0_f) { emissionColor += Float(StepsSkipShadow) * volumeColor * directLight(rayPos, seed); } FI; outColor += absorption * transmittance * emissionColor; IF(*this, maxV(absorption) < 1.0_f - MaxAbso) { loopBreakStmt(); } FI; IF(*this, randomFloat(seed) > absorbance) { rayDir = randomDir(seed); absorption *= volumeColor; } FI; } FI; } FI; IF(*this, length(rayPos) > SceneRadius && dot(rayDir, rayPos) > 0.0_f) { returnStmt(outColor + backgroundColor(rayDir) * absorption); } FI; } ROF; returnStmt(outColor); }, InVec3{ *this, "rayPos_arg" }, InVec3{ *this, "rayDir_arg" }, InOutFloat{ *this, "seed" }); // n-blade aperture sampleAperture = implementFunction<Vec2>( "sampleAperture", [&](const Int& nbBlades, const Float& rotation, Float seed) { auto alpha = declLocale("alpha", 2.0_f * Pi / cast<Float>(nbBlades)); auto side = declLocale("side", sin(alpha / 2.0_f)); auto blade = declLocale( "blade", cast<Int>(randomFloat(seed) * cast<Float>(nbBlades))); auto tri = declLocale( "tri", vec2(randomFloat(seed), -randomFloat(seed))); IF(*this, tri.x() + tri.y() > 0.0_f) { tri = vec2(tri.x() - 1.0_f, -1.0_f - tri.y()); } FI; tri.x() *= side; tri.y() *= sqrt(1.0_f - side * side); auto angle = declLocale("angle", rotation + cast<Float>(blade) / cast<Float>(nbBlades) * 2.0_f * Pi); returnStmt(vec2(tri.x() * cos(angle) + tri.y() * sin(angle), tri.y() * cos(angle) - tri.x() * sin(angle))); }, InInt{ *this, "nbBlades" }, InFloat{ *this, "rotation" }, InOutFloat{ *this, "seed" }); } }; Mandelbulb::Mandelbulb(RenderWindow& rw) : RenderApplication(rw), log(vk), gen(rd()), dis(0.0f, 0.3f), computeCB(CommandBuffer(vk, renderWindow.oneTimeCommandPool())), imguiCB(CommandBuffer(vk, renderWindow.oneTimeCommandPool())), copyHDRCB(CommandBuffer(vk, renderWindow.oneTimeCommandPool())), cb(CommandBuffer(vk, renderWindow.oneTimeCommandPool())) { LogRRID log(vk); #pragma region renderPass VkAttachmentDescription colorAttachment = {}; colorAttachment.format = VkFormat::VK_FORMAT_R8G8B8A8_UNORM; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VkAttachmentDescription colorHDRAttachment = {}; // colorHDRAttachment.format = VkFormat::VK_FORMAT_R32G32B32A32_SFLOAT; // colorHDRAttachment.samples = VK_SAMPLE_COUNT_1_BIT; // colorHDRAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // colorHDRAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // colorHDRAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // colorHDRAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // colorHDRAttachment.initialLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; // colorHDRAttachment.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; // std::array colorAttachments{ colorAttachment, colorHDRAttachment }; std::array colorAttachments{ colorAttachment }; VkAttachmentReference colorAttachmentRef = {}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VkAttachmentReference colorHDRAttachmentRef = {}; // colorHDRAttachmentRef.attachment = 1; // colorHDRAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; std::array colorAttachmentRefs{ colorAttachmentRef //, colorHDRAttachmentRef }; VkSubpassDescription subpass = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = uint32_t(colorAttachmentRefs.size()); subpass.pColorAttachments = colorAttachmentRefs.data(); subpass.inputAttachmentCount = 0; subpass.pInputAttachments = nullptr; subpass.pResolveAttachments = nullptr; subpass.pDepthStencilAttachment = nullptr; subpass.preserveAttachmentCount = 0; subpass.pPreserveAttachments = nullptr; VkSubpassDependency dependency = {}; dependency.dependencyFlags = 0; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; vk::RenderPassCreateInfo renderPassInfo; renderPassInfo.attachmentCount = uint32_t(colorAttachments.size()); renderPassInfo.pAttachments = colorAttachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; m_renderPass = vk.create(renderPassInfo); if (!m_renderPass) { std::cerr << "error: failed to create render pass" << std::endl; abort(); } #pragma endregion #pragma region vertexShader { using namespace sdw; VertexWriter writer; auto inPosition = writer.declInput<Vec2>("inPosition", 0); auto fragColor = writer.declOutput<Vec4>("fragColor", 0u); auto out = writer.getOut(); writer.implementMain([&]() { out.vtx.position = vec4(inPosition, 0.0_f, 1.0_f); fragColor = vec4(inPosition / 2.0_f + 0.5_f, 0.0_f, 1.0_f); }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); m_vertexModule = vk.create(createInfo); if (!m_vertexModule) { std::cerr << "error: failed to create vertex shader module" << std::endl; abort(); } } #pragma endregion #pragma region fragmentShader { using namespace sdw; MandelbulbShaderLib<FragmentWriter> writer{ m_config }; auto in = writer.getIn(); auto inPosition = writer.declInput<Vec4>("inPosition", 0u); auto fragColor = writer.declOutput<Vec4>("fragColor", 0u); // auto fragColorHDR = writer.declOutput<Vec4>("fragColorHDR", 1u); auto kernelStorageImage = writer.declImage<RWFImg2DRgba32>("kernelStorageImage", 0, 0); auto kernelImage = writer.declSampledImage<FImg2DRgba32>("kernelImage", 2, 0); //* auto ACESFilm = writer.implementFunction<Vec3>( "ACESFilm", [&](const Vec3& x_arg) { auto ACESMatrix = writer.declLocale<Mat3>( "ACESMatrix", mat3(vec3(0.59719_f, 0.35458_f, 0.04823_f), vec3(0.07600_f, 0.90834_f, 0.01566_f), vec3(0.02840_f, 0.13383_f, 0.83777_f))); ACESMatrix = transpose(ACESMatrix); auto ACESMatrixInv = writer.declLocale<Mat3>( "ACESMatrixInv", inverse(ACESMatrix)); auto x = writer.declLocale("x", x_arg); // RGB to ACES conversion x = ACESMatrix * x; // ACES system tone scale (RTT+ODT) auto a = writer.declLocale("a", 0.0245786_f); auto b = writer.declLocale("b", -0.000090537_f); auto c = writer.declLocale("c", 0.983729_f); auto d = writer.declLocale("d", 0.4329510_f); auto e = writer.declLocale("e", 0.238081_f); x = (x * (x + a) + b) / (x * (x * c + d) + e); // ACES to RGB conversion x = ACESMatrixInv * x; writer.returnStmt(x); }, InVec3{ writer, "x_arg" }); auto bloom = writer.implementFunction<Vec3>( "bloom", [&](const Float& scale, const Float& threshold, const Vec2& fragCoord) { auto logScale = writer.declLocale("logScale", log2(scale) + 1.0_f); auto bloomV3 = writer.declLocale("bloomV3", vec3(0.0_f)); FOR(writer, Int, y, -1_i, y <= 1_i, ++y) { FOR(writer, Int, x, -1_i, x <= 1_i, ++x) { bloomV3 += kernelImage .lod( (fragCoord + vec2(x, y) * vec2(scale)) / vec2(writer.Width, writer.Height), logScale) .rgb(); } ROF; } ROF; writer.returnStmt( max(bloomV3 / vec3(9.0_f) - vec3(threshold), vec3(0.0_f))); }, InFloat{ writer, "scale" }, InFloat{ writer, "threshold" }, InVec2{ writer, "fragCoord" }); //*/ writer.implementMain([&]() { auto uv = writer.declLocale( "uv", in.fragCoord.xy() / vec2(1280.0_f, 720.0_f)); auto col = writer.declLocale("col", kernelImage.sample(uv).rgb()); auto bloomAscale1 = writer.declLocale( "BloomAscale1", writer.ubo.getMember<Float>("bloomAscale1")); auto bloomAscale2 = writer.declLocale( "BloomAscale2", writer.ubo.getMember<Float>("bloomAscale2")); auto bloomBscale1 = writer.declLocale( "BloomBscale1", writer.ubo.getMember<Float>("bloomBscale1")); auto bloomBscale2 = writer.declLocale( "BloomBscale2", writer.ubo.getMember<Float>("bloomBscale2")); auto bloomA = writer.declLocale( "bloomA", bloom(bloomAscale1 * writer.Height, 0.0_f, in.fragCoord.xy())); auto bloomB = writer.declLocale( "bloomB", bloom(bloomBscale1 * writer.Height, 0.0_f, in.fragCoord.xy())); // auto bloomA = writer.declLocale( // "bloomA", bloom(0.15_f, 0.0_f, in.fragCoord.xy())); // auto bloomB = writer.declLocale( // "bloomB", bloom(0.05_f, 0.0_f, in.fragCoord.xy())); auto bloomSum = writer.declLocale("bloomSum", bloomA * vec3(bloomAscale2) + bloomB * vec3(bloomBscale2)); // fragColor = vec4(bloomA, 1.0_f); // fragColor = vec4(ACESFilm(col), 1.0_f); fragColor = vec4(ACESFilm(col + bloomSum), 1.0_f); // fragColor = vec4((col + bloomSum), 1.0_f); // fragColor = vec4(col, 1.0_f); // fragColor = vec4(in.fragCoord.xy() / vec2(writer.Width, // writer.Height), 0.0_f, 1.0_f); }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); m_fragmentModule = vk.create(createInfo); if (!m_fragmentModule) { std::cerr << "error: failed to create fragment shader module" << std::endl; abort(); } } // namespace cdm #pragma endregion #pragma region computeShader { using namespace sdw; MandelbulbShaderLib<ComputeWriter> writer{ m_config }; auto in = writer.getIn(); writer.inputLayout(8, 8); auto kernelSampledImage = writer.declSampledImage<FImg2DRgba32>("kernelSampledImage", 2, 0); auto kernelImage = writer.declImage<RWFImg2DRgba32>("kernelImage", 0, 0); writer.implementMain([&]() { Float x = writer.declLocale( "x", writer.cast<Float>(in.globalInvocationID.x())); Float y = writer.declLocale( "y", writer.cast<Float>(in.globalInvocationID.y())); Vec2 xy = writer.declLocale("xy", vec2(x, y)); IVec2 iuv = writer.declLocale( "iuv", ivec2(writer.cast<Int>(in.globalInvocationID.x()), writer.cast<Int>(in.globalInvocationID.y()))); //* Vec4 previousColor = writer.declLocale("previousColor", kernelImage.load(iuv)); Float samples = writer.declLocale( "samples", writer.ubo.getMember<Float>("samples")); //"samples", previousColor.a()); IF(writer, samples == -1.0_f) { kernelImage.store(iuv, vec4(0.0_f)); } ELSE { Vec2 mousePos = writer.declLocale( "mousePos", vec2(writer.cast<Float>( writer.ubo.getMember<Int>("mouseX")), writer.cast<Float>( writer.ubo.getMember<Int>("mouseY")))); IF(writer, writer.ubo.getMember<Int>("mousePressed") == 1_i && length(mousePos - xy) > 40.0_f) { writer.returnStmt(); } FI; Float seed = writer.declLocale( "seed", cos(x) + sin(y) + writer.ubo.getMember<Float>("seed")); auto CamFocalDistance = writer.declLocale( "CamFocalDistance", writer.ubo.getMember<Float>("camFocalDistance")); auto CamFocalLength = writer.declLocale( "CamFocalLength", writer.ubo.getMember<Float>("camFocalLength")); auto CamAperture = writer.declLocale( "CamAperture", writer.ubo.getMember<Float>("camAperture")); auto CamRot = writer.declLocale( "CamRot", writer.ubo.getMember<Vec3>("camRot")); Vec2 fragCoord = writer.declLocale( "fragCoord", vec2(x, -y + writer.Height - 1.0_f)); Vec2 uv = writer.declLocale( "uv", (fragCoord + vec2(writer.randomFloat(seed), writer.randomFloat(seed)) - vec2(writer.Width, writer.Height) / vec2(2.0_f)) / vec2(writer.Height, writer.Height)); Vec3 focalPoint = writer.declLocale( "focalPoint", vec3(uv * CamFocalDistance / CamFocalLength, CamFocalDistance)); Vec3 aperture = writer.declLocale( "aperture", CamAperture * vec3(writer.sampleAperture(6_i, 0.0_f, seed), 0.0_f)); Vec3 rayDir = writer.declLocale( "rayDir", normalize(focalPoint - aperture)); Vec3 CamPos = writer.declLocale("CamPos", vec3(0.0_f, 0.0_f, -15.0_f)); Mat3 CamMatrix = writer.declLocale( "CamMatrix", writer.rotationMatrix(CamRot)); CamPos = CamMatrix * CamPos; rayDir = CamMatrix * rayDir; aperture = CamMatrix * aperture; samples = previousColor.a(); // clang-format off Vec3 newColor = writer.declLocale("newColor", writer.pathTrace(CamPos + aperture, rayDir, seed)); Vec3 mixer = writer.declLocale("mixer", vec3(1.0_f / (samples + 1.0_f))); Vec3 mixedColor = writer.declLocale("mixedColor", mix(previousColor.rgb(), newColor, mixer)); Vec4 mixedColor4 = writer.declLocale("mixedColor4", vec4(mixedColor, samples + 1.0_f)); // clang-format on kernelImage.store(iuv, mixedColor4); // imageStore(kernelImage, iuv, vec4(uv, 0.0_f, 1.0_f)); // imageStore(kernelImage, iuv, vec4(0.0_f, fragCoord.y(), // 0.0_f, 1.0_f)); imageStore(kernelImage, iuv, // vec4(fragCoord.x(), 0.0_f, 0.0_f, 0.0_f)); // imageStore(kernelImage, iuv, vec4(x, 0.0_f, 0.0_f, 0.0_f)); // imageStore(kernelImage, iuv, // vec4(uv, 0.0_f, 0.0_f)); } FI; //*/ // kernelImage.store(iuv, vec4(1.0_f)); }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); m_computeModule = vk.create(createInfo); if (!m_computeModule) { std::cerr << "error: failed to create compute shader module" << std::endl; abort(); } } #pragma endregion #pragma region compute descriptor pool std::array poolSizes{ VkDescriptorPoolSize{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 }, VkDescriptorPoolSize{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, VkDescriptorPoolSize{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 }, }; vk::DescriptorPoolCreateInfo poolInfo; poolInfo.maxSets = 1; poolInfo.poolSizeCount = 3; poolInfo.pPoolSizes = poolSizes.data(); m_computePool = vk.create(poolInfo); if (!m_computePool) { std::cerr << "error: failed to create compute descriptor pool" << std::endl; abort(); } #pragma endregion #pragma region compute descriptor set layout VkDescriptorSetLayoutBinding layoutBindingKernelImage{}; layoutBindingKernelImage.binding = 0; layoutBindingKernelImage.descriptorCount = 1; layoutBindingKernelImage.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; layoutBindingKernelImage.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding layoutBindingUbo{}; layoutBindingUbo.binding = 1; layoutBindingUbo.descriptorCount = 1; layoutBindingUbo.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; layoutBindingUbo.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding layoutBindingImage{}; layoutBindingImage.binding = 2; layoutBindingImage.descriptorCount = 1; layoutBindingImage.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; layoutBindingImage.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; std::array layoutBindings{ layoutBindingKernelImage, layoutBindingUbo, layoutBindingImage }; vk::DescriptorSetLayoutCreateInfo setLayoutInfo; setLayoutInfo.bindingCount = 3; setLayoutInfo.pBindings = layoutBindings.data(); m_computeSetLayout = vk.create(setLayoutInfo); if (!m_computeSetLayout) { std::cerr << "error: failed to create compute set layout" << std::endl; abort(); } #pragma endregion #pragma region compute descriptor set vk::DescriptorSetAllocateInfo setAlloc; setAlloc.descriptorPool = m_computePool.get(); setAlloc.descriptorSetCount = 1; setAlloc.pSetLayouts = &m_computeSetLayout.get(); vk.allocate(setAlloc, &m_computeSet.get()); if (!m_computeSet) { std::cerr << "error: failed to allocate compute descriptor set" << std::endl; abort(); } #pragma endregion #pragma region compute pipeline layout // VkPushConstantRange pcRange{}; // pcRange.size = sizeof(float); // pcRange.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; vk::PipelineLayoutCreateInfo computePipelineLayoutInfo; computePipelineLayoutInfo.setLayoutCount = 1; computePipelineLayoutInfo.pSetLayouts = &m_computeSetLayout.get(); // computePipelineLayoutInfo.pushConstantRangeCount = 1; // computePipelineLayoutInfo.pPushConstantRanges = &pcRange; computePipelineLayoutInfo.pushConstantRangeCount = 0; computePipelineLayoutInfo.pPushConstantRanges = nullptr; m_computePipelineLayout = vk.create(computePipelineLayoutInfo); if (!m_computePipelineLayout) { std::cerr << "error: failed to create compute pipeline layout" << std::endl; abort(); } #pragma endregion #pragma region pipeline vk::PipelineShaderStageCreateInfo vertShaderStageInfo; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = m_vertexModule.get(); vertShaderStageInfo.pName = "main"; vk::PipelineShaderStageCreateInfo fragShaderStageInfo; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = m_fragmentModule.get(); fragShaderStageInfo.pName = "main"; std::array shaderStages = { vertShaderStageInfo, fragShaderStageInfo }; VkVertexInputBindingDescription binding = {}; binding.binding = 0; binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; binding.stride = sizeof(float) * 2; VkVertexInputAttributeDescription attribute = {}; attribute.binding = 0; attribute.format = VK_FORMAT_R32G32_SFLOAT; attribute.location = 0; attribute.offset = 0; vk::PipelineVertexInputStateCreateInfo vertexInputInfo; vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.pVertexBindingDescriptions = &binding; vertexInputInfo.vertexAttributeDescriptionCount = 1; vertexInputInfo.pVertexAttributeDescriptions = &attribute; vk::PipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; inputAssembly.primitiveRestartEnable = false; VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = widthf; viewport.height = heightf; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent.width = width; scissor.extent.height = height; vk::PipelineViewportStateCreateInfo viewportState; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; vk::PipelineRasterizationStateCreateInfo rasterizer; rasterizer.depthClampEnable = false; rasterizer.rasterizerDiscardEnable = false; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_NONE; // VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.depthBiasEnable = false; rasterizer.depthBiasConstantFactor = 0.0f; rasterizer.depthBiasClamp = 0.0f; rasterizer.depthBiasSlopeFactor = 0.0f; vk::PipelineMultisampleStateCreateInfo multisampling; multisampling.sampleShadingEnable = false; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; multisampling.pSampleMask = nullptr; multisampling.alphaToCoverageEnable = false; multisampling.alphaToOneEnable = false; VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = false; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.blendEnable = true; // colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; // colorBlendAttachment.dstColorBlendFactor = // VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; // colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendAttachmentState colorHDRBlendAttachment = {}; colorHDRBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; // colorHDRBlendAttachment.blendEnable = false; // colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // colorHDRBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; colorHDRBlendAttachment.blendEnable = true; colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; colorHDRBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; std::array colorBlendAttachments{ colorBlendAttachment, // colorHDRBlendAttachment }; vk::PipelineColorBlendStateCreateInfo colorBlending; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = uint32_t(colorBlendAttachments.size()); colorBlending.pAttachments = colorBlendAttachments.data(); colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::array dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH }; vk::PipelineDynamicStateCreateInfo dynamicState; dynamicState.dynamicStateCount = uint32_t(dynamicStates.size()); dynamicState.pDynamicStates = dynamicStates.data(); vk::GraphicsPipelineCreateInfo pipelineInfo; pipelineInfo.stageCount = uint32_t(shaderStages.size()); pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = nullptr; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = nullptr; pipelineInfo.layout = m_computePipelineLayout.get(); pipelineInfo.renderPass = m_renderPass.get(); pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = nullptr; pipelineInfo.basePipelineIndex = -1; m_pipeline = vk.create(pipelineInfo); if (!m_pipeline) { std::cerr << "error: failed to create graphics pipeline" << std::endl; abort(); } #pragma endregion #pragma region compute pipeline vk::ComputePipelineCreateInfo computePipelineInfo; computePipelineInfo.layout = m_computePipelineLayout.get(); computePipelineInfo.stage = vk::PipelineShaderStageCreateInfo(); computePipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; computePipelineInfo.stage.module = m_computeModule.get(); computePipelineInfo.stage.pName = "main"; computePipelineInfo.basePipelineHandle = nullptr; computePipelineInfo.basePipelineIndex = -1; m_computePipeline = vk.create(computePipelineInfo); if (!m_computePipeline) { std::cerr << "error: failed to create compute pipeline" << std::endl; abort(); } #pragma endregion #pragma region vertexBuffer using Vertex = std::array<float, 2>; // std::vector<Vertex> vertices(POINT_COUNT); // for (auto& vertex : vertices) //{ // vertex[0] = dis(gen); // vertex[1] = dis(gen); //} std::vector<Vertex> vertices{ { -1, -1 }, { 3, -1 }, { -1, 3 } }; m_vertexBuffer = Buffer( vk, sizeof(Vertex) * vertices.size(), VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); Vertex* data = m_vertexBuffer.map<Vertex>(); std::copy(vertices.begin(), vertices.end(), data); m_vertexBuffer.unmap(); #pragma endregion #pragma region compute UBO m_computeUbo = Buffer( vk, sizeof(m_config), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); m_config.copyTo(m_computeUbo.map()); m_computeUbo.unmap(); CamAperture = m_config.camAperture; CamFocalDistance = m_config.camFocalDistance; CamFocalLength = m_config.camFocalLength; VkDescriptorBufferInfo setBufferInfo{}; setBufferInfo.buffer = m_computeUbo.get(); setBufferInfo.range = sizeof(m_config); setBufferInfo.offset = 0; vk::WriteDescriptorSet uboWrite; uboWrite.descriptorCount = 1; uboWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboWrite.dstArrayElement = 0; uboWrite.dstBinding = 1; uboWrite.dstSet = m_computeSet.get(); uboWrite.pBufferInfo = &setBufferInfo; vk.updateDescriptorSets(uboWrite); #pragma endregion TextureFactory f(vk); #pragma region outputImage f.setWidth(width); f.setHeight(height); f.setFormat(VK_FORMAT_R8G8B8A8_UNORM); f.setUsage(VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); // f.setMipLevels(-1); m_outputImage = f.createTexture2D(); vk.debugMarkerSetObjectName(m_outputImage.image(), "outputImage"); // m_outputImage = Texture2D( // rw, width, height, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_TILING_OPTIMAL, // VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | // VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, // VMA_MEMORY_USAGE_GPU_ONLY, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); m_outputImage.transitionLayoutImmediate(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); #pragma endregion #pragma region outputImageHDR // f.setWidth(width); // f.setHeight(height); f.setFormat(VK_FORMAT_R32G32B32A32_SFLOAT); f.setUsage(VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); f.setMipLevels(11); f.setLod(0, 10); f.setMipmapMode(VK_SAMPLER_MIPMAP_MODE_LINEAR); m_outputImageHDR = f.createTexture2D(); vk.debugMarkerSetObjectName(m_outputImageHDR.image(), "outputImageHDR"); // m_outputImageHDR = Texture2D( // rw, width, height, VK_FORMAT_R32G32B32A32_SFLOAT, // VK_IMAGE_TILING_OPTIMAL, // VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | // VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT // | VK_IMAGE_USAGE_SAMPLED_BIT, // VMA_MEMORY_USAGE_GPU_ONLY, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, -1); m_outputImageHDR.transitionLayoutImmediate(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); VkDescriptorImageInfo setImageInfo{}; setImageInfo.imageView = m_outputImageHDR.view(); setImageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkDescriptorImageInfo setImageInfo2{}; setImageInfo2.imageView = m_outputImageHDR.view(); setImageInfo2.imageLayout = VK_IMAGE_LAYOUT_GENERAL; setImageInfo2.sampler = m_outputImageHDR.sampler(); vk::WriteDescriptorSet write; write.descriptorCount = 1; write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write.dstArrayElement = 0; write.dstBinding = 0; write.dstSet = m_computeSet.get(); write.pImageInfo = &setImageInfo; vk::WriteDescriptorSet write2; write2.descriptorCount = 1; write2.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; write2.dstArrayElement = 0; write2.dstBinding = 2; write2.dstSet = m_computeSet.get(); write2.pImageInfo = &setImageInfo2; std::array writes{ write, write2 }; vk.updateDescriptorSets(2, writes.data()); #pragma endregion #pragma region framebuffer vk::FramebufferCreateInfo framebufferInfo; framebufferInfo.renderPass = m_renderPass.get(); std::array attachments = { m_outputImage.view() //, m_outputImageHDR.view() }; framebufferInfo.attachmentCount = uint32_t(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = width; framebufferInfo.height = height; framebufferInfo.layers = 1; m_framebuffer = vk.create(framebufferInfo); if (!m_framebuffer) { std::cerr << "error: failed to create framebuffer" << std::endl; abort(); } #pragma endregion } Mandelbulb::~Mandelbulb() {} void Mandelbulb::render(CommandBuffer& cb) { std::array clearValues = { VkClearValue{}, VkClearValue{} }; vk::RenderPassBeginInfo rpInfo; rpInfo.framebuffer = m_framebuffer.get(); rpInfo.renderPass = m_renderPass.get(); rpInfo.renderArea.extent.width = width; rpInfo.renderArea.extent.height = height; //rpInfo.renderArea.offset.x = mouseX - 10; //rpInfo.renderArea.offset.y = mouseY - 10; //rpInfo.renderArea.extent.width = mouseX + 10; //rpInfo.renderArea.extent.height = mouseY + 10; rpInfo.clearValueCount = 1; rpInfo.pClearValues = clearValues.data(); vk::SubpassBeginInfo subpassBeginInfo; subpassBeginInfo.contents = VK_SUBPASS_CONTENTS_INLINE; vk::SubpassEndInfo subpassEndInfo; cb.beginRenderPass2(rpInfo, subpassBeginInfo); cb.bindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline.get()); cb.bindDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, m_computePipelineLayout.get(), 0, m_computeSet.get()); cb.bindVertexBuffer(m_vertexBuffer.get()); // cb.draw(POINT_COUNT); cb.draw(3); cb.endRenderPass2(subpassEndInfo); } void Mandelbulb::compute(CommandBuffer& cb) { cb.bindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, m_computePipeline.get()); cb.bindDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, m_computePipelineLayout.get(), 0, m_computeSet.get()); cb.dispatch(width / 8, height / 8); } void Mandelbulb::imgui(CommandBuffer& cb) { ImGui_ImplVulkan_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); { static float f = 0.0f; static int counter = 0; ImGui::Begin("Controls"); bool changed = false; changed |= ImGui::SliderFloat("CamFocalDistance", &m_config.camFocalDistance, 0.1f, 30.0f); changed |= ImGui::SliderFloat("CamFocalLength", &m_config.camFocalLength, 0.0f, 20.0f); changed |= ImGui::SliderFloat("CamAperture", &m_config.camAperture, 0.0f, 5.0f); changed |= ImGui::DragFloat3("rotation", &m_config.camRot.x, 0.01f); changed |= ImGui::DragFloat3("lightDir", &m_config.lightDir.x, 0.01f); changed |= ImGui::SliderFloat("scene radius", &m_config.sceneRadius, 0.0f, 10.0f); ImGui::SliderFloat("BloomAscale1", &m_config.bloomAscale1, 0.0f, 1.0f); ImGui::SliderFloat("BloomAscale2", &m_config.bloomAscale2, 0.0f, 1.0f); ImGui::SliderFloat("BloomBscale1", &m_config.bloomBscale1, 0.0f, 1.0f); ImGui::SliderFloat("BloomBscale2", &m_config.bloomBscale2, 0.0f, 1.0f); changed |= ImGui::SliderFloat("Power", &m_config.power, 0.0f, 50.0f); changed |= ImGui::DragInt("Iterations", &m_config.iterations, 0.1f, 1, 64); if (changed) applyImguiParameters(); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } ImGui::Render(); // vk::ImageMemoryBarrier barrier; // barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; // barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // barrier.image = outputImage(); // barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // barrier.subresourceRange.baseMipLevel = 0; // barrier.subresourceRange.levelCount = 1; // barrier.subresourceRange.baseArrayLayer = 0; // barrier.subresourceRange.layerCount = 1; // barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // cb.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, // VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); { std::array clearValues = { VkClearValue{}, VkClearValue{} }; vk::RenderPassBeginInfo rpInfo; rpInfo.framebuffer = m_framebuffer.get(); rpInfo.renderPass = renderWindow.imguiRenderPass(); rpInfo.renderArea.extent.width = width; rpInfo.renderArea.extent.height = height; rpInfo.clearValueCount = 1; rpInfo.pClearValues = clearValues.data(); vk::SubpassBeginInfo subpassBeginInfo; subpassBeginInfo.contents = VK_SUBPASS_CONTENTS_INLINE; cb.beginRenderPass2(rpInfo, subpassBeginInfo); } ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cb.get()); vk::SubpassEndInfo subpassEndInfo2; cb.endRenderPass2(subpassEndInfo2); // barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; // barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // barrier.dstAccessMask = // VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; // cb.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, // VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); } void Mandelbulb::draw() { if (mustClear) { mustClear = false; m_config.samples = -1.0f; //outputTexture().transitionLayoutImmediate( //outputTextureHDR().transitionLayoutImmediate( //VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); cb.reset(); cb.begin(); vk::ImageMemoryBarrier barrier; //barrier.image = outputImage(); barrier.image = outputImageHDR(); barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; cb.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); VkClearColorValue clearColor{}; VkImageSubresourceRange range{}; range.aspectMask = VkImageAspectFlagBits::VK_IMAGE_ASPECT_COLOR_BIT; range.layerCount = 1; range.levelCount = 1; //cb.clearColorImage(outputImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, cb.clearColorImage(outputImageHDR(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearColor, range); barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; cb.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); cb.end(); //if (vk.queueSubmit(vk.graphicsQueue(), imguiCB.get()) != VK_SUCCESS) if (vk.queueSubmit(vk.graphicsQueue(), cb.get()) != VK_SUCCESS) { std::cerr << "error: failed to submit clear command buffer" << std::endl; abort(); } vk.wait(vk.graphicsQueue()); //outputTexture().transitionLayoutImmediate( //outputTextureHDR().transitionLayoutImmediate( //VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); m_config.samples += 1.0f; } double mouseX, mouseY; getMousePos(mouseX, mouseY); setSampleAndRandomize(m_config.samples); m_config.mouseX = int(mouseX); m_config.mouseY = int(mouseY); m_config.mousePressed = int(getMouseButtonState(MouseButton::Right) == ButtonState::Pressing); computeCB.reset(); computeCB.begin(); computeCB.debugMarkerBegin("compute", 1.0f, 0.2f, 0.2f); compute(computeCB); computeCB.debugMarkerEnd(); computeCB.end(); if (vk.queueSubmit(vk.graphicsQueue(), computeCB.get()) != VK_SUCCESS) { std::cerr << "error: failed to submit imgui command buffer" << std::endl; abort(); } vk.wait(vk.graphicsQueue()); outputTextureHDR().generateMipmapsImmediate(VK_IMAGE_LAYOUT_GENERAL); outputTexture().transitionLayoutImmediate( VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); imguiCB.reset(); imguiCB.begin(); imguiCB.debugMarkerBegin("render", 0.2f, 0.2f, 1.0f); // mandelbulb.compute(imguiCB); render(imguiCB); imgui(imguiCB); imguiCB.debugMarkerEnd(); imguiCB.end(); if (vk.queueSubmit(vk.graphicsQueue(), imguiCB.get()) != VK_SUCCESS) { std::cerr << "error: failed to submit imgui command buffer" << std::endl; abort(); } vk.wait(vk.graphicsQueue()); m_config.samples += 1.0f; auto swapImages = renderWindow.swapchainImages(); vk.debugMarkerSetObjectName(copyHDRCB.get(), VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, "copyHDRCB"); renderWindow.present(m_outputImage, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, nullptr); vk.wait(); vk.wait(); outputTexture().transitionLayoutImmediate( VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); vk.wait(); /* copyHDRCB.reset(); copyHDRCB.begin(); vk::ImageMemoryBarrier barrier; barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = outputImage(); barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; copyHDRCB.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); for (auto swapImage : swapImages) { vk::ImageMemoryBarrier swapBarrier = barrier; swapBarrier.image = swapImage; swapBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; swapBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; swapBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; swapBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; copyHDRCB.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, swapBarrier); VkImageBlit blit{}; blit.srcOffsets[1].x = 1280; blit.srcOffsets[1].y = 720; blit.srcOffsets[1].z = 1; blit.dstOffsets[1].x = 1280; blit.dstOffsets[1].y = 720; blit.dstOffsets[1].z = 1; blit.srcSubresource.aspectMask = VkImageAspectFlagBits::VK_IMAGE_ASPECT_COLOR_BIT; blit.srcSubresource.baseArrayLayer = 0; blit.srcSubresource.layerCount = 1; blit.srcSubresource.mipLevel = 0; blit.dstSubresource.aspectMask = VkImageAspectFlagBits::VK_IMAGE_ASPECT_COLOR_BIT; blit.dstSubresource.baseArrayLayer = 0; blit.dstSubresource.layerCount = 1; blit.dstSubresource.mipLevel = 0; copyHDRCB.blitImage(outputImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VkFilter::VK_FILTER_LINEAR); swapBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; swapBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; swapBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; swapBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; copyHDRCB.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, swapBarrier); } barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; copyHDRCB.pipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, barrier); if (copyHDRCB.end() != VK_SUCCESS) { std::cerr << "error: failed to record command buffer" << std::endl; abort(); } vk.wait(vk.graphicsQueue()); if (vk.queueSubmit(vk.graphicsQueue(), copyHDRCB.get()) != VK_SUCCESS) { std::cerr << "error: failed to submit draw command buffer" << std::endl; abort(); } vk.wait(vk.graphicsQueue()); //*/ } void Mandelbulb::applyImguiParameters() { m_config.samples = -1.0f; mustClear = true; } void Mandelbulb::randomizePoints() { using Vertex = std::array<float, 2>; std::vector<Vertex> vertices(POINT_COUNT); for (auto& vertex : vertices) { vertex[0] = dis(gen); vertex[1] = dis(gen); } Vertex* data = m_vertexBuffer.map<Vertex>(); std::copy(vertices.begin(), vertices.end(), static_cast<Vertex*>(data)); m_vertexBuffer.unmap(); m_config.seed = udis(gen); m_config.copyTo(m_computeUbo.map()); m_computeUbo.unmap(); } void Mandelbulb::setSampleAndRandomize(float s) { m_config.samples = s; m_config.seed = udis(gen); m_config.copyTo(m_computeUbo.map()); m_computeUbo.unmap(); } } // namespace cdm #include <chrono> int main() { using namespace cdm; RenderWindow rw(1280, 720, true); Mandelbulb mandelbulb(rw); return mandelbulb.run(); }
33.710077
113
0.678932
[ "render", "vector" ]
49bff17fc78211fa5c10e299ab09ee2b924e4667
15,035
cpp
C++
openbabel-2.4.1/src/formats/pngformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
1
2017-09-16T07:36:29.000Z
2017-09-16T07:36:29.000Z
openbabel-2.4.1/src/formats/pngformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
openbabel-2.4.1/src/formats/pngformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
/********************************************************************** Copyright (C) 2007 by Chris Morley This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <iterator> #include <openbabel/babelconfig.h> #include <openbabel/obconversion.h> #include <openbabel/mol.h> #include <zlib.h> using namespace std; namespace OpenBabel { class PNGFormat : public OBFormat { public: PNGFormat() { OBConversion::RegisterFormat("png",this); OBConversion::RegisterOptionParam("y", this, 1, OBConversion::INOPTIONS); OBConversion::RegisterOptionParam("y", this, 1, OBConversion::OUTOPTIONS); } virtual const char* Description() { return "PNG 2D depiction\n" "or add/extract chemical structures from a .png file\n\n" "The PNG format has several uses. The most common is to generate a\n" ":file:`.png` file for one or more molecules.\n" "2D coordinates are generated if not present::\n\n" " obabel mymol.smi -O image.png\n\n" "Chemical structure data can be embedded in the :file:`.png` file\n" "(in a ``tEXt`` chunk)::\n\n" " obabel mymol.mol -O image.png -xO molfile\n\n" "The parameter of the ``-xO`` option specifies the format (\"file\"can be added).\n" "Note that if you intend to embed a 2D or 3D format, you may have to call\n" "``--gen2d`` or ``--gen3d`` to generate the required coordinates if they are\n" "not present in the input.\n\n" "Molecules can also be embedded in an existing PNG file::\n\n" " obabel existing.png mymol1.smi mymol2.mol -O augmented.png -xO mol\n\n" "Reading from a PNG file will extract any embedded chemical structure data::\n\n" " obabel augmented.png -O contents.sdf\n\n" "Write Options e.g. -xp 500\n" " p <pixels> image size, default 300\n" " w <pixels> image width (or from image size)\n" " h <pixels> image height (or from image size)\n" " c# number of columns in table\n" " r# number of rows in table\n" " N# max number objects to be output\n" " u no element-specific atom coloring\n" " Use this option to produce a black and white diagram\n" " U do not use internally-specified color\n" " e.g. atom color read from cml or generated by internal code\n" " b <color> background color, default white\n" " e.g ``-xb yellow`` or ``-xb #88ff00`` ``-xb none`` is transparent.\n" " Just ``-xb`` is black with white bonds.\n" " The atom symbol colors work with black and white backgrounds,\n" " but may not with other colors.\n" " B <color> bond color, default black\n" " e.g ``-xB`` yellow or ``-xB #88ff00``\n" " C do not draw terminal C (and attached H) explicitly\n" " The default is to draw all hetero atoms and terminal C explicitly,\n" " together with their attched hydrogens.\n" " a draw all carbon atoms\n" " So propane would display as H3C-CH2-CH3\n" " d do not display molecule name\n" " m do not add margins to the image\n" " This only applies if there is a single molecule to depict.\n" " Implies -xd.\n" " s use asymmetric double bonds\n" " t use thicker lines\n" " A display aliases, if present\n" " This applies to structures which have an alternative, usually\n" " shorter, representation already present. This might have been input\n" " from an A or S superatom entry in an sd or mol file, or can be\n" " generated using the --genalias option. For example::\n \n" " obabel -:\"c1cc(C=O)ccc1C(=O)O\" -O out.png\n" " --genalias -xA\n \n" " would add a aliases COOH and CHO to represent the carboxyl and\n" " aldehyde groups and would display them as such in the svg diagram.\n" " The aliases which are recognized are in data/superatom.txt, which\n" " can be edited.\n" " O <format ID> Format of embedded text\n" " For example, ``molfile`` or ``smi``.\n" " If there is no parameter, input format is used.\n" " y <additional chunk ID> Write to a chunk with specified ID\n\n" "Read Options e.g. -ay\n" " y <additional chunk ID> Look also in chunks with specified ID\n\n" "If Cairo was not found when Open Babel was compiled, then\n" "the 2D depiction will be unavailable. However, it will still be\n" "possible to extract and embed chemical data in :file:`.png` files.\n" "\n" ".. seealso::\n\n" " :ref:`PNG_2D_depiction`\n\n" ; }; virtual const char* TargetClassDescription() { static string txt; txt = " PNG_files\n"; //so reports "n PNG_files converted" txt += OBFormat::TargetClassDescription(); //to display OBMol options in GUI return txt.c_str(); } virtual unsigned int Flags() { return READONEONLY | READBINARY | WRITEBINARY | DEPICTION2D; }; virtual bool ReadChemObject(OBConversion* pConv) { bool ret = ReadMolecule(NULL, pConv); pConv->GetChemObject(); //increments output index return ret; }; virtual bool WriteChemObject(OBConversion* pConv) { //If there is a PNG input file, embed all the subsequent molecules in it if(!CopyOfInput.empty() && bytesToIEND>0) { OBBase* pOb = pConv->GetChemObject(); return WriteMolecule(pOb, pConv); } else { _hasInputPngFile = false; //draw image in PNG2, which will test whether embedding is required OBFormat* ppng2 = OBConversion::FindFormat("_png2"); if(!ppng2) { obErrorLog.ThrowError("PNG Format","PNG2Format not found. Probably the Cairo library is not loaded.", obError); return false; } bool ret = ppng2->WriteChemObject(pConv); if(pConv->IsLast()) pConv->SetOutFormat(""); // report as output objects, not "PNG_files" return ret; } }; virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv); virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv); private: int _count; //number of chemical objects converted vector<char> CopyOfInput; unsigned bytesToIEND; //number of bytes upto but not including the IEND chunk. unsigned origBytesToIEND; //saved between WriteMolecule calls bool _hasInputPngFile; //Read and write number consisting of 4 bytes with most significant bytes first. //Should be independent of compiler and platform. unsigned long Read32(istream& ifs) { char ch; unsigned long val=0; for(int i=0; i<4; ++i) { if(!ifs.get(ch)) return 0; val = val * 0x100 + (unsigned char)ch; } return val; } void Write32(unsigned long val, ostream& ofs) { char p[4]; for(int i=0; i<4; ++i) { p[3-i] = (char)val % 0x100; val /= 0x100; } ofs.write(p, 4); } }; //////////////////////////////////////////////////// //Make an instance of the format class PNGFormat thePNGFormat; ///////////////////////////////////////////////////////////////// bool PNGFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) { istream& ifs = *pConv->GetInStream(); if(pConv->IsFirstInput()) { _count=0; _hasInputPngFile=true; } const char pngheader[] = {-119,80,78,71,13,10,26,10,0}; char readbytes[9]; ifs.read(readbytes, 8); if(!equal(pngheader, pngheader+8, readbytes)) { obErrorLog.ThrowError("PNG Format","Not a PNG file", obError); return false; } //Loop through all the chunks while(ifs) { unsigned int len = Read32(ifs); ifs.read(readbytes,4); string chunkid(readbytes, readbytes+4); if(chunkid=="IEND") { bytesToIEND = ifs.tellg(); bytesToIEND -= 8; break; } streampos pos = ifs.tellg(); const char* altid = pConv->IsOption("y",OBConversion::INOPTIONS); if(chunkid=="tEXt" || chunkid=="zTXt" || (altid && chunkid==altid)) { string keyword; getline(ifs, keyword, '\0'); unsigned int datalength = len - keyword.size()-1; //remove "file" from end of keyword transform(keyword.begin(),keyword.end(),keyword.begin(),::tolower); string::size_type pos = keyword.find("file"); if(pos!=string::npos) keyword.erase(pos); OBFormat* pFormat = OBConversion::FindFormat(keyword.c_str()); if(pFormat) { //We have found embedded text that we need to extract stringstream ss; if(chunkid[0]!='z') { //Copy it to a stringstream istreambuf_iterator<char> initer(ifs); ostreambuf_iterator<char> outiter(ss); for (unsigned int i = 0; i < datalength; ++i) *outiter++ = *initer++; } else { //Needs to be uncompressed first Bytef* pCompTxt = new Bytef[datalength]; ifs.read((char*)pCompTxt, datalength); --datalength; //for compression method byte uLongf uncompLen; Bytef* pUncTxt = new Bytef[datalength*6];//guess uncompressed length. NASTY! if(*pCompTxt!=0 /*compression method*/ || uncompress(pUncTxt, &uncompLen, pCompTxt+1, datalength)!=Z_OK) { obErrorLog.ThrowError("PNG Format","Errors in decompression", obError); delete[] pUncTxt; delete[] pCompTxt; return false; } pUncTxt[uncompLen] = '\0'; ss.str((char*)pUncTxt); delete[] pUncTxt; delete[] pCompTxt; } //Use a new OBConversion object to convert embedded text OBConversion conv2(&ss, pConv->GetOutStream()); conv2.CopyOptions(pConv); conv2.SetInAndOutFormats(pFormat, pConv->GetOutFormat()); _count += conv2.Convert(); ifs.ignore(4);//CRC continue; //already at the end of the chunk } } //Move to end of chunk ifs.seekg(pos); ifs.ignore(len+4); //data + CRC } //if we will be writing a png file, read and save the whole input file. CopyOfInput.clear(); if(pConv->GetOutFormat()==this) { ifs.seekg(0); copy(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>(),back_inserter(CopyOfInput)); } if(pConv->IsLastFile() && _count>0) { pConv->ReportNumberConverted(_count); //report the number of chemical objects pConv->SetOutFormat(this); //so that number of files is reported as "PNG_files" } return true; } ///////////////////////////////////////////////////////////////// bool PNGFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv) { // Embeds molecules into a png file in CopyOfInput ostream& ofs = *pConv->GetOutStream(); if(!CopyOfInput.empty() && bytesToIEND>0) { //copy the generated or saved png file, except the IEND chunk, to the output ostreambuf_iterator<char> outiter(pConv->GetOutStream()->rdbuf()); //In Windows the output stream needs to be in binary mode to avoid extra CRs here copy(CopyOfInput.begin(), CopyOfInput.begin()+bytesToIEND, outiter); origBytesToIEND = bytesToIEND; bytesToIEND=0;//to ensure not copied again } //Convert pOb and write it to a tEXt chunk const char* otxt = pConv->IsOption("O", OBConversion::OUTOPTIONS); OBConversion conv2; conv2.CopyOptions(pConv); //So that can use commandline options in this conversion string formatID; if(otxt && *otxt) { formatID = otxt; // Format name can have "file" at the end; // e.g. "molfile" is written in PNG chunk, but the format is "mol" string::size_type pos = formatID.find("file"); if(pos!=string::npos) formatID.erase(pos); } else //if no param on -xO option, format is input format formatID = pConv->GetInFormat()->GetID(); if(!conv2.SetOutFormat(OBConversion::FindFormat(formatID))) { obErrorLog.ThrowError("PNG Format","Format not found", obError); return false; } //Write new chunk stringstream ss; ss.str(""); const char* pid = pConv->IsOption("y"); if(pid && strlen(pid)==4) ss << pid; else ss << "tEXt"; ss << formatID << '\0'; bool ret = conv2.Write(pOb, &ss); if(ret) { unsigned long len = ss.str().size() - 4; //don't count length of tEXt Write32(len, ofs); ofs << ss.str(); //ss has type, keyword and data uLong crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, (unsigned char*)ss.str().c_str(), ss.str().size()); Write32(crc, ofs); } else obErrorLog.ThrowError("PNG Format","Failed when converting the molecule", obError); if(pConv->IsLast()) { //Write the IEND chunk ostreambuf_iterator<char> outiter(pConv->GetOutStream()->rdbuf()); copy(CopyOfInput.begin()+origBytesToIEND, CopyOfInput.end(), outiter); CopyOfInput.clear(); // If there is an input PNG file, decrement output index to not count it if(_hasInputPngFile) pConv->SetOutputIndex(pConv->GetOutputIndex()-1); // and report as output objects, not "PNG_files" pConv->SetOutFormat(formatID.c_str()); } return ret; } /* Reading PNGFormat extracts chemical information that is embedded in PNG files. The data can be in chunks of types tEXt, zTXt or, if in any type specified with the -aa option. If the first letter of the type is 'z' the data is decompressed. The keyword in the chunk should be an OpenBabel Format ID, optionally with file added, e.g. cml, InChI, molfile. There can be multiple molecules in each chunk, multiple chunks with chemical info and multiple png files can be read together. Writing This embeds chemical information into an existing PNG file. A PNG file should be the first input file, followed by one or more chemical files in any format. Each can contain multiple molecules. Each molecule is output in a separate chunk in a format specified by the -xO option. the default with no option is InChI. The chunk ID is normally tEXt but can be specified in the -xa option. For example babel OrigImg.png Firstmol.smi Secondmol.mol2 OutImg.png -xO "cml" -xa "chEm" It should be possible to embed into png filesusing the API. The following is simplified and UNTESTED: OBConversion conv; conv.SetInAndOutFormats("png","png"); stringstream ss; ifstream ifs("img.png"); ofstream ofs("img_with_chem.png"); OBMol mol; conv.Read(&mol, &ifs); //Reads the embedded molecule ...manipulate mol Note that the content of the PNG file is stored in PNGFormat, so do not input from another PNG file until this one is written. //Set the format of the embedded molecule on output conv.AddOption("O",OBConversion::OUTOPTIONS,"smi"); conv.Write(&mol, ofs); */ } //namespace OpenBabel
33.560268
119
0.643232
[ "object", "vector", "transform", "3d" ]
49cd54aaa754b2499d2cba5d9bb15ad928f1636e
1,322
hpp
C++
src/renderer/graphics_system.hpp
tuket/OWMAN
d1b3502c3f8e72e4442cc7b52ad32ca191ab8a11
[ "MIT" ]
6
2018-04-26T16:12:56.000Z
2021-08-06T05:20:01.000Z
src/renderer/graphics_system.hpp
ArnCarveris/OWMAN
d1b3502c3f8e72e4442cc7b52ad32ca191ab8a11
[ "MIT" ]
13
2015-11-17T10:18:45.000Z
2018-06-08T21:02:29.000Z
src/renderer/graphics_system.hpp
ArnCarveris/OWMAN
d1b3502c3f8e72e4442cc7b52ad32ca191ab8a11
[ "MIT" ]
2
2018-04-26T19:43:33.000Z
2019-07-03T12:27:31.000Z
#include "low_level_renderer_2d.hpp" #include "sprite_factory.hpp" #include <string> #include <set> #include <vector> #include "camera.hpp" #ifndef ENGINE class Engine; #endif #ifndef GRAPHICS_SYSTEM #define GRAPHICS_SYSTEM class GraphicsSystem { enum class PendingTaskType { DESTROY_SPRITE }; class PendingTask { public: PendingTask(const PendingTaskType& type, void* pointer); PendingTaskType pendingTaskType; void* pointer; }; std::vector<PendingTask> pendingTasks; Engine* myEngine; Camera camera; LowLevelRenderer2D renderer; std::set<GraphicsComponent*> components; // Factories SpriteFactory spriteFactory; public: GraphicsSystem ( std::string windowTitle, unsigned int width, unsigned int height, bool fullScreen ); /** \brief update animations */ void update(unsigned int delta); /** \brief set fullscreen mode */ void setFullScreen(bool b); void draw(); /** \brief Swap buffers * Once you ave drawn all the components \ * call this function to swap buffers */ void swap(); Sprite* createSprite(std::string fileName, const Vec2f& scale); void destroySprite(Sprite* sprite); void destroyGraphicsComponent(GraphicsComponent* graphicsComponent); LowLevelRenderer2D* getRenderer(); Camera* getCamera(); void end(); }; #endif
16.121951
69
0.727685
[ "vector" ]
49d0759b43e31d2bfc8663a22c7e3fbbf0ed811f
9,962
cpp
C++
torch/csrc/jit/script/sugared_value.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
1
2019-07-23T11:20:58.000Z
2019-07-23T11:20:58.000Z
torch/csrc/jit/script/sugared_value.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
torch/csrc/jit/script/sugared_value.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
#include <torch/csrc/jit/script/sugared_value.h> #include <torch/csrc/jit/ir.h> #include <torch/csrc/jit/script/schema_matching.h> #include <torch/csrc/jit/script/tree_views.h> namespace torch { namespace jit { namespace script { struct NoneValue : SugaredValue { NoneValue() = default; std::string kind() const override { return "None"; } }; std::shared_ptr<SugaredValue> PrintValue::call( const SourceRange& loc, Function& m, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) { auto& g = *m.graph(); if (!attributes.empty()) throw ErrorReport(loc) << "print doesn't accept any keyword arguments"; // temporary hack to allow print statements to work in python 2, where // print(a, b) is treated as a (a, b) tuple input. std::vector<Value*> lowered_inputs = toValues(*m.graph(), inputs); if (lowered_inputs.size() == 1 && lowered_inputs.at(0)->node()->kind() == prim::TupleConstruct) { auto input = lowered_inputs[0]; for (size_t j = 0; j < input->node()->inputs().size(); ++j) { lowered_inputs.insert( lowered_inputs.begin() + 1 + j, input->node()->inputs().at(j)); } lowered_inputs.erase(lowered_inputs.begin()); } g.insertNode(g.create(prim::Print, lowered_inputs, 0) ->setSourceLocation(std::make_shared<SourceRange>(loc))); return std::make_shared<NoneValue>(); } static const std::unordered_map<std::string, std::string>& builtin_cast_methods() { static std::unordered_map<std::string, std::string> builtin_cast_methods = { {"byte", "_cast_Byte"}, {"char", "_cast_Char"}, {"double", "_cast_Double"}, {"float", "_cast_Float"}, {"int", "_cast_Int"}, {"long", "_cast_Long"}, {"short", "_cast_Short"}, {"half", "_cast_Half"}}; return builtin_cast_methods; } std::shared_ptr<SugaredValue> BuiltinFunction::call( const SourceRange& loc, Function& m, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) { return std::make_shared<SimpleValue>( emitBuiltinCall(loc, *m.graph(), symbol, self, inputs, attributes, true)); } // support syntax sugar for x.foo(y, z) by allowing x.foo to return a // callable value that will resolve to foo(x, y, z) when called. std::shared_ptr<SugaredValue> SimpleValue::attr( const SourceRange& loc, Function& m, const std::string& field) { // Allow method-style casts on Tensor types. e.g. x.int() if (value_->type()->isSubtypeOf(TensorType::get())) { if (builtin_cast_methods().count(field)) { return std::make_shared<BuiltinFunction>( Symbol::aten(builtin_cast_methods().at(field)), NamedValue(loc, "self", value_)); } // functions that are just direct property lookups on tensor // must be registered as prim::<name>(Tensor t) -> <return_type> static const std::unordered_set<std::string> fields = { "dtype", "device", "shape", "is_cuda", "requires_grad", }; if (fields.count(field)) { auto r = m.graph()->insert(Symbol::fromQualString("prim::" + field), {value_}); return std::make_shared<SimpleValue>(r); } } if (value_->type()->isSubtypeOf(NumberType::get())) { throw ErrorReport(loc) << "Cannot call methods on numbers"; } if (auto tuple_type = value_->type()->cast<TupleType>()) { if (!tuple_type->hasNames()) { throw ErrorReport(loc) << "Getting attributes of tuples is not supported"; } auto names = tuple_type->names(); for (size_t i = 0; i < names.size(); i++) { if (names[i] == field) { auto r = m.graph() ->insertNode(m.graph()->createTupleIndex(value_, i)) ->output(); return std::make_shared<SimpleValue>(r); } } throw ErrorReport(loc) << "Unknown attribute to named tuple"; } if (auto classType = value_->type()->cast<ClassType>()) { // This is a class, emit the proper attribute lookup if (auto method = classType->getMethod(field)) { return std::make_shared<MethodValue>(getValue(), method); } if (!classType->hasAttribute(field)) { throw ErrorReport(loc) << "Tried to access to nonexistent attribute " << field << ". Did you forget to initialize it in __init__()?"; } auto& g = *m.graph(); auto n = g.insertNode(g.createGetAttr(value_, field)); return std::make_shared<SimpleValue>(n->output()); } return std::make_shared<BuiltinFunction>( Symbol::aten(field), NamedValue(loc, "self", value_)); } std::vector<std::shared_ptr<SugaredValue>> SimpleValue::asTuple( const SourceRange& loc, Function& m, const c10::optional<size_t>& size_hint) { static const auto make_simple_value = [](Value* v) -> std::shared_ptr<SugaredValue> { return std::make_shared<SimpleValue>(v); }; if (value_->type()->kind() == TypeKind::TupleType) { auto outputs = createTupleUnpack(value_); return fmap(outputs, make_simple_value); } else if (value_->type()->kind() == TypeKind::ListType) { if (!size_hint) { throw ErrorReport(loc) << "cannot statically infer the expected size of a " << "list in this context"; } auto graph = value_->owningGraph(); Node* unpack = graph->insertNode(graph->createListUnpack(value_, *size_hint)); return fmap(unpack->outputs(), make_simple_value); } throw ErrorReport(loc) << value_->type()->str() << " cannot be used as a tuple"; } void SimpleValue::setAttr( const SourceRange& loc, Function& m, const std::string& field, Value* newValue) { const auto classType = value_->type()->cast<ClassType>(); if (!classType) { throw ErrorReport(loc) << "Tried to set an attribute: " << field << " on a non-class: " << value_->type()->str(); } auto expectedType = classType->getAttribute(field); if (!expectedType) { // If we are still compiling the __init__ method for this class, then // setting an unknown attribute adds it to the class's definition. // We are initializing if: const auto isInitializing = // 1. The method we're currently inserting into is an init method m.name() == "__init__" && // 2. The `self` arg matches this value's type (i.e. we are in the init // method for this class, not some other class) !m.graph()->inputs().empty() && m.graph()->inputs().at(0)->type() == classType; if (isInitializing) { classType->addAttribute(field, newValue->type()); expectedType = newValue->type(); const auto insertPoint = m.graph()->insertPoint(); const auto topLevelBlock = m.graph()->block(); if (insertPoint->owningBlock() != topLevelBlock) { throw ErrorReport(loc) << "First assignment cannot be in a control-flow block. " << "Initialize the field at the top level first."; } } else { throw ErrorReport(loc) << "Tried to set nonexistent attribute: " << field << ". Did you forget to initialize it in __init__()?"; } } AT_ASSERT(expectedType); // Check type correctness const auto newType = newValue->type(); if (!newType->isSubtypeOf(expectedType)) { throw ErrorReport(loc) << "Wrong type for attribute assignment. Expected " << expectedType->str() << " but got " << newType->str(); } auto& g = *m.graph(); g.insertNode(g.createSetAttr(value_, field, newValue)); } std::shared_ptr<SugaredValue> SimpleValue::call( const SourceRange& loc, Function& m, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) { // allow our 'fake' closures to be called, used for fork serialization // at the moment, but can be expanded later Node* self = getValue()->node(); if (self->kind() == prim::TupleConstruct && self->inputs().size() == 2 && self->inputs().at(0)->node()->kind() == prim::Function) { std::shared_ptr<Graph> graph = self->inputs().at(0)->node()->g(attr::Subgraph); Value* context = self->inputs().at(1); AT_ASSERT(context->node()->kind() == prim::TupleConstruct); // fork nodes are emitted in their own block but we do not simplify // tuple construction across blocks. To ensure we clean up the tuple // construct create another copy of the tuple construct in the fork block Value* close_context = m.graph() ->insertNode(m.graph()->createTuple(context->node()->inputs())) ->output(); auto fn = CompilationUnit().create_function("anon", graph); return MethodValue(close_context, fn).call(loc, m, inputs, attributes, n_binders); } return SugaredValue::call(loc, m, inputs, attributes, n_binders); } std::shared_ptr<SugaredValue> ClassValue::call( const SourceRange& loc, Function& m, // note: names for args will be 'argument 0', 'argument 1', etc.. at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) { AT_ASSERT(n_binders <= 1); // Generate a new object of the right type, then call `__init__` on it auto& g = *m.graph(); auto self = g.insertNode(g.createObject(type_))->output(); auto initMethod = type_->getMethod("__init__"); AT_ASSERT(initMethod); // Call the init function MethodValue(self, initMethod).call(loc, m, inputs, attributes, n_binders); return std::make_shared<SimpleValue>(self); } std::shared_ptr<SugaredValue> ClassValue::attr( const SourceRange& loc, Function& m, const std::string& field) { if (field != "__new__") { throw ErrorReport(loc) << "Tried to lookup unknown attribute on class"; } return std::make_shared<ClassNewMethod>(type_); } } // namespace script } // namespace jit } // namespace torch
35.578571
86
0.633808
[ "object", "shape", "vector" ]
49d26dcfbbd517f9114651daca2909d868065902
3,783
cpp
C++
ReactQt/runtime/src/reactpropertyhandler.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
15
2018-03-11T23:50:11.000Z
2021-12-24T08:41:05.000Z
ReactQt/runtime/src/reactpropertyhandler.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
ReactQt/runtime/src/reactpropertyhandler.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
2
2018-04-14T19:47:35.000Z
2020-07-30T21:48:29.000Z
/** * Copyright (C) 2016, Canonical Ltd. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Author: Justin McPherson <justin.mcpherson@canonical.com> * */ #include <QDebug> #include "reactpropertyhandler.h" #include "reactvaluecoercion.h" ReactPropertyHandler::ReactPropertyHandler(QObject* object, SetPropertyCallback callback) : QObject(object), m_object(object), m_setPropertyCallback(callback) {} ReactPropertyHandler::~ReactPropertyHandler() {} QMap<QString, QMetaProperty> ReactPropertyHandler::availableProperties() { buildPropertyMap(); QMap<QString, QMetaProperty> allProperties; allProperties.unite(m_qmlProperties); allProperties.unite(m_HandlerProperties); return allProperties; } void ReactPropertyHandler::applyProperties(const QVariantMap& properties) { buildPropertyMap(); // qDebug() << __PRETTY_FUNCTION__ << m_object << properties; for (const QString& key : properties.keys()) { QVariant propertyValue = properties.value(key); QMap<QString, QMetaProperty>::iterator it = m_HandlerProperties.find(key); // Extras get first shot if (it != m_HandlerProperties.end()) { QMetaProperty property = it.value(); setValueToObjectProperty(this, property, propertyValue); } else if (m_exposeQmlProperties) { it = m_qmlProperties.find(key); if (it != m_qmlProperties.end()) { QMetaProperty property = it.value(); setValueToObjectProperty(m_object, property, propertyValue); } } } } QVariant ReactPropertyHandler::value(const QString& propertyName) { buildPropertyMap(); QVariant value; if (m_HandlerProperties.contains(propertyName)) { value = m_HandlerProperties[propertyName].read(this); } else if (m_exposeQmlProperties && m_qmlProperties.contains(propertyName)) { value = m_qmlProperties[propertyName].read(m_object); } return value; } void ReactPropertyHandler::buildPropertyMap() { if (m_cached) { return; } // Get qml properties of current object (and its parents) if (m_exposeQmlProperties) { const QMetaObject* metaObject = m_object->metaObject(); getPropertiesFromMetaObject(metaObject); } // Get all properties on the handlers (extras) const QMetaObject* metaObject = this->metaObject(); const int propertyCount = metaObject->propertyCount(); for (int i = 1; i < propertyCount; ++i) { QMetaProperty p = metaObject->property(i); if (p.isScriptable()) m_HandlerProperties.insert(p.name(), p); } m_cached = true; } void ReactPropertyHandler::getPropertiesFromMetaObject(const QMetaObject* metaObject) { // we get all prefixed properties from object and its parents const int propertyCount = metaObject->propertyCount(); for (int i = 0; i < propertyCount; ++i) { QMetaProperty p = metaObject->property(i); QString qmlPropName = p.name(); if (p.isScriptable() && qmlPropName.startsWith(QML_PROPERTY_PREFIX)) { QString nameWithoutPrefix = qmlPropName.right(qmlPropName.length() - QML_PROPERTY_PREFIX.length()); m_qmlProperties.insert(nameWithoutPrefix, p); } } } void ReactPropertyHandler::setValueToObjectProperty(QObject* object, QMetaProperty property, const QVariant& value) { property.write(object, reactCoerceValue(value, property.userType())); if (m_setPropertyCallback) { m_setPropertyCallback(object, property, value); } }
34.390909
117
0.69125
[ "object" ]
49d2838b2cabee1180faed85f07bcdde414cff8e
1,463
cpp
C++
spoj/MAXISET.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
spoj/MAXISET.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
spoj/MAXISET.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
/** Courage is a word of justice. It means the quality of mind that enables one to face apprehension with confidence and resolution. It is not right to use it as an excuse to kill someone */ #include <bits/stdc++.h> #define forn(i, l, r) for(int i=l;i<=r;i++) #define all(v) v.begin(),v.end() #define pb push_back #define nd second #define st first #define debug(x) cout<<#x<<" -> "<<x<< endl #define kakimasu(x) cout << x << '\n' #define sz(x) (int)x.size() #define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin()) //need to sort first b4 using unique using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<bool> vb; typedef vector<string> vs; typedef vector<double> vd; typedef vector<long long> vll; typedef vector<vector<int> > vvi; typedef vector<vll> vvll; typedef vector<pair<int, int> > vpi; typedef vector<vpi> vvpi; typedef pair<int, int> pi; typedef pair<ll, ll> pll; typedef vector<pll> vpll; const int INF = 1 << 30; /** Start coding from here */ const int maxn = 1 << 20; vpi a[maxn]; int w[45]; vi g[45]; int n, m, na, nb; int t1, t2; int main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL_PROJECT freopen("input.txt","r",stdin); #endif int tc; cin>>tc; while(tc--) { cin>>n>>m; na = n/2; nb = n - na; forn(i, 0, 44) g[i].clear(); forn(i, 0, n-1) cin>>w[i]; forn(i, 1, m) { cin>>t1>>t2; g[t1].pb(t2); g[t2].pb(t1); } } return 0; }
22.859375
191
0.643882
[ "vector" ]
49e2238ea04f69ce99b83cfcca66385f1c3a2a62
7,200
cpp
C++
tools/faodel-cli/KelpieBlastParams.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
tools/faodel-cli/KelpieBlastParams.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
tools/faodel-cli/KelpieBlastParams.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #include <iostream> #include <functional> #include "faodelConfig.h" #ifdef Faodel_ENABLE_MPI_SUPPORT #include <mpi.h> #endif #include "faodel-common/Configuration.hh" #include "faodel-common/ResourceURL.hh" #include "faodel-common/Bootstrap.hh" #include "faodel-common/StringHelpers.hh" #include "faodel-services/MPISyncStart.hh" #include "kelpie/Kelpie.hh" #include "faodel_cli.hh" #include "KelpieBlastParams.hh" using namespace std; KelpieBlastParams::KelpieBlastParams(const std::vector<std::string> &args) : mpi_rank(0), mpi_size(1), timestep(0), num_timesteps(1), delay_between_timesteps_us(1000000), k1_length(8), k2_length(8), reuse_memory(false), async_pubs(false), use_rft_keys(false), no_barrier_before_generate(false), verbose(0), failed(false) { //Parse our args failed = (parseArgs(args) != 0); if(failed) return; faodel::Configuration config; if(!pool_external.empty()) { //External pool. Just get reference from user pool_name = pool_external; } else { //Internal pool. Parse string auto vals = faodel::Split(pool_internal,':',true); if((vals.size()<1) || (vals.size()>2)) { cerr << "Problem parsing internal pool '"<<pool_internal<<"'"<<endl; failed = true; return; } //Setup an iom if user provided a path string url_extra; if(vals.size()==2) { config.Append("kelpie.ioms", "localdump"); config.Append("kelpie.iom.localdump.type", "PosixIndividualObjects"); config.Append("kelpie.iom.localdump.path", vals.at(1)); url_extra="&iom=localdump"; } #ifdef Faodel_ENABLE_MPI_SUPPORT //Create the dirman info config.Append("mpisyncstart.enable", "true"); config.Append("dirman.root_node_mpi", "0"); config.Append("dirman.resources_mpi[]", vals.at(0)+":/my/pool"+url_extra+" ALL"); #endif pool_name="/my/pool"; } if(verbose>1) { config.Append("kelpie.debug", "true"); config.Append("bootstrap.debug", "true"); } //Launch MPI #ifdef Faodel_ENABLE_MPI_SUPPORT MPI_Init(nullptr, nullptr); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); global_rank=mpi_rank; faodel::mpisyncstart::bootstrap(); #endif //Launch FAODEL faodel::bootstrap::Start(config, kelpie::bootstrap); } KelpieBlastParams::~KelpieBlastParams() { if(!failed) { #ifdef Faodel_ENABLE_MPI_SUPPORT MPI_Barrier(MPI_COMM_WORLD); faodel::bootstrap::Finish(); MPI_Barrier(MPI_COMM_WORLD); dbg0("Finalizing"); MPI_Finalize(); #else faodel::bootstrap::Finish(); #endif dbg0("Exiting"); } } void KelpieBlastParams::dumpSettings(faodel::DirectoryInfo dir) { if((failed)||(mpi_rank!=0)) return; cout << "# Runtime Configuration\n" << "# mpi_size: "<<mpi_size << endl << "# pool_name: "<<pool_name << endl << "# pool_dirinfo_url: "<<dir.url.GetFullURL() << endl << "# pool_dirinfo_num_members: "<<dir.members.size() << endl << "# num_timesteps: "<<num_timesteps << endl << "# delay_between_timesteps_us: "<<delay_between_timesteps_us << endl << "# object_sizes_per_timestep: "; for(auto x:object_sizes_per_timestep) { cout <<" "<<x; } cout << endl << "# max_object_size: "<<max_object_size << endl << "# bytes_per_rank_step: "<<bytes_per_rank_step << endl << "# reuse_memory: "<<reuse_memory << endl << "# async_pubs: "<<async_pubs << endl << "# use_rft_keys: "<<use_rft_keys << endl << "# no_barrier_before_generate: "<<no_barrier_before_generate << endl; } int KelpieBlastParams::parseArgs(const std::vector<std::string> &args) { string s_object_sizes; int rc=0; struct ArgInfo { string short_name; string long_name; bool has_argument; std::function<int(const string&)> lambda; }; vector<ArgInfo> options { { "-a", "--async", false, [=](const string &s) { this->async_pubs = true; return 0; } }, { "-m", "--reuse-memory", false, [=](const string &s) { this->reuse_memory = true; return 0; } }, { "-r", "--rank-grouping", false, [=](const string &s) { this->use_rft_keys = true; return 0; } }, { "-s", "--skip-barrier" , false, [=](const string &s) { this->no_barrier_before_generate = true; return 0; } }, { "-t", "--timesteps", true, [=](const string &s) { return faodel::StringToUInt64(&this->num_timesteps, s); } }, { "-T", "--delay", true, [=](const string &s) { return faodel::StringToTimeUS(&this->delay_between_timesteps_us, s); } }, { "-o", "--objects", true, [=,&s_object_sizes](const string &s) { s_object_sizes = s; return 0; } }, { "-p", "--external-pool", true, [=](const string &s) { this->pool_external = s; return 0; } }, { "-P", "--internal-pool", true, [=](const string &s) { this->pool_internal = s; return 0; } } }; for(int i=0; i<args.size(); i++) { bool found=false; for(auto &option : options) { if((option.short_name == args[i]) || (option.long_name == args[i])) { if(option.has_argument) { i++; if(i >= args.size()) { cerr << "Not enough arguments for " << option.short_name << "/" << option.long_name << endl; return -1; } } rc = option.lambda(args[i]); if(rc != 0) { cerr << "Problem parsing " << option.short_name << "/" << option.long_name << endl; return -1; } found = true; break; } } if(!found) { cerr <<"Unknown option "<<args[i]<<endl; return -1; } } //Verify values we were given if(num_timesteps<1) { rc=EINVAL; cerr<<"Timesteps must be greater than 0\n"; } //Verify we were given a pool if( !(pool_internal.empty() ^ pool_external.empty()) ) { cerr <<"You must specify either the external pool or the internal pool (but not both)\n"; return EINVAL; } if(s_object_sizes.empty()){ dbg0("No object sizes specified, using 1MB"); object_sizes_per_timestep.push_back(1024*1024); bytes_per_rank_step=1024*1024; max_object_size=1024*1024; } else { auto svals = faodel::Split(s_object_sizes,',',true); max_object_size=bytes_per_rank_step=0; for(auto s: svals) { uint64_t x; rc = faodel::StringToUInt64(&x,s); if(rc) { cerr<<"Parse error with object sizes for '"<<s<<"'\n"; return EINVAL; } object_sizes_per_timestep.push_back(x); bytes_per_rank_step += x; if(x>max_object_size) max_object_size=x; } } return 0; } void KelpieBlastParams::barrier() { #ifdef Faodel_ENABLE_MPI_SUPPORT MPI_Barrier(MPI_COMM_WORLD); #endif }
32.432432
140
0.603889
[ "object", "vector" ]
49e821649413cba6d2856c0fde4a8ee232971fe1
1,690
cpp
C++
Exemplo21/sources/model/Lamp.cpp
alencarrh/ComputacaoGrafica
b7ea6b46956e47f695e4437fe254fd974a2b90de
[ "MIT" ]
null
null
null
Exemplo21/sources/model/Lamp.cpp
alencarrh/ComputacaoGrafica
b7ea6b46956e47f695e4437fe254fd974a2b90de
[ "MIT" ]
null
null
null
Exemplo21/sources/model/Lamp.cpp
alencarrh/ComputacaoGrafica
b7ea6b46956e47f695e4437fe254fd974a2b90de
[ "MIT" ]
null
null
null
#include "../../headers/model/Lamp.h" Lamp::Lamp() {} Lamp::~Lamp() { delete this->_mesh; } Face* createFace2(int v0, int v1, int v2, int v3, int normal) { Face* face = new Face(); face->addVerticeId(v0); face->addVerticeId(v1); face->addVerticeId(v3); face->addVerticeId(v1); face->addVerticeId(v2); face->addVerticeId(v3); return face; } void Lamp::prepare() { this->_mesh = new Mesh("default"); int A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7; float escale = 4; this->_mesh->addVertice(new glm::vec3(1.0f / escale, 1.0f / escale, 1.0f / escale)); //A this->_mesh->addVertice(new glm::vec3(-1.0f / escale, 1.0f / escale, 1.0f / escale)); //B this->_mesh->addVertice(new glm::vec3(-1.0f / escale, -1.0f / escale, 1.0f / escale)); //C this->_mesh->addVertice(new glm::vec3(1.0f / escale, -1.0f / escale, 1.0f / escale)); //D this->_mesh->addVertice(new glm::vec3(1.0f / escale, 1.0f / escale, -1.0f / escale)); //E this->_mesh->addVertice(new glm::vec3(-1.0f / escale, 1.0f / escale, -1.0f / escale)); //F this->_mesh->addVertice(new glm::vec3(-1.0f / escale, -1.0f / escale, -1.0f / escale)); //G this->_mesh->addVertice(new glm::vec3(1.0f / escale, -1.0f / escale, -1.0f / escale)); //H Group* group = new Group("default"); group->addFace(createFace2(A, B, C, D, 4)); group->addFace(createFace2(A, D, H, E, 0)); group->addFace(createFace2(A, E, F, B, 2)); group->addFace(createFace2(C, B, F, G, 1)); group->addFace(createFace2(D, C, G, H, 3)); group->addFace(createFace2(H, G, F, E, 5)); this->_mesh->addGroup(group); this->_mesh->prepare(); }
34.489796
99
0.584615
[ "mesh", "model" ]
49eb08ee5e4fd3b7215e394b3c1a641c0767c186
2,775
cpp
C++
sparse/src/magma_zwrapper.cpp
LiangqinGong/magma
4c2588119ee636999b230b248fca3e3824a23be9
[ "BSD-3-Clause" ]
13
2018-03-25T01:03:31.000Z
2022-03-31T09:12:23.000Z
sparse/src/magma_zwrapper.cpp
LiangqinGong/magma
4c2588119ee636999b230b248fca3e3824a23be9
[ "BSD-3-Clause" ]
3
2020-01-02T05:21:16.000Z
2020-01-07T20:04:05.000Z
sparse/src/magma_zwrapper.cpp
LiangqinGong/magma
4c2588119ee636999b230b248fca3e3824a23be9
[ "BSD-3-Clause" ]
7
2018-03-24T23:33:28.000Z
2022-01-25T18:41:03.000Z
/* -- MAGMA (version 2.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date @precisions normal z -> c d s @author Hartwig Anzt */ #include "magmasparse_internal.h" /** Purpose ------- This is the interface to MAGMA-sparse functionalities. The zopts structure contains all information about which functionality is requested, where it is computed etc. Arguments --------- @param[in] zopts magma_zopts Structure containing all information which node-level operation is requested. @param[in] A magma_z_matrix Sparse matrix A in CSR format. @param[in] x magma_z_matrix* Output vector x. @param[in] b magma_z_matrix Input vector b. @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zaux ********************************************************************/ extern "C" magma_int_t magma_zwrapper( magma_zopts *zopts, magma_z_matrix A, magma_z_matrix *x, magma_z_matrix b, magma_queue_t queue ){ magma_int_t info = 0; switch( zopts->operation ) { case Magma_SOLVE: { CHECK( magma_zsolverinfo_init( &zopts->solver_par, &zopts->precond_par, queue ) ); CHECK( magma_zeigensolverinfo_init( &zopts->solver_par, queue ) ); CHECK( magma_z_precondsetup( A, b, &zopts->solver_par, &zopts->precond_par, queue ) ); CHECK( magma_z_solver( A, b, x, zopts, queue ) ); CHECK( magma_zsolverinfo( &zopts->solver_par, &zopts->precond_par, queue ) ); CHECK( magma_zsolverinfo_free( &zopts->solver_par, &zopts->precond_par, queue ) ); break; } case Magma_GENERATEPREC: { CHECK( magma_z_precondsetup( A, b, &zopts->solver_par, &zopts->precond_par, queue ) ); break; } case Magma_PRECONDLEFT: { magma_trans_t trans = MagmaNoTrans; CHECK( magma_z_applyprecond_left( trans, A, b, x, &zopts->precond_par, queue ) ); break; } case Magma_PRECONDRIGHT: { magma_trans_t trans = MagmaNoTrans; CHECK( magma_z_applyprecond_right( trans, A, b, x, &zopts->precond_par, queue ) ); break; } case Magma_SPMV:break; default: printf("error: no MAGMA-spare operation specified.\n"); break; } cleanup: return info; }
28.90625
105
0.535135
[ "vector" ]
49eb29d0371c7f89a5b796d5bf3ad4d47436d5de
10,199
cc
C++
tensorflow/core/grappler/optimizers/dependency_optimizer.cc
yasunakacho/tensorflow
cf36c3fdefda3c874cd8cebb779744c5035bb435
[ "Apache-2.0" ]
null
null
null
tensorflow/core/grappler/optimizers/dependency_optimizer.cc
yasunakacho/tensorflow
cf36c3fdefda3c874cd8cebb779744c5035bb435
[ "Apache-2.0" ]
null
null
null
tensorflow/core/grappler/optimizers/dependency_optimizer.cc
yasunakacho/tensorflow
cf36c3fdefda3c874cd8cebb779744c5035bb435
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 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/core/grappler/optimizers/dependency_optimizer.h" #include <unordered_set> #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/grappler/costs/graph_properties.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/grappler/op_types.h" #include "tensorflow/core/grappler/optimizers/arithmetic_optimizer.h" #include "tensorflow/core/grappler/optimizers/constant_folding.h" #include "tensorflow/core/grappler/utils/frame.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace grappler { namespace { // A vector with a set. The set stores the same elements as the vector, and // quickly answers whether a value is in the vector. Duplicated elements are not // allowed for now. template <class T> class SetVector { public: // Returns false if value already existed in the set, true otherwise. bool PushBack(const T& value) { if (!set_.insert(value).second) { return false; } vector_.push_back(value); return true; } T PopBack() { T back = vector_.back(); set_.erase(back); vector_.pop_back(); return back; } bool Exists(const T& value) const { return set_.count(value); } bool Empty() const { return vector_.empty(); } void Reserve(int64 size) { vector_.reserve(size); } private: std::unordered_set<T> set_; std::vector<T> vector_; }; bool HasRegularOutputs(const NodeDef& node, const NodeMap& node_map) { for (const NodeDef* output : node_map.GetOutputs(node.name())) { for (const string& input : output->input()) { if (input == node.name()) { return true; } } } return false; } int FindInputSlot(const NodeDef& node, const string& input) { for (int i = 0; i < node.input_size(); ++i) { if (node.input(i) == input) { return i; } } return -1; } } // namespace bool DependencyOptimizer::SafeToConvertToNoOp(const NodeDef& node) { if (!has_fetch_ || HasRegularOutputs(node, *node_map_)) { return false; } if (IsMerge(node)) { return false; } if (!ArithmeticOptimizer::CanDedup(node, nodes_to_preserve_)) { return false; } const OpDef* op_def = nullptr; Status status = OpRegistry::Global()->LookUpOpDef(node.op(), &op_def); if (!status.ok() || op_def->output_arg_size() == 0) { return false; } // TODO(rmlarsen): We have to skip Const nodes to make // core/debug/debug_gateway_test pass. See if we can fix that test. // TODO(rmlarsen): We have to skip Identity nodes to make an obsolete test in // python/training/session_manager_test.py pass. See if we can fix or get rid // of that test. const std::unordered_set<string> do_not_rewrite_ops = { "Assert", "CheckNumerics", "Const", "Identity", "_Retval", "_Arg", "_ParallelConcatUpdate", "_TPUExecute"}; return do_not_rewrite_ops.find(node.op()) == do_not_rewrite_ops.end(); } string DependencyOptimizer::TryOptimizeDependencies( NodeDef* node, GraphDef* graph, std::vector<NodeDef*>* new_nodes) { // Change ops that only have control dependencies as outputs to NoOps. if (node->op() != "NoOp" && SafeToConvertToNoOp(*node)) { VLOG(2) << "***** Replacing " << node->name() << " (" << node->op() << ") with NoOp."; // The outputs of this node are not consumed. Replace its inputs with // control dependencies and replace the op itself with the NoOp op. for (int i = 0; i < node->input_size(); ++i) { const string& old_input = node->input(i); if (IsControlInput(old_input)) { continue; } const string ctrl_input = ConstantFolding::AddControlDependency( old_input, graph, node_map_.get()); node->set_input(i, ctrl_input); node_map_->UpdateInput(node->name(), old_input, ctrl_input); new_nodes->push_back(node_map_->GetNode(old_input)); } node->set_op("NoOp"); node->clear_attr(); new_nodes->push_back(node); return ""; } // Remove NoOp nodes if their fan-in or fan-out is less than 2. // The non-trivial rewrites take the following form: // // Case a) // x --^> +------+ x --^> +---+ // y --^> | NoOp | --^> a ==> y --^> | a | // ... | | ... | | // z --^> +------+ z --^> +---+ // // Case b) // +------+ --^> a +---+ --^> a // x --^> | NoOp | --^> b ==> | x | --^> b // | | ... | | ... // +------+ --^> c +---+ --^> c if (node->op() == "NoOp" && nodes_to_preserve_.find(node->name()) == nodes_to_preserve_.end()) { auto outputs = node_map_->GetOutputs(node->name()); const int num_outputs = outputs.size(); const int num_inputs = node->input_size(); if (num_inputs > 1 && num_outputs > 1) { return ""; } for (auto consumer : outputs) { for (int i = 0; i < num_inputs; ++i) { const string& input = node->input(i); // Forward dependencies from inputs to consumer if it doesn't already // depend on it. if (node_map_->GetOutputs(input).count(consumer) == 0) { consumer->add_input(ConstantFolding::AddControlDependency( input, graph, node_map_.get())); node_map_->AddOutput(NodeName(input), consumer->name()); } new_nodes->push_back(node_map_->GetNode(input)); } // Remove dependency on node from consumer. int pos = FindInputSlot(*consumer, AsControlDependency(node->name())); if (pos >= 0) { consumer->mutable_input()->SwapElements(pos, consumer->input_size() - 1); consumer->mutable_input()->RemoveLast(); node_map_->RemoveOutput(node->name(), consumer->name()); new_nodes->push_back(consumer); } } // Clear all control inputs to node. node_map_->RemoveInputs(node->name()); node->clear_input(); return ""; } return ""; } Status DependencyOptimizer::OptimizeDependencies(GraphDef* optimized_graph) { // TODO(rmlarsen,bsteiner): The folloing code is similar to the control loop // in the ArithmeticOptimizer. Dedup this. SetVector<NodeDef*> nodes_to_simplify; for (int i = 0; i < optimized_graph->node_size(); ++i) { const NodeDef& node = optimized_graph->node(i); if (node.op() == "NoOp" || SafeToConvertToNoOp(node)) { nodes_to_simplify.PushBack(optimized_graph->mutable_node()->Mutable(i)); } } while (!nodes_to_simplify.Empty()) { NodeDef* node = nodes_to_simplify.PopBack(); std::vector<NodeDef*> new_nodes; const string simplified_tensor = TryOptimizeDependencies(node, optimized_graph, &new_nodes); if (simplified_tensor.empty()) { continue; } if (NodeName(simplified_tensor) != node->name()) { // Always consider simplified_tensor for further optimizations. NodeDef* simplified_node = node_map_->GetNode(simplified_tensor); if (simplified_node != nullptr) { nodes_to_simplify.PushBack(simplified_node); } // When `node` is simplifed to another node rather than in-place, the // consumers of `node` are already redirected to `simplified_tensor`. // Re-push the consumers into `nodes_to_simplify` for further // optimizations. std::set<NodeDef*> consumers = node_map_->GetOutputs(node->name()); for (NodeDef* consumer : consumers) { // Update `consumer`'s use of `node` to `input`'s operand. for (int i = 0; i < consumer->input_size(); ++i) { int operand_pos; string operand_node_name = ParseNodeName(consumer->input(i), &operand_pos); if (operand_node_name == node->name()) { *consumer->mutable_input(i) = (operand_pos < 0 ? AsControlDependency(NodeName(simplified_tensor)) : simplified_tensor); } VLOG(2) << "Update input " << consumer->input(i) << " of " << consumer->name() << " to " << simplified_tensor; } node_map_->UpdateInput(consumer->name(), node->name(), simplified_tensor); nodes_to_simplify.PushBack(consumer); } } for (auto new_node : new_nodes) { nodes_to_simplify.PushBack(new_node); } } return Status::OK(); } Status DependencyOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item, GraphDef* optimized_graph) { *optimized_graph = item.graph; nodes_to_preserve_ = item.NodesToPreserve(); node_map_.reset(new NodeMap(optimized_graph)); has_fetch_ = !item.fetch.empty(); VLOG(2) << "Graph before optimization:\n" << optimized_graph->DebugString(); TF_RETURN_IF_ERROR(OptimizeDependencies(optimized_graph)); VLOG(2) << "Graph after optimization:\n" << optimized_graph->DebugString(); return Status::OK(); } void DependencyOptimizer::Feedback(Cluster* /*cluster*/, const GrapplerItem& /*item*/, const GraphDef& /*optimized_graph*/, double /*result*/) { // Nothing to do for DependencyOptimizer. } } // end namespace grappler } // end namespace tensorflow
36.555556
80
0.622414
[ "vector" ]
49f761a7fa42b810510e8c3d11d1930a6e1d0976
3,905
cpp
C++
src/Testbench.cpp
spcl/stencil_hls
a1274256b40c670115bbc18eb088114232db0506
[ "BSD-3-Clause" ]
6
2020-02-07T09:52:00.000Z
2022-03-15T22:11:13.000Z
src/Testbench.cpp
spcl/stencil_hls
a1274256b40c670115bbc18eb088114232db0506
[ "BSD-3-Clause" ]
null
null
null
src/Testbench.cpp
spcl/stencil_hls
a1274256b40c670115bbc18eb088114232db0506
[ "BSD-3-Clause" ]
2
2021-02-16T15:51:45.000Z
2021-06-19T02:45:48.000Z
/// @author Johannes de Fine Licht (definelicht@inf.ethz.ch) /// @copyright This software is copyrighted under the BSD 3-Clause License. #include "Stencil.h" #include "Reference.h" #include <algorithm> // std::copy #include <cmath> // std::fabs #include <iostream> #include <vector> bool Verify(std::vector<Data_t> const &reference, std::vector<Memory_t> const &test) { const int offset = (kTimeFolded % 2 == 0) ? 0 : kTotalElementsMemory; // int correct = 0; // int mismatches = 0; for (int r = 0; r < kRows; ++r) { for (int c = 0; c < kBlockWidthMemory * kBlocks; ++c) { const int index = r * kBlockWidthMemory * kBlocks + c; for (int k = 0; k < kKernelPerMemory; ++k) { const Kernel_t elem = test[offset + index][k]; for (int w = 0; w < kKernelWidth; ++w) { const auto expected = reference[kMemoryWidth * index + kKernelWidth * k + w]; const auto actual = elem[w]; auto diff = expected - actual; diff = (diff < 0) ? Data_t(-diff) : Data_t(diff); if (diff > 1e-4) { std::cerr << "Mismatch at (" << r << ", " << c * kMemoryWidth + k * kKernelWidth + w << "): " << actual << " (should be " << expected << ")" << std::endl; // ++mismatches; return false; } else { // std::cout << "Correct at (" << r << ", " // << c * kMemoryWidth + k * kKernelWidth + w // << "): " << elem[w] << "\n"; // ++correct; } } } } } // std::cout << "Correct: " << correct << "\nMismatches: " << mismatches // << std::endl; return true; } int main() { std::cout << "Running reference implementation..." << std::flush; const auto reference = Reference(std::vector<Data_t>(kRows * kCols, 0)); std::cout << " Done." << std::endl; std::cout << "Initializing memory..." << std::flush; std::vector<Memory_t> memory(2 * kTotalElementsMemory, Kernel_t(Data_t(static_cast<Data_t>(0)))); std::vector<Memory_t> memorySplit(2 * kTotalElementsMemory, Kernel_t(Data_t(static_cast<Data_t>(0)))); std::vector<Memory_t> memorySplit0(kTotalElementsMemory, Kernel_t(Data_t(static_cast<Data_t>(0)))); std::vector<Memory_t> memorySplit1(kTotalElementsMemory, Kernel_t(Data_t(static_cast<Data_t>(0)))); std::cout << " Done." << std::endl; std::cout << "Running single memory implementation..." << std::flush; Jacobi(memory.data(), memory.data()); std::cout << " Done." << std::endl; std::cout << "Running dual memory implementation..." << std::flush; JacobiTwoDimms(memorySplit0.data(), memorySplit0.data(), memorySplit1.data(), memorySplit1.data()); std::cout << " Done." << std::endl; std::cout << "Reassembling memory..." << std::flush; for (int rIn = 0, rOut = 0; rOut < kRows; ++rIn, rOut += 2) { static constexpr auto kMemoryCols = kCols / kMemoryWidth; const auto iStart = rIn * kMemoryCols; std::copy(memorySplit0.begin() + iStart, memorySplit0.begin() + iStart + kMemoryCols, memorySplit.begin() + rOut * kMemoryCols); std::copy(memorySplit1.begin() + iStart, memorySplit1.begin() + iStart + kMemoryCols, memorySplit.begin() + (rOut + 1) * kMemoryCols); } std::cout << " Done." << std::endl; std::cout << "Verifying single memory..." << std::flush; if (!Verify(reference, memory)) { return 1; } std::cout << " Done." << std::endl; std::cout << "Verifying dual memory..." << std::flush; if (!Verify(reference, memorySplit)) { return 1; } std::cout << " Done." << std::endl; return 0; }
38.284314
79
0.542894
[ "vector" ]
49fe9d6407b8c4e73ce50d1f2ae1958bba767bfe
5,269
cpp
C++
p1/src/project.cpp
goncaloinunes/asa
cefb161741eec50ff060d8182e8a41fc5ad83dc4
[ "MIT" ]
null
null
null
p1/src/project.cpp
goncaloinunes/asa
cefb161741eec50ff060d8182e8a41fc5ad83dc4
[ "MIT" ]
null
null
null
p1/src/project.cpp
goncaloinunes/asa
cefb161741eec50ff060d8182e8a41fc5ad83dc4
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <sstream> #include <string> #include <climits> #include <unordered_map> #include <algorithm> #define ull unsigned long long #define ll long long using namespace std; void readSequenceToVector(vector<int>& vec) { int number; string line; getline(cin >> ws, line); istringstream iss(line); while(iss >> number) { vec.push_back(number); } } // Time Complexity: O(N) void removeConsecutiveDuplicates(vector<int>& vet, unordered_map<int, int>& m) { int last = INT_MAX; ull k = 0; for (ull i = 0; i < vet.size(); i++) { if(m.find(vet[i]) == m.end()) // if m.find(x) == m.end() then x is not in the map yet m[vet[i]] = 1; // inserting vet[i] into the map else if(vet[i] == last) // if vet[i] == last it's a consecutive duplicate continue; vet[k++] = vet[i]; // add element and increase number of elements last = vet[i]; // update last element seen } vet.resize(k); // resize vet with number of elements not duplicated } // Time Complexity: O(N), where N equals max(v1.size(), v2.size()) void removeUncommonElements(vector<int>& v1, vector<int>& v2, unordered_map<int, int>& m1, unordered_map<int, int>& m2) { ull k = 0; for(ull i = 0; i < v1.size(); i++) // for every element in v1 if(m2.find(v1[i]) != m2.end()) // check if element is in m2 v1[k++] = v1[i]; // add element and increase number of elements v1.resize(k); // resize v1 with number of v1 elements in m2 k = 0; for(ull i = 0; i < v2.size(); i++) if(m1.find(v2[i]) != m1.end()) v2[k++] = v2[i]; v2.resize(k); } // Time Complexity: O(N) // Space Complexity: O(N) // Removes sequecial duplicates and uncommon elements in both sequences void preprocessSequences(vector<int>& s1, vector<int>& s2) { unordered_map<int, int> m1, m2; // builds the unordered_map while removing consecutive duplicates removeConsecutiveDuplicates(s1, m1); removeConsecutiveDuplicates(s2, m2); removeUncommonElements(s1, s2, m1, m2); } pair<ll, ll> findNumberAndLengthOfLIS(int* sequence, ll size) { ll maxLength = 0, subsequenceCount = 0; vector<ll> lengths(size, 1); vector<ll> counts(size, 1); vector<int> sorted(size); copy(sequence, sequence + size, begin(sorted)); sort(begin(sorted), end(sorted)); for(ll i = 0; i < size; i++) { ll j = i - 1; // ignore all the first previous elements bigger or equal to sequence[i] for(; j >= 0; j--) { if(sequence[j] < sequence[i]) break; } // find the previous element of sequence[i] in sorted sequence ll current_idx = lower_bound(sorted.begin(), sorted.end(), sequence[i]) - sorted.begin(); int previous = sorted[current_idx - 1]; // update current length, length[i] for(ll k = j; k >= 0; k--) { if(lengths[k] >= lengths[i] && sequence[k] < sequence[i]) { lengths[i] = lengths[k] + 1; counts[i] = counts[k]; j = k; // update position // if current == previous we don't need to continue searching if(sequence[k] == previous) break; } } // find how many paths we can take to reach the current length for(j--; j >= 0; j--) { if(lengths[j] == lengths[i] - 1 && sequence[j] < sequence[i]) counts[i] += counts[j]; } // update maxLength and subsequenceCount if (maxLength < lengths[i]) { maxLength = lengths[i]; subsequenceCount = counts[i]; } else if (maxLength == lengths[i]) subsequenceCount += counts[i]; } return pair<ll, ll>(maxLength, subsequenceCount); } ull findLengthOfLCIS(vector<int>& seq1, vector<int>& seq2) { vector<ull> lengths(seq2.size(), 0); ull currentLength, maxLength = 0; for(ull i = 0; i < seq1.size(); i++) { currentLength = 0; for(ull j = 0; j < seq2.size(); j++) { if(seq1[i] > seq2[j] && lengths[j] > currentLength) currentLength = lengths[j]; else if(seq1[i] == seq2[j]) { lengths[j] = currentLength + 1; // update maxLength if(lengths[j] > maxLength) maxLength = lengths[j]; } } } return maxLength; } void handleFirstProblem() { vector<int> sequence; pair<ll, ll> result; readSequenceToVector(sequence); result = findNumberAndLengthOfLIS(&(sequence[0]), sequence.size()); cout << result.first << " " << result.second << endl; } void handleSecondProblem() { vector<int> sequence1, sequence2; readSequenceToVector(sequence1); readSequenceToVector(sequence2); preprocessSequences(sequence1, sequence2); cout << findLengthOfLCIS(sequence1, sequence2) << endl; } int main() { int problem; cin >> problem; if(problem == 1) handleFirstProblem(); else if (problem == 2) handleSecondProblem(); return 0; }
27.300518
121
0.565193
[ "vector" ]
8e654395574bf954cbc4e700218aed614c2d5c3e
22,002
cpp
C++
Shizuku/Window.cpp
blackoffee/Shizuku
dde4c4f437ca271181d59a78da2815dee01800eb
[ "MIT" ]
15
2018-12-17T14:17:12.000Z
2022-01-21T16:21:44.000Z
Shizuku/Window.cpp
blackoffee/InteractiveCFD
dde4c4f437ca271181d59a78da2815dee01800eb
[ "MIT" ]
1
2019-03-03T18:01:11.000Z
2019-03-03T18:20:13.000Z
Shizuku/Window.cpp
blackoffee/InteractiveCFD
dde4c4f437ca271181d59a78da2815dee01800eb
[ "MIT" ]
4
2017-03-14T21:38:46.000Z
2018-09-20T14:45:26.000Z
#include "../imgui/imgui.h" #include "../imgui/imgui_impl_glfw.h" #include "Window.h" #include "../imgui/imgui_impl_opengl3.h" #include "Shizuku.Flow/Command/Zoom.h" #include "Shizuku.Flow/Command/Pan.h" #include "Shizuku.Flow/Command/Rotate.h" #include "Shizuku.Flow/Command/AddObstruction.h" #include "Shizuku.Flow/Command/MoveObstruction.h" #include "Shizuku.Flow/Command/PreSelectObstruction.h" #include "Shizuku.Flow/Command/AddPreSelectionToSelection.h" #include "Shizuku.Flow/Command/TogglePreSelection.h" #include "Shizuku.Flow/Command/DeleteSelectedObstructions.h" #include "Shizuku.Flow/Command/ClearSelection.h" #include "Shizuku.Flow/Command/PauseSimulation.h" #include "Shizuku.Flow/Command/PauseRayTracing.h" #include "Shizuku.Flow/Command/SetSimulationScale.h" #include "Shizuku.Flow/Command/SetTimestepsPerFrame.h" #include "Shizuku.Flow/Command/SetInletVelocity.h" #include "Shizuku.Flow/Command/SetContourMode.h" #include "Shizuku.Flow/Command/SetContourMinMax.h" #include "Shizuku.Flow/Command/SetSurfaceShadingMode.h" #include "Shizuku.Flow/Command/SetWaterDepth.h" #include "Shizuku.Flow/Command/RestartSimulation.h" #include "Shizuku.Flow/Command/SetFloorWireframeVisibility.h" #include "Shizuku.Flow/Command/SetLightProbeVisibility.h" #include "Shizuku.Flow/Command/SetToTopView.h" #include "Shizuku.Flow/Command/ProbeLightPaths.h" #include "Shizuku.Flow/Command/Parameter/VelocityParameter.h" #include "Shizuku.Flow/Command/Parameter/ScaleParameter.h" #include "Shizuku.Flow/Command/Parameter/ModelSpacePointParameter.h" #include "Shizuku.Flow/Command/Parameter/ScreenPointParameter.h" #include "Shizuku.Flow/Command/Parameter/MinMaxParameter.h" #include "Shizuku.Flow/Command/Parameter/DepthParameter.h" #include "Shizuku.Flow/Command/Parameter/VisibilityParameter.h" #include "Shizuku.Flow/Query.h" #include "Shizuku.Flow/Flow.h" #include "Shizuku.Flow/TimerKey.h" #include "Shizuku.Core/Ogl/Ogl.h" #include "Shizuku.Core/Ogl/Shader.h" #include <GLFW/glfw3.h> #include <boost/any.hpp> #include <boost/none.hpp> #include <iostream> #include <typeinfo> #include <memory> using namespace Shizuku::Presentation; using namespace Shizuku::Flow; namespace { void ResizeWrapper(GLFWwindow* window, int width, int height) { Window::Instance().Resize(Rect<int>(width, height)); } void MouseButtonWrapper(GLFWwindow* window, int button, int state, int mods) { Window::Instance().MouseButton(button, state, mods); } void MouseMotionWrapper(GLFWwindow* window, double x, double y) { Window::Instance().MouseMotion(x, y); } void MouseWheelWrapper(GLFWwindow* window, double xwheel, double ywheel) { Window::Instance().MouseWheel(xwheel, ywheel); } void KeyboardWrapper(GLFWwindow* window, int key, int scancode, int action, int mode) { Window::Instance().Keyboard(key, scancode, action, mode); } void GLAPIENTRY MessageCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) { printf( "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n", ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ), type, severity, message ); } const char* MakeReadableString(const ContourMode contour) { switch (contour) { case ContourMode::VelocityMagnitude: return "Velocity.mag"; case ContourMode::VelocityU: return "Velocity.u"; case ContourMode::VelocityV: return "Velocity.v"; case ContourMode::Pressure: return "Pressure"; case ContourMode::StrainRate: return "Strain Rate"; case ContourMode::Water: return "Water"; default: throw "Unexpected contour mode"; } } const char* MakeReadableString(const SurfaceShadingMode p_shadingMode) { switch (p_shadingMode) { case SurfaceShadingMode::RayTracing: return "Ray Tracing"; case SurfaceShadingMode::SimplifiedRayTracing: return "Simplified Ray Tracing"; case SurfaceShadingMode::Phong: return "Phong"; default: throw "Unexpected contour mode"; } } namespace TimeHistoryProviders{ static float SolveFluid(void* data, int i) { return TimeHistory::Instance(TimerKey::SolveFluid).DataProvider(data, i); } static float PrepareFloor(void* data, int i) { return TimeHistory::Instance(TimerKey::PrepareFloor).DataProvider(data, i); } static float PrepareSurf(void* data, int i) { return TimeHistory::Instance(TimerKey::PrepareSurface).DataProvider(data, i); } static float ProcessFloor(void* data, int i) { return TimeHistory::Instance(TimerKey::ProcessFloor).DataProvider(data, i); } static float ProcessSurf(void* data, int i) { return TimeHistory::Instance(TimerKey::ProcessSurface).DataProvider(data, i); } } void CreateHistoryPlotLines(Query& p_query, const TimerKey p_key, const char* p_label) { const double time = p_query.GetTime(p_key); TimeHistory::Instance(p_key).Append(time); float(*provider) (void*, int) = NULL; switch (p_key) { case TimerKey::SolveFluid: provider = TimeHistoryProviders::SolveFluid; break; case TimerKey::PrepareSurface: provider = TimeHistoryProviders::PrepareSurf; break; case TimerKey::PrepareFloor: provider = TimeHistoryProviders::PrepareFloor; break; case TimerKey::ProcessSurface: provider = TimeHistoryProviders::ProcessSurf; break; case TimerKey::ProcessFloor: provider = TimeHistoryProviders::ProcessFloor; break; default: throw "Unexpected TimerKey"; } const MinMax<double> minMax = TimeHistory::Instance(p_key).MinMax(); char timeStr[64]; sprintf_s(timeStr, "%f", time); const int chartHeight = 64; ImGui::PlotLines(p_label, provider, NULL, (TimeHistory::Instance(p_key).Size()), 0, timeStr, minMax.Min, minMax.Max, ImVec2(0, chartHeight)); } float ScaleFromResolution(const float p_res) { return -2.f*p_res + 3.f; } } Window::Window() : m_resolution(0.5f), m_velocity(0.06f), m_timesteps(10), m_contourMode(ContourMode::Water), m_firstUIDraw(true), m_contourMinMax(0.0f, 1.0f), m_depth(0.5f), m_paused(false), m_diagEnabled(false), //m_history(20), m_shadingMode(SurfaceShadingMode::RayTracing) { } void Window::SetGraphics(std::shared_ptr<Shizuku::Flow::Flow> flow) { m_flow = flow; m_query = std::make_shared<Query>(*flow); } void Window::RegisterCommands() { m_zoom = std::make_shared<Zoom>(*m_flow); m_pan = std::make_shared<Pan>(*m_flow); m_rotate = std::make_shared<Rotate>(*m_flow); m_addObstruction = std::make_shared<AddObstruction>(*m_flow); m_moveObstruction = std::make_shared<MoveObstruction>(*m_flow); m_preSelectObst = std::make_shared<PreSelectObstruction>(*m_flow); m_addPreSelectionToSelection = std::make_shared<AddPreSelectionToSelection>(*m_flow); m_deleteSelectedObstructions = std::make_shared<DeleteSelectedObstructions>(*m_flow); m_togglePreSelection = std::make_shared<TogglePreSelection>(*m_flow); m_clearSelection = std::make_shared<ClearSelection>(*m_flow); m_pauseSimulation = std::make_shared<PauseSimulation>(*m_flow); m_pauseRayTracing = std::make_shared<PauseRayTracing>(*m_flow); m_restartSimulation = std::make_shared<RestartSimulation>(*m_flow); m_setSimulationScale = std::make_shared<SetSimulationScale>(*m_flow); m_timestepsPerFrame = std::make_shared<SetTimestepsPerFrame>(*m_flow); m_setVelocity = std::make_shared<SetInletVelocity>(*m_flow); m_setContourMode = std::make_shared<SetContourMode>(*m_flow); m_setContourMinMax = std::make_shared<SetContourMinMax>(*m_flow); m_setSurfaceShadingMode = std::make_shared<SetSurfaceShadingMode>(*m_flow); m_setDepth = std::make_shared<SetWaterDepth>(*m_flow); m_setFloorWireframeVisibility = std::make_shared<SetFloorWireframeVisibility>(*m_flow); m_setLightProbeVisibility = std::make_shared<SetLightProbeVisibility>(*m_flow); m_setToTopView = std::make_shared<SetToTopView>(*m_flow); m_probeLightPaths = std::make_shared<ProbeLightPaths>(*m_flow); } void Window::ApplyInitialFlowSettings() { m_setSimulationScale->Start(boost::any(ScaleParameter(ScaleFromResolution(m_resolution)))); m_timestepsPerFrame->Start(m_timesteps); m_setVelocity->Start(boost::any(VelocityParameter(m_velocity))); m_setContourMode->Start(m_contourMode); m_setSurfaceShadingMode->Start(m_shadingMode); m_setDepth->Start(boost::any(DepthParameter(m_depth))); //TODO: need mode switching m_preSelectObst->Start(boost::none); } void Window::InitializeImGui() { IMGUI_CHECKVERSION(); ImGui::CreateContext(); const char* glsl_version = "#version 430 core"; ImGui_ImplGlfw_InitForOpenGL(m_window, true); ImGui_ImplOpenGL3_Init(glsl_version); ImGui::StyleColorsDark(); } void Window::RegisterGlfwInputs() { //glfw is in C so cannot bind instance method... glfwSetKeyCallback(m_window, KeyboardWrapper); glfwSetWindowSizeCallback(m_window, ResizeWrapper); glfwSetCursorPosCallback(m_window, MouseMotionWrapper); glfwSetMouseButtonCallback(m_window, MouseButtonWrapper); glfwSetScrollCallback(m_window, MouseWheelWrapper); } void Window::Resize(GLFWwindow* window, int width, int height) { Resize(Rect<int>(width, height)); } void Window::Resize(const Rect<int>& size) { m_size = size; m_flow->Resize(size); } void Window::EnableDebug() { m_debug = true; } void Window::EnableDiagnostics() { m_diagEnabled = true; } void Window::MouseButton(const int button, const int state, const int mod) { if (m_imguiHandlingMouseEvent) return; double x, y; glfwGetCursorPos(m_window, &x, &y); const Types::Point<int> screenPos(x, m_size.Height - 1 - y); const ScreenPointParameter param(screenPos); if (button == GLFW_MOUSE_BUTTON_MIDDLE && state == GLFW_PRESS && mod == GLFW_MOD_CONTROL) { m_pan->Start(param); m_probeLightPaths->End(boost::none); } else if (button == GLFW_MOUSE_BUTTON_MIDDLE && state == GLFW_PRESS) { m_rotate->Start(param); m_probeLightPaths->End(boost::none); } else if (button == GLFW_MOUSE_BUTTON_RIGHT && state == GLFW_PRESS) { m_addObstruction->Start(ModelSpacePointParameter(m_query->ProbeModelSpaceCoord(screenPos))); m_probeLightPaths->End(boost::none); } else if (button == GLFW_MOUSE_BUTTON_LEFT && state == GLFW_PRESS) { m_probeLightPaths->End(boost::none); if (mod == GLFW_MOD_CONTROL) { m_togglePreSelection->Start(boost::none); } else { if (m_query->PreSelectedObstructionCount() == 0) { m_clearSelection->Start(boost::none); } else { const boost::optional<const Info::ObstInfo> info = m_query->ObstInfo(screenPos); if (info.is_initialized()) { if (!info.value().Selected) { m_clearSelection->Start(boost::none); m_addPreSelectionToSelection->Start(boost::none); } m_moveObstruction->Start(param); } } } } else { m_pan->End(boost::none); m_rotate->End(boost::none); m_moveObstruction->End(boost::none); m_probeLightPaths->Start(boost::none); } } void Window::MouseMotion(const int x, const int y) { const ScreenPointParameter param(Types::Point<int>(x, m_size.Height - 1 - y)); m_pan->Track(param); m_rotate->Track(param); m_moveObstruction->Track(param); m_preSelectObst->Track(param); m_probeLightPaths->Track(param); } void Window::MouseWheel(double xwheel, double ywheel) { double x, y; glfwGetCursorPos(m_window, &x, &y); const int dir = ywheel > 0 ? 1 : 0; m_zoom->Start(dir, 0.6f); } void Window::Keyboard(int key, int scancode, int action, int mode) { switch (key) { case GLFW_KEY_SPACE: if (action == GLFW_PRESS) TogglePaused(); break; case GLFW_KEY_DELETE: if (action == GLFW_PRESS) m_deleteSelectedObstructions->Start(boost::none); } } void Window::TogglePaused() { m_paused = !m_paused; m_pauseSimulation->Start(boost::any(bool(m_paused))); } void Window::UpdateWindowTitle(const float fps, const Rect<int> &domainSize, const int tSteps) { char fpsReport[256]; const int xDim = domainSize.Width; const int yDim = domainSize.Height; sprintf_s(fpsReport, "Shizuku Flow running at: %i timesteps/frame at %3.1f fps = %3.1f timesteps/second on %ix%i mesh", tSteps, fps, m_timesteps*fps, xDim, yDim); glfwSetWindowTitle(m_window, fpsReport); } void Window::Draw3D() { m_fpsTracker.Tick(); m_flow->Update(); m_flow->SetUpFrame(); m_flow->Draw3D(); m_fpsTracker.Tock(); UpdateWindowTitle(m_fpsTracker.GetFps(), m_query->SimulationDomain(), m_timesteps); } void Window::InitializeGlfw() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); GLFWwindow* window = glfwCreateWindow(m_size.Width, m_size.Height, "Shizuku", nullptr, nullptr); glfwMakeContextCurrent(window); m_window = window; glewExperimental = GL_TRUE; glewInit(); if (m_debug) { glEnable ( GL_DEBUG_OUTPUT ); glDebugMessageCallback(MessageCallback, 0); } } void Window::DrawUI() { ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); ImGui::PushStyleVar(ImGuiStyleVar_GrabRounding, 3.0f); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGuiIO& io = ImGui::GetIO(); m_imguiHandlingMouseEvent = io.WantCaptureMouse; if (m_firstUIDraw) { ImGui::SetNextWindowSize(ImVec2(350,350)); ImGui::SetNextWindowPos(ImVec2(5,5)); //! HACK - Adding obst has to happen after lbm dimensions are set. Need to split up Flow initilization sequence m_addObstruction->Start(ModelSpacePointParameter(Point<float>(-0.2f, 0.2f))); m_addObstruction->Start(ModelSpacePointParameter(Point<float>(-0.1f, -0.3f))); } ImGui::Begin("Settings"); { const ContourMode contour = m_contourMode; const char* currentItem = MakeReadableString(contour); if (ImGui::BeginCombo("Contour Mode", currentItem)) { for (int i = 0; i < static_cast<int>(ContourMode::NUMB_CONTOUR_MODE); ++i) { const ContourMode contourItem = static_cast<ContourMode>(i); bool isSelected = (contourItem == contour); if (ImGui::Selectable(MakeReadableString(contourItem), isSelected)) { currentItem = MakeReadableString(contourItem); m_contourMode = contourItem; } if (isSelected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } if (contour != m_contourMode) m_setContourMode->Start(m_contourMode); if (m_contourMode != ContourMode::Water) { MinMax<float> maxRange; const char* format = "%.3f"; switch (m_contourMode){ case VelocityMagnitude: maxRange = MinMax<float>(0.f, 4.f*m_velocity); break; case VelocityU: maxRange = MinMax<float>(-1.5f*m_velocity, 4.f*m_velocity); break; case VelocityV: maxRange = MinMax<float>(-2.f*m_velocity, 2.f*m_velocity); break; case Pressure: maxRange = MinMax<float>(0.98f, 1.02f); break; case StrainRate: maxRange = MinMax<float>(0.f, 2.f*m_velocity*m_velocity); format = "%.5f"; break; } const MinMax<float> oldMinMax = m_contourMinMax; m_contourMinMax.Clamp(maxRange); float minMax[2] = { m_contourMinMax.Min, m_contourMinMax.Max }; ImGui::SliderFloat2("Contour Range", minMax, maxRange.Min, maxRange.Max, format); m_contourMinMax = MinMax<float>(minMax[0], minMax[1]); if (m_contourMinMax != oldMinMax) m_setContourMinMax->Start(boost::any(MinMaxParameter(m_contourMinMax))); } const float oldRes = m_resolution; ImGui::SliderFloat("Resolution", &m_resolution, 0.0f, 1.0f, "%.2f"); if (oldRes != m_resolution) m_setSimulationScale->Start(boost::any(ScaleParameter(ScaleFromResolution(m_resolution)))); const float oldTimesteps = m_timesteps; ImGui::SliderInt("Timesteps/Frame", &m_timesteps, 2, 30); if (oldTimesteps != m_timesteps) m_timestepsPerFrame->Start(m_timesteps); const float oldVel = m_velocity; ImGui::SliderFloat("Velocity", &m_velocity, 0.0f, 0.12f, "%.3f"); if (oldVel != m_velocity) m_setVelocity->Start(boost::any(VelocityParameter(m_velocity))); const float oldDepth = m_depth; ImGui::SliderFloat("Depth", &m_depth, 0.0f, 5.f, "%.2f"); if (oldDepth != m_depth) m_setDepth->Start(boost::any(DepthParameter(m_depth))); if (m_debug) { const SurfaceShadingMode shadingMode = m_shadingMode; const char* currentShadingItem = MakeReadableString(shadingMode); if (ImGui::BeginCombo("Shading Mode", currentShadingItem)) { for (int i = 0; i < static_cast<int>(SurfaceShadingMode::NUMB_SHADING_MODE); ++i) { const SurfaceShadingMode shadingItem = static_cast<SurfaceShadingMode>(i); bool isSelected = (shadingItem == shadingMode); if (ImGui::Selectable(MakeReadableString(shadingItem), isSelected)) { currentShadingItem = MakeReadableString(shadingItem); m_shadingMode = shadingItem; } if (isSelected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } if (shadingMode != m_shadingMode) m_setSurfaceShadingMode->Start(m_shadingMode); } ImGui::Spacing(); if (ImGui::Button("Restart simulation")) m_restartSimulation->Start(); const bool oldPaused = m_paused; if (ImGui::Checkbox("Pause simulation", &m_paused) && m_paused != oldPaused) m_pauseSimulation->Start(boost::any(bool(m_paused))); const bool oldRayTracingPaused = m_rayTracingPaused; if (ImGui::Checkbox("Pause ray tracing", &m_rayTracingPaused) && m_rayTracingPaused != oldRayTracingPaused) m_pauseRayTracing->Start(boost::any(bool(m_rayTracingPaused))); const bool oldFloorWireframe = m_floorWireframeVisible; if (ImGui::Checkbox("Show caustics mesh", &m_floorWireframeVisible) && m_floorWireframeVisible != oldFloorWireframe) m_setFloorWireframeVisibility->Start(boost::any(VisibilityParameter(m_floorWireframeVisible))); const bool oldLightProbe = m_lightProbeEnabled; if (ImGui::Checkbox("Probe caustics beams", &m_lightProbeEnabled) && m_lightProbeEnabled != oldLightProbe) m_setLightProbeVisibility->Start(boost::any(VisibilityParameter(m_lightProbeEnabled))); const bool oldToTopView = m_topViewMode; if (ImGui::Checkbox("Top view", &m_topViewMode) && m_topViewMode != oldToTopView) m_setToTopView->Start(boost::any(m_topViewMode)); } ImGui::End(); if (m_diagEnabled) { if (m_firstUIDraw) { ImGui::SetNextWindowSize(ImVec2(370,250)); ImGui::SetNextWindowPos(ImVec2(m_size.Width-370-5,5)); } ImGui::Begin("Diagnostics"); { CreateHistoryPlotLines(*m_query, TimerKey::SolveFluid, "Solve Fluid"); CreateHistoryPlotLines(*m_query, TimerKey::PrepareSurface, "Prepare Surface"); CreateHistoryPlotLines(*m_query, TimerKey::PrepareFloor, "Prepare Floor"); //CreateHistoryPlotLines(*m_query, TimerKey::ProcessSurface, "Process Surface"); //CreateHistoryPlotLines(*m_query, TimerKey::ProcessFloor, "Process Floor"); } ImGui::End(); } ImGui::Render(); int display_w, display_h; glfwMakeContextCurrent(m_window); glfwGetFramebufferSize(m_window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); m_firstUIDraw = false; } void Window::Display() { glClearColor(0.1f, 0.1f, 0.1f, 1.0f); while (!glfwWindowShouldClose(m_window)) { glfwPollEvents(); Draw3D(); DrawUI(); glfwSwapBuffers(m_window); } glfwTerminate(); }
34.92381
133
0.644941
[ "mesh", "render" ]
8e65894e0fdcb5895b541b8de1d97a3c74bcb55e
18,464
hpp
C++
plugins/pixel_plugin/include/eosio/pixel_plugin/protocol.hpp
ai-chen2050/eos
dd61ccde3c4273aef763abdfe1de21d59b7267d6
[ "MIT" ]
2
2018-10-23T14:30:10.000Z
2018-10-23T14:30:13.000Z
plugins/pixel_plugin/include/eosio/pixel_plugin/protocol.hpp
ai-chen2050/eos
dd61ccde3c4273aef763abdfe1de21d59b7267d6
[ "MIT" ]
null
null
null
plugins/pixel_plugin/include/eosio/pixel_plugin/protocol.hpp
ai-chen2050/eos
dd61ccde3c4273aef763abdfe1de21d59b7267d6
[ "MIT" ]
null
null
null
#pragma once #include <eosio/chain/types.hpp> #include <eosio/plugin_lib/plugin_lib.hpp> #include <eosio/chain/action.hpp> #include <regex> #include <string> #include <map> #include <eosio/wallet_plugin/wallet_plugin.hpp> #include <eosio/wallet_plugin/wallet_manager.hpp> #include <fc/static_variant.hpp> #include <fc/exception/exception.hpp> #include <fc/variant.hpp> #include <fc/io/json.hpp> #include <fc/crypto/private_key.hpp> #include <fc/crypto/public_key.hpp> namespace { namespace pixel_message_t { struct init{}; struct refresh{}; struct changedur{}; struct end{}; struct createacct{}; struct withdraw{}; struct clearpixels{}; struct clearaccts{}; struct clearcanvs{}; struct resetquota{}; struct dump_tables{}; struct transfer{}; struct create_system_acct{}; struct create_key{}; struct create_wallet{}; struct import_privkey{}; struct unlock_wallet{}; struct lock_wallet{}; }; } namespace eosio { struct async_result_visitor : public fc::visitor<std::string> { template<typename T> std::string operator()(const T& v) const { return fc::json::to_string(v); } }; #define PIXEL_SYNC_CALL(call_name)\ pixel_plugin::handle_exception(#call_name, fc::json::to_string(cmd), cb) #define PIXEL_ASYNC_CALL(call_name, call_result)\ [cb, &cmd](const fc::static_variant<fc::exception_ptr, call_result>& result){\ if (result.contains<fc::exception_ptr>()) {\ try {\ result.get<fc::exception_ptr>()->dynamic_rethrow_exception();\ } catch (...) {\ pixel_plugin::handle_exception(#call_name, fc::json::to_string(cmd), cb);\ }\ } else {\ cb(result.visit(async_result_visitor()));\ }\ } using response_callback = std::function<void(const string&)>; namespace cmd { const string init = "init"; const string refresh = "refresh"; const string changedur = "changedur"; const string end = "end"; const string createacct = "createacct"; const string withdraw = "withdraw"; const string clearpixels = "clearpixels"; const string clearaccts = "clearaccts"; const string clearcanvs = "clearcanvs"; const string resetquota = "resetquota"; const string dump_tables = "dump_tables"; const string transfer = "transfer"; const string create_key = "create_key"; const string create_system_acct = "create_system_acct"; const string create_wallet = "create_wallet"; const string import_privkey = "import_privkey"; const string unlock_wallet = "unlock_wallet"; const string lock_wallet = "lock_wallet"; const string unknow = "unknow"; } using namespace std; struct message_handle { virtual ~message_handle() {} message_handle() { contract_name = pixel_plugin::contract_name; } virtual bool handle_message(fc::variant& cmd, response_callback cb) { cb("{\"code\":\"500\",\"what\":\"unsupport type of message.\"}"); throw fc::exception(unspecified_exception_code, "pixel exception", "unknow type of message."); return false; }; static string contract_name; static string team_name; }; string message_handle::contract_name = "eospixels"; string message_handle::team_name = "magicsteam11"; template<typename T> struct pixel_message_handle: public message_handle {}; template<> struct pixel_message_handle<pixel_message_t::init>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello init." << endl; try{ plugin_lib::instance().push_action({contract_name}, contract_name, cmd::init, fc::variant{vector<string>{}}, PIXEL_ASYNC_CALL(init, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel init message error!!!"); PIXEL_SYNC_CALL(init); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::refresh>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello refresh." << endl; try{ plugin_lib::instance().push_action({team_name}, contract_name, cmd::refresh, fc::variant{vector<string>{}}, PIXEL_ASYNC_CALL(refresh, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel refresh message error!!!"); PIXEL_SYNC_CALL(refresh); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::changedur>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello changedur." << endl; try{ string duration = cmd["duration"].as_string(); fc::variant action_args_var{vector<string>{duration}}; plugin_lib::instance().push_action({team_name}, contract_name, cmd::changedur, action_args_var, PIXEL_ASYNC_CALL(changedur, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel changedur message error!!!"); PIXEL_SYNC_CALL(changedur); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::end>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello end." << endl; try{ string account_name = cmd["account_name"].as_string(); fc::variant action_args_var{vector<string>{account_name}}; plugin_lib::instance().push_action({account_name}, contract_name, cmd::end, action_args_var, PIXEL_ASYNC_CALL(end, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel end message error!!!"); PIXEL_SYNC_CALL(end); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::createacct>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello createacct." << endl; try{ string account_name = cmd["account_name"].as_string(); fc::variant action_args_var{vector<string>{account_name}}; plugin_lib::instance().push_action({account_name}, contract_name, cmd::createacct, action_args_var, PIXEL_ASYNC_CALL(createacct, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel createacct message error!!!"); PIXEL_SYNC_CALL(createacct); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::withdraw>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello withdraw." << endl; try{ string account_name = cmd["account_name"].as_string(); fc::variant action_args_var{vector<string>{account_name}}; plugin_lib::instance().push_action({account_name}, contract_name, cmd::withdraw, action_args_var, PIXEL_ASYNC_CALL(withdraw, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel withdraw message error!!!"); PIXEL_SYNC_CALL(withdraw); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::clearpixels>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello clearpixels." << endl; try{ string count = cmd["count"].as_string(); string nonce = cmd["nonce"].as_string(); fc::variant action_args_var{vector<string>{count, nonce}}; plugin_lib::instance().push_action({team_name}, contract_name, cmd::clearpixels, action_args_var, PIXEL_ASYNC_CALL(clearpixels, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(clearpixels); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::clearaccts>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello clearaccts." << endl; try{ string count = cmd["count"].as_string(); string nonce = cmd["nonce"].as_string(); fc::variant action_args_var{vector<string>{count, nonce}}; plugin_lib::instance().push_action({team_name}, contract_name, cmd::clearaccts, action_args_var, PIXEL_ASYNC_CALL(clearaccts, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel clearaccts message error!!!"); PIXEL_SYNC_CALL(clearaccts); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::clearcanvs>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello clearcanvs." << endl; try{ string count = cmd["count"].as_string(); string nonce = cmd["nonce"].as_string(); fc::variant action_args_var{vector<string>{count, nonce}}; plugin_lib::instance().push_action({team_name}, contract_name, cmd::clearcanvs, action_args_var, PIXEL_ASYNC_CALL(clearcanvs, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel clearcanvs message error!!!"); PIXEL_SYNC_CALL(clearcanvs); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::resetquota>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello resetquota." << endl; try{ plugin_lib::instance().push_action({team_name}, contract_name, cmd::resetquota, fc::variant{vector<string>{}}, PIXEL_ASYNC_CALL(resetquota, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel resetquota message error!!!"); PIXEL_SYNC_CALL(resetquota); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::dump_tables>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello dump_tables." << endl; try{ auto ret = plugin_lib::instance().get_table(cmd.as<chain_apis::read_only::get_table_rows_params>()); cb(fc::json::to_string(ret)); } catch( const fc::exception& e ) { elog( "pixel dump_tables message error!!!"); PIXEL_SYNC_CALL(dump_tables); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::transfer>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello transfer." << endl; try{ string from = cmd["from"].as_string(); string to = cmd["to"].as_string(); string quantity = cmd["quantity"].as_string(); string referrer = cmd["referrer"].as_string(); const auto& pixels = cmd["pixels"].get_array(); string memo; for(const auto& pixel : pixels) memo.append(pixel.as_string()+","); if(!pixels.empty()) memo.erase(memo.end()-1); if(!referrer.empty()) memo.append(string(";") + referrer); fc::variant action_args_var{vector<string>{from, to, quantity, memo}}; plugin_lib::instance().push_action({from}, "eosio.token", cmd::transfer, action_args_var, PIXEL_ASYNC_CALL(transfer, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(transfer); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::create_key>: public message_handle { using public_key_type = fc::crypto::public_key; using private_key_type = fc::crypto::private_key; bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello create_key." << endl; try{ auto pk = private_key_type::generate(); auto privs = string(pk); auto pubs = string(pk.get_public_key()); string resp_key = string("{\"code\":\"0\",\"type\":\"create_key\",\"Public_key\":\"") + pubs + string("\",") + string("\"Private_key\":\"") + privs + string("\"}"); std::cout << resp_key <<std::endl; cb(resp_key); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(create_key); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::create_system_acct>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello create_system_acct." << endl; try{ string creator = cmd["creator"].as_string(); string permission = cmd["permission"].as_string(); if (! permission.empty()) { creator = permission; } plugin_lib::instance().create_account({creator}, fc::variant(cmd), PIXEL_ASYNC_CALL(create_system_acct, chain_apis::read_write::push_transaction_results)); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(create_system_acct); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::create_wallet>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello create_wallet." << endl; try{ string name = cmd["wallet_name"].as_string(); const auto& v = plugin_lib::instance().create_wallet(name); string priv_key = v.get_string(); string ret = string("{\"type\":\"create_wallet\",\"wallet_name\":\"") + name + string("\",") + string("\"Wallet_key\":\"") + priv_key + string("\"}"); cb(ret); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(create_wallet); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::import_privkey>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello import_privkey." << endl; try{ string name = cmd["wallet_name"].as_string(); string wallet_key_str = cmd["priv_key"].as_string(); plugin_lib::instance().import_privkey(name,wallet_key_str); string resp_key = string("{\"code\":\"0\",\"type\":\"import_privkey\",\"wallet_name\":\"") + name + string("\",") + string("\"memoInfo\":\"") + string("import success") + string("\"}"); cb(resp_key); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(import_privkey); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::unlock_wallet>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello unlock_wallet." << endl; try{ string name = cmd["wallet_name"].as_string(); string wallet_key_str = cmd["priv_key"].as_string(); plugin_lib::instance().unlock_wallet(name,wallet_key_str); string resp_key = string("{\"code\":\"0\",\"type\":\"unlock_wallet\",\"wallet_name\":\"") + name + string("\",") + string("\"memoInfo\":\"") + string("unlock success") + string("\"}"); cb(resp_key); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(unlock_wallet); return false; } return true; } }; template<> struct pixel_message_handle<pixel_message_t::lock_wallet>: public message_handle { bool handle_message(fc::variant& cmd, response_callback cb) { cout << "hello lock_wallet." << endl; try{ string name = cmd["wallet_name"].as_string(); plugin_lib::instance().lock_wallet(name); string resp_key = string("{\"code\":\"0\",\"type\":\"lock_wallet\",\"wallet_name\":\"") + name + string("\",") + string("\"memoInfo\":\"") + string("lock success") + string("\"}"); cb(resp_key); } catch( const fc::exception& e ) { elog( "pixel message error!!!"); PIXEL_SYNC_CALL(lock_wallet); return false; } return true; } }; message_handle* get_pixel_message_handle(const string&& s) { static map<string, message_handle*> handle = { {cmd::init, new pixel_message_handle<pixel_message_t::init>()}, {cmd::refresh, new pixel_message_handle<pixel_message_t::refresh>()}, {cmd::changedur, new pixel_message_handle<pixel_message_t::changedur>()}, {cmd::end, new pixel_message_handle<pixel_message_t::end>()}, {cmd::createacct, new pixel_message_handle<pixel_message_t::createacct>()}, {cmd::withdraw, new pixel_message_handle<pixel_message_t::withdraw>()}, {cmd::clearpixels, new pixel_message_handle<pixel_message_t::clearpixels>()}, {cmd::clearaccts, new pixel_message_handle<pixel_message_t::clearaccts>()}, {cmd::clearcanvs, new pixel_message_handle<pixel_message_t::clearcanvs>()}, {cmd::resetquota, new pixel_message_handle<pixel_message_t::resetquota>()}, {cmd::dump_tables, new pixel_message_handle<pixel_message_t::dump_tables>()}, {cmd::transfer, new pixel_message_handle<pixel_message_t::transfer>()}, {cmd::create_key, new pixel_message_handle<pixel_message_t::create_key>()}, {cmd::create_system_acct, new pixel_message_handle<pixel_message_t::create_system_acct>()}, {cmd::create_wallet, new pixel_message_handle<pixel_message_t::create_wallet>()}, {cmd::import_privkey, new pixel_message_handle<pixel_message_t::import_privkey>()}, {cmd::unlock_wallet, new pixel_message_handle<pixel_message_t::unlock_wallet>()}, {cmd::lock_wallet, new pixel_message_handle<pixel_message_t::lock_wallet>()}, {cmd::unknow, new message_handle()} }; return handle.find(s) != handle.end() ? handle.at(s): handle.at(cmd::unknow); } } // namespace eosio
35.852427
194
0.654409
[ "vector" ]
8e73808232682e841b4679a3a4b36ef931109b88
2,602
cpp
C++
src/networking/Client.cpp
dwarfofdawn/framework
78c207b6efdb3a19d27626b501711539c6c20fbd
[ "MIT" ]
null
null
null
src/networking/Client.cpp
dwarfofdawn/framework
78c207b6efdb3a19d27626b501711539c6c20fbd
[ "MIT" ]
null
null
null
src/networking/Client.cpp
dwarfofdawn/framework
78c207b6efdb3a19d27626b501711539c6c20fbd
[ "MIT" ]
null
null
null
// Copyright 2016 Florian Kramer #include "Network.h" #ifdef unix #include <sys/socket.h> #include <netinet/in.h> #include <ifaddrs.h> // allows for setting sockets asynchronious #include <fcntl.h> #include <errno.h> // provides close #include <unistd.h> // provides inet_aton #include <arpa/inet.h> #include <thread> #endif #ifdef windows #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #include <mingw.thread.h> #endif #include <cstring> #include <vector> #include <map> #include "general/os.h" #include "general/Logger.h" // internal network functions and definitions #include "NetworkHelper.h" namespace warp { namespace client { unsigned char utilBuffer[NETWORK_BUFF_SIZE]; int cnt = -1; #ifdef unix sockaddr_in serverAddr; #endif #ifdef windows WSADATA wsaData; #endif ConnectionBuffer connectionBuffer; unsigned char buffer[NETWORK_BUFF_SIZE]; void (*clientPacketCallback)(ConnectionBuffer *conBuff); void clientPacketCallbackWrapper(ConnectionBuffer *conBuff, void *data); bool startClient(std::string serverIp, unsigned int port) { #ifdef unix serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); inet_aton(serverIp.c_str(), &serverAddr.sin_addr); cnt = socket(AF_INET, SOCK_STREAM, 0); if(cnt == -1) { networkLogger.err("CLIENT ERROR while trying to create socket\n"); return false; } if(connect(cnt, (sockaddr *)(&serverAddr), sizeof(serverAddr)) == -1) { close(cnt); networkLogger.err("CLIENT ERROR while trying to connect to ip %s on port 25542", serverIp.c_str()); cnt = -1; return false; } int flags = fcntl(cnt, F_GETFL, 0); flags = flags | O_NONBLOCK; fcntl(cnt, F_SETFL, flags); #endif #ifdef windows #endif return true; } void stopClient() { if(cnt != -1) { #ifdef unix close(cnt); #endif #ifdef windows #endif cnt = -1; } } void update() { warp::readPackets(cnt, &connectionBuffer, clientPacketCallbackWrapper, buffer); } void setClientPacketCallback(void (*callback)(ConnectionBuffer *conBuff)) { clientPacketCallback = callback; } void sendPacket(unsigned char *data, unsigned int length) { if(cnt != -1) { sendPacketTo(cnt, data, length); } } void clientPacketCallbackWrapper(ConnectionBuffer *conBuff, void *data) { clientPacketCallback(conBuff); } bool isConnected() { return cnt != -1; } } // namespace client } // namespace warp
21.865546
107
0.65834
[ "vector" ]
8e784d03b11050ca6b8a7f77ea4ef6b497e7bf61
2,321
hpp
C++
cpp-projects/base/graphics/light.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/graphics/light.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/graphics/light.hpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
1
2021-07-06T14:47:41.000Z
2021-07-06T14:47:41.000Z
/******************************************************************************* ** Toolbox-base ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance] ** ** ** ** 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. ** ** ** ********************************************************************************/ #pragma once // base #include "geometry/point3.hpp" #include "geometry/point4.hpp" namespace tool::graphics{ struct LightInfo{ geo::Pt4f Position; // light position in eye coords geo::Vec3f La; // ambient light intensity geo::Vec3f Ld; // diffuse light intensity geo::Vec3f Ls; // specular light intensity }; } // alignas(sizeof(float)*4)
52.75
81
0.483843
[ "geometry" ]
8e7a355251e88f0a8ce598750260cf651fddf5f7
5,894
cpp
C++
lib/LSPServer/LSPTypes.cpp
kwalberg/allium
13b98d56fe480f0e87a45cf870a76ef7a96f398d
[ "MIT" ]
null
null
null
lib/LSPServer/LSPTypes.cpp
kwalberg/allium
13b98d56fe480f0e87a45cf870a76ef7a96f398d
[ "MIT" ]
null
null
null
lib/LSPServer/LSPTypes.cpp
kwalberg/allium
13b98d56fe480f0e87a45cf870a76ef7a96f398d
[ "MIT" ]
null
null
null
#include <math.h> #include "LSPServer/LSPTypes.h" #include "Utils/VectorUtils.h" // This is a trick to pass types with multiple template parameters to a macro. // Extra parentheses are allowed around function arguments, so these templates // make it possible to pass a parenthesized template type to a macro and then // strip them off in the template definition. // // Credit: https://stackoverflow.com/a/13842784/15786199 template<typename T> struct argument_type; template<typename T, typename U> struct argument_type<T(U)> { typedef U type; }; // Decoding support #define DECODE_PROPERTY_WITH_DECODER(OBJECT, PROPERTY_NAME, TYPE, DECODER) \ Optional<argument_type<void(TYPE)>::type> PROPERTY_NAME = OBJECT \ .getAtKey(#PROPERTY_NAME) \ .flatMap<argument_type<void(TYPE)>::type>([](JSON v) { return DECODER(v); }); #define DECODE_PROPERTY(OBJECT, PROPERTY_NAME, TYPE) \ DECODE_PROPERTY_WITH_DECODER(OBJECT, PROPERTY_NAME, TYPE, TYPE::decode) #define DECODE_PRIMITIVE_PROPERTY(OBJECT, PROPERTY_NAME, TYPE) \ DECODE_PROPERTY_WITH_DECODER(OBJECT, PROPERTY_NAME, TYPE, decodeJSON<TYPE>) // Decoding support template <> Optional<Unit> decodeJSON(JSON json) { return json.as_a<Unit>(); } template <> Optional<bool> decodeJSON(JSON json) { return json.as_a<bool>(); } template <> Optional<double> decodeJSON(JSON json) { return json.as_a<double>(); } /// Note: this will behave badly for doubles that do not store their 1's bit. template <> Optional<int> decodeJSON(JSON json) { return json.as_a<double>().flatMap<int>([](double d) -> Optional<int> { if(trunc(d) == d) { return (int) d; } else { return Optional<int>(); } }); } template <> Optional<std::string> decodeJSON(JSON json) { return json.as_a<std::string>(); } // Encoding support JSON encodeJSON(Unit) { return JSON(Unit()); } JSON encodeJSON(bool b) { return JSON(b); } JSON encodeJSON(double d) { return JSON(d); } JSON encodeJSON(int i) { return JSON((double) i); } JSON encodeJSON(std::string str) { return JSON(str); } Optional<JSONRPCRequest> JSONRPCRequest::decode(JSON json) { return json.as_a<JSONObject>().flatMap<JSONRPCRequest>([](JSONObject o) { DECODE_PRIMITIVE_PROPERTY(o, jsonrpc, std::string); DECODE_PRIMITIVE_PROPERTY(o, method, std::string); Optional<JSON> params = o.getAtKey("params"); DECODE_PROPERTY_WITH_DECODER(o, id, (TaggedUnion<std::string, int, Unit>), (decodeJSONUnion<std::string, int, Unit>)); return all<std::string, std::string, JSON, TaggedUnion<std::string, int, Unit>>( jsonrpc, method, params, id ).map<JSONRPCRequest>([&](auto properties) { return JSONRPCRequest( std::get<0>(properties), std::get<1>(properties), std::get<2>(properties), std::get<3>(properties)); }); }); } Optional<ClientInfo> ClientInfo::decode(JSON json) { return json.as_a<JSONObject>().flatMap<ClientInfo>([](JSONObject o) { DECODE_PRIMITIVE_PROPERTY(o, name, std::string); DECODE_PRIMITIVE_PROPERTY(o, version, std::string); return name.map<ClientInfo>([&](std::string name) { return ClientInfo( name, version); }); }); } JSON ClientInfo::encode() { JSONObject o = { { "name", encodeJSON(name) } }; version.then([&](std::string version) { o.emplace("version", encodeJSON(version)); }); return JSON(o); } bool operator==(const ClientInfo &lhs, const ClientInfo &rhs) { return lhs.name == rhs.name && lhs.version == rhs.version; } Optional<InitializeParams> InitializeParams::decode(JSON json) { return json.as_a<JSONObject>().flatMap<InitializeParams>([](JSONObject o) { DECODE_PROPERTY_WITH_DECODER(o, processId, (TaggedUnion<int, Unit>), (decodeJSONUnion<int, Unit>)); DECODE_PROPERTY(o, clientInfo, ClientInfo); return all<TaggedUnion<int, Unit>>( processId ).map<InitializeParams>([&](auto properties) { return InitializeParams( std::get<0>(properties), clientInfo); }); }); } bool operator==(const InitializeParams &lhs, const InitializeParams &rhs) { return lhs.processId == rhs.processId && lhs.clientInfo == rhs.clientInfo; } JSON SemanticTokensLegend::encode() { return JSON(JSONObject({ { "tokenTypes", encodeJSON(tokenTypes) }, { "tokenModifiers", encodeJSON(tokenModifiers) } })); } bool operator==(const SemanticTokensLegend &lhs, const SemanticTokensLegend &rhs) { return lhs.tokenTypes == rhs.tokenTypes && lhs.tokenModifiers == rhs.tokenModifiers; } JSON SemanticTokensOptions::encode() { JSONObject o = { { "legend", legend.encode() } }; range.then([&](bool b) { o.emplace("range", b); }); full.then([&](bool b) { o.emplace("full", b); }); return JSON(o); } bool operator==(const SemanticTokensOptions &lhs, const SemanticTokensOptions &rhs) { return lhs.legend == rhs.legend && lhs.range == rhs.range && lhs.full == rhs.full; } JSON ServerCapabilities::encode() { JSONObject o = {}; semanticTokensProvider.then([&](auto stp) { o.emplace("semanticTokensProvider", stp.encode()); }); return JSON(o); } bool operator==(const ServerCapabilities &lhs, const ServerCapabilities &rhs) { assert(false); return true; } JSON InitializeResult::encode() { JSONObject o = { { "capabilities", capabilities.encode() } }; serverInfo.then([&](ClientInfo serverInfo) { o.emplace("serverInfo", serverInfo.encode()); }); return JSON(o); } bool operator==(const InitializeResult &lhs, const InitializeResult & rhs) { assert(false); return true; }
29.178218
126
0.647438
[ "object" ]
8e8a4df705be18050a5be3f342c39cfc317204e3
24,174
hpp
C++
project/ksdiy/components/esp-dl/include/image/dl_image.hpp
Kevincoooool/esp32s3_openmv_lvgl
554ee35d63f3c8f3108538eb8d85a6f8ca9fe690
[ "MIT" ]
100
2021-06-13T03:04:49.000Z
2022-03-26T08:23:23.000Z
project/ksdiy/components/esp-dl/include/image/dl_image.hpp
Kevincoooool/esp32s3_openmv_lvgl
554ee35d63f3c8f3108538eb8d85a6f8ca9fe690
[ "MIT" ]
65
2021-07-13T02:34:48.000Z
2022-03-25T17:25:36.000Z
project/ksdiy/components/esp-dl/include/image/dl_image.hpp
Kevincoooool/esp32s3_openmv_lvgl
554ee35d63f3c8f3108538eb8d85a6f8ca9fe690
[ "MIT" ]
27
2021-06-11T22:10:58.000Z
2022-03-26T18:06:17.000Z
#pragma once #include <stdint.h> #include <stdlib.h> #include <math.h> #include <vector> #include "dl_define.hpp" #include "dl_variable.hpp" #include "dl_math_matrix.hpp" namespace dl { namespace image { typedef enum { IMAGE_RESIZE_BILINEAR = 0, /*<! Resize image by taking bilinear of four pixels */ IMAGE_RESIZE_MEAN = 1, /*<! Resize image by taking mean of four pixels */ IMAGE_RESIZE_NEAREST = 2 /*<! Resize image by taking the nearest pixel */ } resize_type_t; /** * @brief Convert RGB888 pixel to Gray. * * @param red red value * @param green green value * @param blue blue value * @return gray value */ inline uint8_t convert_pixel_rgb888_to_gray(int red, int green, int blue) { int temp = (red * 38 + green * 75 + blue * 15) >> 7; return DL_CLIP(temp, 0, 255); } /** * @brief Convert RGB565 pixel to RGB888. * * @tparam T supports all integer types * @param input pixel value in RGB565 * @param output pixel value in RGB888 */ template <typename T> inline void convert_pixel_rgb565_to_rgb888(uint16_t input, T *output) { output[0] = (input & 0x1F00) >> 5; // blue output[1] = ((input & 0x7) << 5) | ((input & 0xE000) >> 11); // green output[2] = input & 0xF8; // red } /** * @brief Convert RGB565 image to RGB888 image. * * @param image ptr of RGB565 image * @param image_shape shape of the input image * @return Tensor<uint8_t>* output RGB88 image */ Tensor<uint8_t> *convert_image_rgb565_to_rgb888(uint16_t *image, std::vector<int> &image_shape); /** * @brief Convert RGB565 pixel to Gray. * * @param input pixel value in RGB565 * @return pixel value in Gray */ inline uint8_t convert_pixel_rgb565_to_gray(uint16_t input) { int blue = (input & 0x1F00) >> 5; // blue int green = ((input & 0x7) << 5) | ((input & 0xE000) >> 11); // green int red = input & 0xF8; // red return convert_pixel_rgb888_to_gray(red, green, blue); } /** * @brief Crop a patch from image and resize and store to destination image. * If the cropping box is out of image, destination image will be padded with edge. * * The outer rectangle is the entire output image. * The inner rectangle is where the resized image will be stored. * In other world, this function could help you do padding while resize image. * ___________________________(dst_w)__________________ * | ___________________________ | * | |(x_start, y_start) | | * | | | | * | | | | * (dst_h)| | | | * | | | | * | | | | * | |___________________________|(x_end, y_end) | * |____________________________________________________| * * @tparam T suppot all integer types * @param dst_image pointer of destination(output) image * @param dst_width destination image width * @param dst_channel destination image channel number * @param dst_y_start start y of resized image in destination image * @param dst_y_end end y of resized image in destination image * @param dst_x_start start x of resized image in destination image * @param dst_x_end end x of resized image in destination image * @param src_image pointer of source image * @param src_height source image height * @param src_width source image width * @param src_channel source image channel * @param src_y_start start y of resized image in source image * @param src_y_end end y of resized image in source image * @param src_x_start start x of resized image in source image * @param src_x_end end x of resized image in source image * @param resize_type one of IMAGE_RESIZE_BILINEAR or IMAGE_RESIZE_MEAN or IMAGE_RESIZE_NEAREST * @param shift_left bit left shift number implemented on output */ template <typename T> void crop_and_resize(T *dst_image, int dst_width, int dst_channel, int dst_y_start, int dst_y_end, int dst_x_start, int dst_x_end, uint16_t *src_image, int src_height, int src_width, int src_channel, int src_y_start, int src_y_end, int src_x_start, int src_x_end, resize_type_t resize_type = IMAGE_RESIZE_NEAREST, int shift_left = 0); /** * @brief Crop a patch from image and resize and store to destination image. * If the cropping box is out of image, destination image will be padded with edge. * * The outer rectangle is the entire output image. * The inner rectangle is where the resized image will be stored. * In other world, this function could help you do padding while resize image. * ___________________________(dst_w)__________________ * | ___________________________ | * | |(x_start, y_start) | | * | | | | * | | | | * (dst_h)| | | | * | | | | * | | | | * | |___________________________|(x_end, y_end) | * |____________________________________________________| * * @tparam T suppot all integer types * @param dst_image pointer of destination(output) image * @param dst_width destination image width * @param dst_channel destination image channel number * @param dst_y_start start y of resized image in destination image * @param dst_y_end end y of resized image in destination image * @param dst_x_start start x of resized image in destination image * @param dst_x_end end x of resized image in destination image * @param src_image pointer of source image * @param src_height source image height * @param src_width source image width * @param src_channel source image channel * @param src_y_start start y of resized image in source image * @param src_y_end end y of resized image in source image * @param src_x_start start x of resized image in source image * @param src_x_end end x of resized image in source image * @param resize_type one of IMAGE_RESIZE_BILINEAR or IMAGE_RESIZE_MEAN or IMAGE_RESIZE_NEAREST * @param shift_left bit left shift number implemented on output */ template <typename T> void crop_and_resize(T *dst_image, int dst_width, int dst_channel, int dst_y_start, int dst_y_end, int dst_x_start, int dst_x_end, uint8_t *src_image, int src_height, int src_width, int src_channel, int src_y_start, int src_y_end, int src_x_start, int src_x_end, resize_type_t resize_type = IMAGE_RESIZE_NEAREST, int shift_left = 0); /** * @brief Draw a filled rectangle on RGB888 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x1 left up corner x * @param y1 left up corner y * @param x2 right bottom corner x * @param y2 right bottom corner y * @param color 0x 00| 00| 00| 00 * reserved|channel 0|channel 1|channel 2 */ void draw_filled_rectangle(uint8_t *image, const uint32_t image_height, const uint32_t image_width, uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2, const uint32_t color = 0x00FF0000); /** * @brief Draw a filled rectangle on RGB565 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x1 left up corner x * @param y1 left up corner y * @param x2 right bottom corner x * @param y2 right bottom corner y * @param color 0b 000| 00000| 00000| 000 * channel 1[2:0]|channel 0|channel 2|channel 1[5:3] */ void draw_filled_rectangle(uint16_t *image, const uint32_t image_height, const uint32_t image_width, uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2, const uint16_t color = 0b0001111100000000); /** * @brief Draw a point on RGB888 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x point x * @param y point y * @param size size of point * @param color 0x 00| 00| 00| 00 * reserved|channel 0|channel 1|channel 2 */ void draw_point(uint8_t *image, const uint32_t image_height, const uint32_t image_width, const uint32_t x, const uint32_t y, const uint32_t size, const uint32_t color = 0x00FF0000); /** * @brief Draw a point on RGB565 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x point x * @param y point y * @param size size of point * @param color 0b 000| 00000| 00000| 000 * channel 1[2:0]|channel 0|channel 2|channel 1[5:3] */ void draw_point(uint16_t *image, const uint32_t image_height, const uint32_t image_width, const uint32_t x, const uint32_t y, const uint32_t size, uint16_t color = 0b0001111100000000); /** * @brief Draw a hollow rectangle on RGB888 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x1 left up corner x * @param y1 left up corner y * @param x2 right bottom corner x * @param y2 right bottom corner y * @param color 0x 00| 00| 00| 00 * reserved|channel 0|channel 1|channel 2 */ void draw_hollow_rectangle(uint8_t *image, const uint32_t image_height, const uint32_t image_width, uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2, uint32_t color = 0x00FF0000); /** * @brief Draw a hollow rectangle on RGB565 image. * * @param image pointer of input image * @param image_height height of input image * @param image_width width of input image * @param x1 left up corner x * @param y1 left up corner y * @param x2 right bottom corner x * @param y2 right bottom corner y * @param color 0b 000| 00000| 00000| 000 * channel 1[2:0]|channel 0|channel 2|channel 1[5:3] */ void draw_hollow_rectangle(uint16_t *image, const uint32_t image_height, const uint32_t image_width, uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2, const uint16_t color = 0b0001111100000000); /** * @brief Detect target moving by activated detection point number. Each cross in the figure below is a detection point. * Once abs(frame_1_detection_point[i] - frame_2_detection_point[i]) > threshold, this detection point is activated. * This function will return the number of activated detection point. * * __stride__________________________ * | | | | | * stride | | | | | * | | | | | * |________|________|________| | * | | | | | * | | | | | * | | | | | * |________|________|________| height * | | | | | * | | | | | * | | | | | * |________|________|________| | * | | | | | * | | | | | * | | | | | * |________|________|________|___|___ * | | * |__________width___________| * | | * * Time consumption: * Frame shape = (240, 240) * Both frame are in PSRAM * On ESP32-S3 with CPU 240MHz, QSPI 80MHz * * stride latency * 1 28316us * 2 8770us * 4 3622us * 8 1990us * 16 880us * 32 260us * * * In a application, outside this function, threshold of activated detection point number is needed. * Once activated detection point number > number_threshold, this two frame are judged target moved. * How to determine the number_threshold? * Let's assume that the minimize shape of target is (target_min_height, target_max_width). * Then, the number_threshold = [target_min_height / stride] * [target_max_width / stride] * ratio, * where ratio is in (0, 1), the smaller the ratio is, the more sensitive the detector is, the more false detected. * * * @param f1 one frame in RGB565 * @param f2 another frame in RGB565 * @param height height of frame * @param width width of frame * @param stride stride of detection point, the smaller the stride is, the more reliable the detector is. * @param threshold activation threshold of each detection point * @return activated detection point number */ uint32_t get_moving_point_number(uint16_t *f1, uint16_t *f2, const uint32_t height, const uint32_t width, const uint32_t stride, const uint32_t threshold = 5); /** * @brief Detect target moving by activated detection point number. Each cross in the figure below is a detection point. * Once abs(frame_1_detection_point[i] - frame_2_detection_point[i]) > threshold, this detection point is activated. * This function will return the number of activated detection point. * * __stride__________________________ * | | | | | * stride | | | | | * | | | | | * |________|________|________| | * | | | | | * | | | | | * | | | | | * |________|________|________| height * | | | | | * | | | | | * | | | | | * |________|________|________| | * | | | | | * | | | | | * | | | | | * |________|________|________|___|___ * | | * |__________width___________| * | | * * * In a application, outside this function, threshold of activated detection point number is needed. * Once activated detection point number > number_threshold, this two frame are judged target moved. * How to determine the number_threshold? * Let's assume that the minimize shape of target is (target_min_height, target_max_width). * Then, the number_threshold = [target_min_height / stride] * [target_max_width / stride] * ratio, * where ratio is in (0, 1), the smaller the ratio is, the more sensitive the detector is, the more false detected. * * * @param f1 one frame in RGB888 * @param f2 another frame in RGB888 * @param height height of frame * @param width width of frame * @param stride stride of detection point, the smaller the stride is, the more reliable the detector is. * @param threshold activation threshold of each detection point * @return activated detection point number */ uint32_t get_moving_point_number(uint8_t *f1, uint8_t *f2, const uint32_t height, const uint32_t width, const uint32_t stride, const uint32_t threshold = 5); /** * @brief Apply an affine transformation to an image. * * @tparam T * @param input the input image. * @param output the output image. * @param M_inv the inverse transformation matrix. */ template <typename T> void warp_affine(dl::Tensor<T> *input, dl::Tensor<T> *output, dl::math::Matrix<float> *M_inv); /** * @brief Apply an affine transformation to an image. * * @tparam T * @param input the pointer of the input image. * @param shape the shape of the input image. * @param output the output image. * @param M_inv the inverse transformation matrix. */ template <typename T> void warp_affine(uint16_t *input, std::vector<int> shape, dl::Tensor<T> *output, dl::math::Matrix<float> *M_inv); /** * @brief Get the otsu thresh object. * * @param image the gray image. * @return uint8_t the otsu thresh. */ uint8_t get_otsu_thresh(Tensor<uint8_t> &image); /** * @brief Convert RGB image to gray image * * @param image input image * @param bgr true: the image is in BGR format * false: the image is in RGB format * @return Tensor<uint8_t>* output image in gray format */ Tensor<uint8_t> *rgb2gray(Tensor<uint8_t> &image, bool bgr = false); /** * @brief Convert RGB image to LAB image * * @param image input image * @param bgr true: the image is in BGR format * false: the image is in RGB format * @param fast true: use the fast alogrithm, but the accuracy will be reduced * false: do not use the fast alogrithm * @return Tensor<uint8_t>* output image in LAB foramt */ Tensor<uint8_t> *rgb2lab(Tensor<uint8_t> &image, bool bgr = false, bool fast = true); /** * @brief Convert RGB image to HSV image * * @param image input image * @param bgr true: the image is in BGR format * false: the image is in RGB format * @param fast true: use the fast alogrithm, but the accuracy will be reduced * false: do not use the fast alogrithm * @return Tensor<uint8_t>* output image in HSV format */ Tensor<uint8_t> *rgb2hsv(Tensor<uint8_t> &image, bool bgr = false, bool fast = true); /** * @brief resize an image to the target shape. * * @param image the input image Tensor * @param target_shape the target shape of the resized image. * @param resize_type one of IMAGE_RESIZE_BILINEAR or IMAGE_RESIZE_MEAN or IMAGE_RESIZE_NEAREST * @return Tensor<uint8_t>* the pointer of the resized image Tensor */ Tensor<uint8_t> *resize_image(Tensor<uint8_t> &image, std::vector<int> target_shape, resize_type_t resize_type); /** * @brief resize an image to the target shape. * * @param image the input image Tensor * @param resized_image the resized image Tensor * @param resize_type one of IMAGE_RESIZE_BILINEAR or IMAGE_RESIZE_MEAN or IMAGE_RESIZE_NEAREST */ void resize_image(Tensor<uint8_t> &image, Tensor<uint8_t> &resized_image, resize_type_t resize_type); /** * @brief resize an image to the target shape with nearest method. * * @tparam T * @param image the pointer of the input image * @param input_shape the input shape of the image * @param target_shape the target shape of the resized image * @return T* the pointer of the resized image */ template <typename T> T *resize_image_nearest(T *image, std::vector<int> input_shape, std::vector<int> target_shape); /** * @brief resize an image to the target shape with nearest method. * * @tparam T * @param image the pointer of the input image * @param input_shape the input shape of the image * @param resized_image the pointer of the resized image * @param target_shape the target shape of the resized image */ template <typename T> void resize_image_nearest(T *image, std::vector<int> input_shape, T *resized_image, std::vector<int> target_shape); } // namespace image } // namespace dl
49.134146
167
0.50604
[ "object", "shape", "vector" ]
8e949f1f722e465166feba29e4c09de526b5290d
9,631
cpp
C++
examples/cpp/qt/shadertoy/Shadertoy.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
135
2015-01-08T03:27:23.000Z
2022-03-06T08:30:21.000Z
examples/cpp/qt/shadertoy/Shadertoy.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
34
2015-01-03T10:40:12.000Z
2021-04-15T18:24:02.000Z
examples/cpp/qt/shadertoy/Shadertoy.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
80
2015-01-10T08:41:28.000Z
2022-03-06T08:30:24.000Z
/************************************************************************************ Authors : Bradley Austin Davis <bdavis@saintandreas.org> Copyright : Copyright Bradley Austin Davis. 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 "QtCommon.h" #include "Shadertoy.h" #include <QDomDocument> #include <QXmlQuery> #include <QJsonValue> #include <QJsonDocument> namespace shadertoy { const char * UNIFORM_RESOLUTION = "iResolution"; const char * UNIFORM_GLOBALTIME = "iGlobalTime"; const char * UNIFORM_CHANNEL_TIME = "iChannelTime"; const char * UNIFORM_CHANNEL_RESOLUTIONS[MAX_CHANNELS] = { "iChannelResolution[0]", "iChannelResolution[1]", "iChannelResolution[2]", "iChannelResolution[3]", }; const char * UNIFORM_CHANNEL_RESOLUTION = "iChannelResolution"; const char * UNIFORM_MOUSE_COORDS = "iMouse"; const char * UNIFORM_DATE = "iDate"; const char * UNIFORM_SAMPLE_RATE = "iSampleRate"; const char * UNIFORM_POSITION = "iPos"; const char * UNIFORM_CHANNELS[MAX_CHANNELS] = { "iChannel0", "iChannel1", "iChannel2", "iChannel3", }; const char * SHADER_HEADER = "#version 330\n" "uniform vec3 iResolution; // viewport resolution (in pixels)\n" "uniform float iGlobalTime; // shader playback time (in seconds)\n" "uniform float iChannelTime[4]; // channel playback time (in seconds)\n" "uniform vec3 iChannelResolution[4]; // channel resolution (in pixels)\n" "uniform vec4 iMouse; // mouse pixel coords. xy: current (if MLB down), zw: click\n" "uniform vec4 iDate; // (year, month, day, time in seconds)\n" "uniform float iSampleRate; // sound sample rate (i.e., 44100)\n" "uniform vec3 iPos; // Head position\n" "in vec3 iDir; // Direction from viewer\n" "out vec4 FragColor;\n"; const char * LINE_NUMBER_HEADER = "#line 1\n"; const QStringList TEXTURES({ "/presets/tex00.jpg", "/presets/tex01.jpg", "/presets/tex02.jpg", "/presets/tex03.jpg", "/presets/tex04.jpg", "/presets/tex05.jpg", "/presets/tex06.jpg", "/presets/tex07.jpg", "/presets/tex08.jpg", "/presets/tex09.jpg", "/presets/tex10.png", "/presets/tex11.png", "/presets/tex12.png", "/presets/tex14.png", "/presets/tex15.png", "/presets/tex16.png" }); const QStringList CUBEMAPS({ "/presets/cube00_%1.jpg", "/presets/cube01_%1.png", "/presets/cube02_%1.jpg", "/presets/cube03_%1.png", "/presets/cube04_%1.png", "/presets/cube05_%1.png", }); } namespace shadertoy { static const char * CHANNEL_REGEX = "(\\w+)(\\d{2})"; static const char * XML_ROOT_NAME = "shadertoy"; static const char * XML_FRAGMENT_SOURCE = "fragmentSource"; static const char * XML_NAME = "name"; static const char * XML_CHANNEL = "channel"; static const char * XML_CHANNEL_ATTR_ID = "id"; static const char * XML_CHANNEL_ATTR_SOURCE = "source"; static const char * XML_CHANNEL_ATTR_TYPE = "type"; ChannelInputType channelTypeFromString(const QString & channelTypeStr) { ChannelInputType channelType = ChannelInputType::TEXTURE; if (channelTypeStr == "tex") { channelType = ChannelInputType::TEXTURE; } else if (channelTypeStr == "cube") { channelType = ChannelInputType::CUBEMAP; } return channelType; } ChannelInputType fromShadertoyString(const QString & channelType) { // texture music cubemap ??? if (channelType == "cubemap") { return ChannelInputType::CUBEMAP; } else if (channelType == "texture") { return ChannelInputType::TEXTURE; } else if (channelType == "music") { return ChannelInputType::AUDIO; } else { // FIXME add support for video throw std::runtime_error("Unable to parse channel type"); } } Shader parseShaderJson(const QByteArray & shaderJson) { Shader result; QJsonDocument jsonResponse = QJsonDocument::fromJson(shaderJson); QJsonObject jsonObject = jsonResponse.object(); QJsonObject info = path(jsonResponse.object(), { "Shader", 0, "info" }).toObject(); result.name = info["name"].toString().toLocal8Bit(); result.id = info["id"].toString().toLocal8Bit(); //result.description = info["description"].toString().toLocal8Bit(); QJsonObject renderPass = path(jsonResponse.object(), { "Shader", 0, "renderpass", 0 }).toObject(); result.fragmentSource = renderPass["code"].toString().toLocal8Bit(); QJsonArray inputs = renderPass["inputs"].toArray(); for (int i = 0; i < inputs.count(); ++i) { QJsonObject channel = inputs.at(i).toObject(); int channelIndex = channel["channel"].toInt(); result.channelTypes[channelIndex] = fromShadertoyString(channel["ctype"].toString()); result.channelTextures[channelIndex] = channel["src"].toString().toLocal8Bit(); } result.vrEnabled = result.fragmentSource.contains("#pragma vr"); return result; } Shader loadShaderXml(QIODevice & ioDevice) { QDomDocument dom; Shader result; dom.setContent(&ioDevice); auto children = dom.documentElement().childNodes(); for (int i = 0; i < children.count(); ++i) { auto child = children.at(i); if (child.nodeName() == "url") { result.url = child.firstChild().nodeValue(); } if (child.nodeName() == XML_FRAGMENT_SOURCE) { result.fragmentSource = child.firstChild().nodeValue(); } if (child.nodeName() == XML_NAME) { result.name = child.firstChild().nodeValue(); } else if (child.nodeName() == XML_CHANNEL) { auto attributes = child.attributes(); int channelIndex = -1; QString source; if (attributes.contains(XML_CHANNEL_ATTR_ID)) { channelIndex = attributes.namedItem(XML_CHANNEL_ATTR_ID).nodeValue().toInt(); } if (channelIndex < 0 || channelIndex >= shadertoy::MAX_CHANNELS) { continue; } // Compatibility mode if (attributes.contains(XML_CHANNEL_ATTR_SOURCE)) { source = attributes.namedItem(XML_CHANNEL_ATTR_SOURCE).nodeValue(); QRegExp re(CHANNEL_REGEX); if (!re.exactMatch(source)) { continue; } result.channelTypes[channelIndex] = channelTypeFromString(re.cap(1)); result.channelTextures[channelIndex] = ("preset://" + re.cap(1) + "/" + re.cap(2)); continue; } if (attributes.contains(XML_CHANNEL_ATTR_TYPE)) { result.channelTypes[channelIndex] = channelTypeFromString(attributes.namedItem(XML_CHANNEL_ATTR_SOURCE).nodeValue()); result.channelTextures[channelIndex] = child.firstChild().nodeValue(); } } } result.vrEnabled = result.fragmentSource.contains("#pragma vr"); return result; } Shader loadShaderJson(const QString & shaderPath) { QByteArray json = readFileToByteArray(shaderPath); return parseShaderJson(json); } Shader loadShaderXml(const QString & fileName) { QFile file(fileName); return loadShaderXml(file); } Shader loadShaderFile(const QString & shaderPath) { if (shaderPath.endsWith(".xml", Qt::CaseInsensitive)) { return shadertoy::loadShaderXml(shaderPath); } else if (shaderPath.endsWith(".json", Qt::CaseInsensitive)) { return shadertoy::loadShaderJson(shaderPath); } else { qWarning() << "Don't know how to parse path " << shaderPath; } return Shader(); } QByteArray readFile(const QString & filename) { QFile file(filename); file.open(QFile::ReadOnly); QByteArray result = file.readAll(); file.close(); return result; } // FIXME no error handling. QDomDocument writeShaderXml(const Shader & shader) { QDomDocument result; QDomElement root = result.createElement(XML_ROOT_NAME); result.appendChild(root); for (int i = 0; i < MAX_CHANNELS; ++i) { if (!shader.channelTextures[i].isEmpty()) { QDomElement channelElement = result.createElement(XML_CHANNEL); channelElement.setAttribute(XML_CHANNEL_ATTR_ID, i); channelElement.setAttribute(XML_CHANNEL_ATTR_TYPE, shader.channelTypes[i] == ChannelInputType::CUBEMAP ? "cube" : "tex"); channelElement.appendChild(result.createTextNode(shader.channelTextures[i])); root.appendChild(channelElement); } } root.appendChild(result.createElement(XML_FRAGMENT_SOURCE)). appendChild(result.createCDATASection(shader.fragmentSource)); if (!shader.name.isEmpty()) { root.appendChild(result.createElement(XML_NAME)). appendChild(result.createCDATASection(shader.name)); } return result; } // FIXME no error handling. void saveShaderXml(const QString & name, const Shader & shader) { QDomDocument doc = writeShaderXml(shader); QFile file(name); file.open(QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text); file.write(doc.toByteArray()); file.close(); } }
36.071161
129
0.654553
[ "object" ]
8ea10ebbca13185283b69c15e6f3b7feab76fc56
7,799
cc
C++
cyber/examples/self_part/lidar_listener.cc
sunzengpeng/cyber_multisensor_fusion
36118c58da6fb97932218a33981ed54157144363
[ "MIT" ]
null
null
null
cyber/examples/self_part/lidar_listener.cc
sunzengpeng/cyber_multisensor_fusion
36118c58da6fb97932218a33981ed54157144363
[ "MIT" ]
null
null
null
cyber/examples/self_part/lidar_listener.cc
sunzengpeng/cyber_multisensor_fusion
36118c58da6fb97932218a33981ed54157144363
[ "MIT" ]
1
2021-10-19T12:15:33.000Z
2021-10-19T12:15:33.000Z
/****************************************************************************** * Copyright 2018 The Apollo 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 "cyber/cyber.h" #include "modules/drivers/proto/pointcloud.pb.h" //#include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/pcl_visualizer.h> #include <iostream> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/crop_box.h> #include <pcl/filters/extract_indices.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/kdtree/kdtree.h> #include <pcl/common/transforms.h> #include <pcl/common/common.h> #include <boost/thread/thread.hpp> #include <vector> #include <unordered_set> #include <string> #include <chrono> //#include <vtkProp3D.h> using namespace std; //pcl::visualization::CloudViewer viewer("point cloud viewer"); boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer("viewer test")); //init para struct Color { float r, g, b; Color(float setR, float setG, float setB) : r(setR), g(setG), b(setB) {} }; struct Box { float x_min; float y_min; float z_min; float x_max; float y_max; float z_max; }; float filterRes = 0.4; Eigen::Vector4f minpoint(-10, -6.5, -2, 1); Eigen::Vector4f maxpoint(30, 6.5, 1, 1); int maxIterations = 40; float distanceThreshold = 0.3; float clusterTolerance = 0.5; int minsize = 10; int maxsize = 140; void MessageCallback( const std::shared_ptr<apollo::drivers::PointCloud>& msg) { cout << "-----------------------" << msg->point_size() << endl; //init viewer // viewer->initCameraParameters(); // int v1(0); // int v2(0); // viewer->createViewPort(0.0, 0.0, 1.0, 1.0, v1); // viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2); pcl::PointCloud<pcl::PointXYZ>::Ptr pcloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>& cloud = *pcloud; // pcl::PointCloud<pcl::PointXYZ> cloud; cloud.width = msg->point_size(); cloud.height = 1; cloud.is_dense = false; cloud.points.resize(cloud.width * cloud.height); for (size_t i = 0; i < cloud.points.size(); ++i) { cloud.points[i].x = msg->point(i).x(); cloud.points[i].y = msg->point(i).y(); cloud.points[i].z = msg->point(i).z(); } // save point_cloud to pcd file // pcl::io::savePCDFileASCII("/apollo/write_pcd_test.pcd", cloud); // visualize point_cloud // viewer.showCloud(pcloud); //voxel frid filter pcl::PointCloud<pcl::PointXYZ>::Ptr cloudFiltered(new pcl::PointCloud<pcl::PointXYZ>); pcl::VoxelGrid<pcl::PointXYZ> vg; vg.setInputCloud(pcloud); vg.setLeafSize(filterRes, filterRes, filterRes); vg.filter(*cloudFiltered); // viewer.showCloud(pcloud); //cropbox pcl::PointCloud<pcl::PointXYZ>::Ptr cloudRegion(new pcl::PointCloud<pcl::PointXYZ>); pcl::CropBox<pcl::PointXYZ> region(true); region.setMin(minpoint); region.setMax(maxpoint); region.setInputCloud(cloudFiltered); region.filter(*cloudRegion); vector<int> indices; pcl::CropBox<pcl::PointXYZ> roof(true); roof.setMin(Eigen::Vector4f(-1.5, -1.7, -1, 1)); roof.setMax(Eigen::Vector4f(2.6, 1.7, -0.4, 1)); roof.setInputCloud(cloudRegion); roof.filter(indices); pcl::PointIndices::Ptr inliers(new pcl::PointIndices); for(int point:indices) { inliers->indices.push_back(point); } pcl::ExtractIndices<pcl::PointXYZ> extract; extract.setInputCloud(cloudRegion); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*cloudRegion); //segment plane // int num_points = cloudRegion->points.size(); // auto cloud_points = cloudRegion->points; // Ransac<pcl::PointXYZ> RansacSeg(maxIterations, distanceThreshold, num_points); pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers_seg(new pcl::PointIndices); pcl::SACSegmentation<pcl::PointXYZ>seg; seg.setOptimizeCoefficients(true); seg.setModelType(pcl::SACMODEL_PLANE); seg.setMethodType(pcl::SAC_RANSAC); seg.setDistanceThreshold(distanceThreshold); seg.setInputCloud(cloudRegion); seg.segment(*inliers_seg, *coefficients); //segment obstacles pcl::PointCloud<pcl::PointXYZ>::Ptr obstCloud(new pcl::PointCloud<pcl::PointXYZ>()); pcl::PointCloud<pcl::PointXYZ>::Ptr planeCloud(new pcl::PointCloud<pcl::PointXYZ>()); for(int index : inliers_seg->indices) { planeCloud->points.push_back(cloudRegion->points[index]); } pcl::ExtractIndices<pcl::PointXYZ> extract_obst; extract_obst.setInputCloud(cloudRegion); extract_obst.setIndices(inliers_seg); extract_obst.setNegative(true); extract.filter(*obstCloud); std::pair<pcl::PointCloud<pcl::PointXYZ>::Ptr, pcl::PointCloud<pcl::PointXYZ>::Ptr> segResult(obstCloud, planeCloud); //cluster vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>clusters; typename pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud(segResult.first); vector<pcl::PointIndices> clusterIndices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; ec.setClusterTolerance(clusterTolerance); ec.setMinClusterSize(minsize); ec.setMaxClusterSize(maxsize); ec.setSearchMethod(tree); ec.setInputCloud(segResult.first); ec.extract(clusterIndices); for(pcl::PointIndices getIndices: clusterIndices){ pcl::PointCloud<pcl::PointXYZ>::Ptr cloudCluster(new pcl::PointCloud<pcl::PointXYZ>); for(int index:getIndices.indices) { cloudCluster->points.push_back(segResult.first->points[index]); } cloudCluster->width = cloudCluster->points.size(); cloudCluster->height = 1; cloudCluster->is_dense = true; clusters.push_back(cloudCluster); } //bounding box int clusterId = 0; vector<Color> colors = {Color(1, 0, 0), Color(0, 1, 0), Color(0, 0, 1)}; for(pcl::PointCloud<pcl::PointXYZ>::Ptr cluster_temp: clusters) { // viewer->addPointCloud<pcl::PointXYZ>(cluster_temp, "obstcloud" + std::to_string(clusterId)); pcl::PointXYZ minpoint_temp, maxpoint_temp; pcl::getMinMax3D(*cluster_temp, minpoint_temp, maxpoint_temp); Box box; box.x_min = minpoint_temp.x; box.y_min = minpoint_temp.y; box.z_min = minpoint_temp.z; box.x_max = maxpoint_temp.x; box.y_max = maxpoint_temp.y; box.z_max = maxpoint_temp.z; cout << box.x_min << endl; ++clusterId; } // viewer->setBackgroundColor (0, 0, 0); // pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> pcloud_handler(pcloud, 250, 0, 0); // viewer->addPointCloud(pcloud, "window1", v1); // viewer->addPointCloud(pcloud, "cloud", v1); // viewer->addPointCloud(pcloud, pcloud_handler, "window2", v2); // viewer->spin(); // viewer.showCloud(cloudRegion); } int main(int argc, char* argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::drivers::PointCloud>( "/diamond/sensor/lidar/front/PointCloud2", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; }
34.056769
119
0.702013
[ "vector" ]
8eaeb57cfe29e4119280f83aea0622aa90ea9c69
8,548
cpp
C++
src/NVMeSensorMain.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
15
2019-02-26T03:44:55.000Z
2021-11-04T23:58:51.000Z
src/NVMeSensorMain.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
17
2019-01-23T19:47:44.000Z
2022-03-31T23:03:43.000Z
src/NVMeSensorMain.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
21
2019-08-07T03:32:20.000Z
2022-01-27T09:40:22.000Z
/* // Copyright (c) 2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include <NVMeBasicContext.hpp> #include <NVMeContext.hpp> #include <NVMeMCTPContext.hpp> #include <NVMeSensor.hpp> #include <boost/asio/deadline_timer.hpp> #include <optional> #include <regex> static NVMEMap nvmeDeviceMap; static constexpr bool debug = false; NVMEMap& getNVMEMap() { return nvmeDeviceMap; } static std::optional<int> extractBusNumber(const std::string& path, const SensorBaseConfigMap& properties) { auto findBus = properties.find("Bus"); if (findBus == properties.end()) { std::cerr << "could not determine bus number for " << path << "\n"; return std::nullopt; } return std::visit(VariantToIntVisitor(), findBus->second); } static std::optional<std::string> extractSensorName(const std::string& path, const SensorBaseConfigMap& properties) { auto findSensorName = properties.find("Name"); if (findSensorName == properties.end()) { std::cerr << "could not determine configuration name for " << path << "\n"; return std::nullopt; } return std::get<std::string>(findSensorName->second); } static std::filesystem::path deriveRootBusPath(int busNumber) { return "/sys/bus/i2c/devices/i2c-" + std::to_string(busNumber) + "/mux_device"; } static std::optional<int> deriveRootBus(std::optional<int> busNumber) { if (!busNumber) { return std::nullopt; } std::filesystem::path muxPath = deriveRootBusPath(*busNumber); if (!std::filesystem::is_symlink(muxPath)) { return *busNumber; } std::string rootName = std::filesystem::read_symlink(muxPath).filename(); size_t dash = rootName.find('-'); if (dash == std::string::npos) { std::cerr << "Error finding root bus for " << rootName << "\n"; return std::nullopt; } return std::stoi(rootName.substr(0, dash)); } static std::shared_ptr<NVMeContext> provideRootBusContext(boost::asio::io_service& io, NVMEMap& map, int rootBus) { auto findRoot = map.find(rootBus); if (findRoot != map.end()) { return findRoot->second; } std::shared_ptr<NVMeContext> context = #if HAVE_NVME_MI_MCTP std::make_shared<NVMeMCTPContext>(io, rootBus); #else std::make_shared<NVMeBasicContext>(io, rootBus); #endif map[rootBus] = context; return context; } static void handleSensorConfigurations( boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer, std::shared_ptr<sdbusplus::asio::connection>& dbusConnection, const ManagedObjectType& sensorConfigurations) { // todo: it'd be better to only update the ones we care about for (const auto& [_, nvmeContextPtr] : nvmeDeviceMap) { if (nvmeContextPtr) { nvmeContextPtr->close(); } } nvmeDeviceMap.clear(); // iterate through all found configurations for (const auto& [interfacePath, sensorData] : sensorConfigurations) { // find base configuration auto sensorBase = sensorData.find(NVMeSensor::CONFIG_TYPE); if (sensorBase != sensorData.end()) { const SensorBaseConfigMap& sensorConfig = sensorBase->second; std::optional<int> busNumber = extractBusNumber(interfacePath, sensorConfig); std::optional<std::string> sensorName = extractSensorName(interfacePath, sensorConfig); std::optional<int> rootBus = deriveRootBus(busNumber); if (!(busNumber && sensorName && rootBus)) { continue; } std::vector<thresholds::Threshold> sensorThresholds; if (!parseThresholdsFromConfig(sensorData, sensorThresholds)) { std::cerr << "error populating thresholds for " << *sensorName << "\n"; } std::shared_ptr<NVMeSensor> sensorPtr = std::make_shared<NVMeSensor>( objectServer, io, dbusConnection, *sensorName, std::move(sensorThresholds), interfacePath, *busNumber); provideRootBusContext(io, nvmeDeviceMap, *rootBus) ->addSensor(sensorPtr); } } for (const auto& [_, context] : nvmeDeviceMap) { context->pollNVMeDevices(); } } void createSensors(boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer, std::shared_ptr<sdbusplus::asio::connection>& dbusConnection) { auto getter = std::make_shared<GetSensorConfiguration>( dbusConnection, std::move([&io, &objectServer, &dbusConnection]( const ManagedObjectType& sensorConfigurations) { handleSensorConfigurations(io, objectServer, dbusConnection, sensorConfigurations); })); getter->getConfiguration(std::vector<std::string>{NVMeSensor::CONFIG_TYPE}); } static void interfaceRemoved(sdbusplus::message::message& message, NVMEMap& contexts) { if (message.is_method_error()) { std::cerr << "interfacesRemoved callback method error\n"; return; } sdbusplus::message::object_path path; std::vector<std::string> interfaces; message.read(path, interfaces); for (auto& [_, context] : contexts) { std::optional<std::shared_ptr<NVMeSensor>> sensor = context->getSensorAtPath(path); if (!sensor) { continue; } auto interface = std::find(interfaces.begin(), interfaces.end(), (*sensor)->objectType); if (interface == interfaces.end()) { continue; } context->removeSensor(sensor.value()); } } int main() { boost::asio::io_service io; auto systemBus = std::make_shared<sdbusplus::asio::connection>(io); systemBus->request_name("xyz.openbmc_project.NVMeSensor"); sdbusplus::asio::object_server objectServer(systemBus); #if HAVE_NVME_MI_MCTP nvmeMCTP::init(); #endif io.post([&]() { createSensors(io, objectServer, systemBus); }); boost::asio::deadline_timer filterTimer(io); std::function<void(sdbusplus::message::message&)> eventHandler = [&filterTimer, &io, &objectServer, &systemBus](sdbusplus::message::message&) { // this implicitly cancels the timer filterTimer.expires_from_now(boost::posix_time::seconds(1)); filterTimer.async_wait([&](const boost::system::error_code& ec) { if (ec == boost::asio::error::operation_aborted) { return; // we're being canceled } if (ec) { std::cerr << "Error: " << ec.message() << "\n"; return; } createSensors(io, objectServer, systemBus); }); }; sdbusplus::bus::match::match configMatch( static_cast<sdbusplus::bus::bus&>(*systemBus), "type='signal',member='PropertiesChanged',path_namespace='" + std::string(inventoryPath) + "',arg0namespace='" + std::string(NVMeSensor::CONFIG_TYPE) + "'", eventHandler); // Watch for entity-manager to remove configuration interfaces // so the corresponding sensors can be removed. auto ifaceRemovedMatch = std::make_unique<sdbusplus::bus::match::match>( static_cast<sdbusplus::bus::bus&>(*systemBus), "type='signal',member='InterfacesRemoved',arg0path='" + std::string(inventoryPath) + "/'", [](sdbusplus::message::message& msg) { interfaceRemoved(msg, nvmeDeviceMap); }); setupManufacturingModeMatch(*systemBus); io.run(); }
30.971014
80
0.609265
[ "vector" ]
8ebde752bc4b956a496aeca4b435b5ae1cd6e549
2,289
cpp
C++
tools/aapt2/SdkConstants.cpp
Y-D-Lu/rr_frameworks_base
c5a298fb78e662bb3775016a6ad5ff7c423ec8a9
[ "Apache-2.0" ]
null
null
null
tools/aapt2/SdkConstants.cpp
Y-D-Lu/rr_frameworks_base
c5a298fb78e662bb3775016a6ad5ff7c423ec8a9
[ "Apache-2.0" ]
null
null
null
tools/aapt2/SdkConstants.cpp
Y-D-Lu/rr_frameworks_base
c5a298fb78e662bb3775016a6ad5ff7c423ec8a9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SdkConstants.h" #include <algorithm> #include <string> #include <unordered_map> #include <vector> using android::StringPiece; namespace aapt { static const char* sDevelopmentSdkCodeName = "P"; static ApiVersion sDevelopmentSdkLevel = 28; static const std::vector<std::pair<uint16_t, ApiVersion>> sAttrIdMap = { {0x021c, 1}, {0x021d, 2}, {0x0269, SDK_CUPCAKE}, {0x028d, SDK_DONUT}, {0x02ad, SDK_ECLAIR}, {0x02b3, SDK_ECLAIR_0_1}, {0x02b5, SDK_ECLAIR_MR1}, {0x02bd, SDK_FROYO}, {0x02cb, SDK_GINGERBREAD}, {0x0361, SDK_HONEYCOMB}, {0x0363, SDK_HONEYCOMB_MR1}, {0x0366, SDK_HONEYCOMB_MR2}, {0x03a6, SDK_ICE_CREAM_SANDWICH}, {0x03ae, SDK_JELLY_BEAN}, {0x03cc, SDK_JELLY_BEAN_MR1}, {0x03da, SDK_JELLY_BEAN_MR2}, {0x03f1, SDK_KITKAT}, {0x03f6, SDK_KITKAT_WATCH}, {0x04ce, SDK_LOLLIPOP}, {0x04d8, SDK_LOLLIPOP_MR1}, {0x04f1, SDK_MARSHMALLOW}, {0x0527, SDK_NOUGAT}, {0x0530, SDK_NOUGAT_MR1}, {0x0568, SDK_O}, {0x056d, SDK_O_MR1}, }; static bool less_entry_id(const std::pair<uint16_t, ApiVersion>& p, uint16_t entryId) { return p.first < entryId; } ApiVersion FindAttributeSdkLevel(const ResourceId& id) { if (id.package_id() != 0x01 || id.type_id() != 0x01) { return 0; } auto iter = std::lower_bound(sAttrIdMap.begin(), sAttrIdMap.end(), id.entry_id(), less_entry_id); if (iter == sAttrIdMap.end()) { return SDK_LOLLIPOP_MR1; } return iter->second; } std::pair<StringPiece, ApiVersion> GetDevelopmentSdkCodeNameAndVersion() { return std::make_pair(StringPiece(sDevelopmentSdkCodeName), sDevelopmentSdkLevel); } } // namespace aapt
28.974684
99
0.707296
[ "vector" ]
8ec438c711812b360c1eb3dbcb5fb4a92e016934
27,260
cc
C++
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/interactionmodel/conditional_event.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/interactionmodel/conditional_event.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/interactionmodel/conditional_event.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/actions/sdk/v2/interactionmodel/conditional_event.proto #include "google/actions/sdk/v2/interactionmodel/conditional_event.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_google_2factions_2fsdk_2fv2_2finteractionmodel_2fevent_5fhandler_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EventHandler_google_2factions_2fsdk_2fv2_2finteractionmodel_2fevent_5fhandler_2eproto; namespace google { namespace actions { namespace sdk { namespace v2 { namespace interactionmodel { class ConditionalEventDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<ConditionalEvent> _instance; } _ConditionalEvent_default_instance_; } // namespace interactionmodel } // namespace v2 } // namespace sdk } // namespace actions } // namespace google static void InitDefaultsConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::actions::sdk::v2::interactionmodel::_ConditionalEvent_default_instance_; new (ptr) ::google::actions::sdk::v2::interactionmodel::ConditionalEvent(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::actions::sdk::v2::interactionmodel::ConditionalEvent::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_ConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto}, { &scc_info_EventHandler_google_2factions_2fsdk_2fv2_2finteractionmodel_2fevent_5fhandler_2eproto.base,}}; void InitDefaults_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto() { ::google::protobuf::internal::InitSCC(&scc_info_ConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto.base); } ::google::protobuf::Metadata file_level_metadata_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto[1]; constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = nullptr; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = nullptr; const ::google::protobuf::uint32 TableStruct_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::interactionmodel::ConditionalEvent, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::interactionmodel::ConditionalEvent, condition_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::interactionmodel::ConditionalEvent, transition_to_scene_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::interactionmodel::ConditionalEvent, handler_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::actions::sdk::v2::interactionmodel::ConditionalEvent)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::actions::sdk::v2::interactionmodel::_ConditionalEvent_default_instance_), }; ::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = { {}, AddDescriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, "google/actions/sdk/v2/interactionmodel/conditional_event.proto", schemas, file_default_instances, TableStruct_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto::offsets, file_level_metadata_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, 1, file_level_enum_descriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, file_level_service_descriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, }; const char descriptor_table_protodef_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto[] = "\n>google/actions/sdk/v2/interactionmodel" "/conditional_event.proto\022&google.actions" ".sdk.v2.interactionmodel\032:google/actions" "/sdk/v2/interactionmodel/event_handler.p" "roto\032\037google/api/field_behavior.proto\"\230\001" "\n\020ConditionalEvent\022\026\n\tcondition\030\001 \001(\tB\003\340" "A\002\022 \n\023transition_to_scene\030\002 \001(\tB\003\340A\001\022J\n\007" "handler\030\003 \001(\01324.google.actions.sdk.v2.in" "teractionmodel.EventHandlerB\003\340A\001B\235\001\n*com" ".google.actions.sdk.v2.interactionmodelB" "\025ConditionalEventProtoP\001ZVgoogle.golang." "org/genproto/googleapis/actions/sdk/v2/i" "nteractionmodel;interactionmodelb\006proto3" ; ::google::protobuf::internal::DescriptorTable descriptor_table_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = { false, InitDefaults_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, descriptor_table_protodef_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, "google/actions/sdk/v2/interactionmodel/conditional_event.proto", &assign_descriptors_table_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, 520, }; void AddDescriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto() { static constexpr ::google::protobuf::internal::InitFunc deps[2] = { ::AddDescriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fevent_5fhandler_2eproto, ::AddDescriptors_google_2fapi_2ffield_5fbehavior_2eproto, }; ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto, deps, 2); } // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto = []() { AddDescriptors_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto(); return true; }(); namespace google { namespace actions { namespace sdk { namespace v2 { namespace interactionmodel { // =================================================================== void ConditionalEvent::InitAsDefaultInstance() { ::google::actions::sdk::v2::interactionmodel::_ConditionalEvent_default_instance_._instance.get_mutable()->handler_ = const_cast< ::google::actions::sdk::v2::interactionmodel::EventHandler*>( ::google::actions::sdk::v2::interactionmodel::EventHandler::internal_default_instance()); } class ConditionalEvent::HasBitSetters { public: static const ::google::actions::sdk::v2::interactionmodel::EventHandler& handler(const ConditionalEvent* msg); }; const ::google::actions::sdk::v2::interactionmodel::EventHandler& ConditionalEvent::HasBitSetters::handler(const ConditionalEvent* msg) { return *msg->handler_; } void ConditionalEvent::clear_handler() { if (GetArenaNoVirtual() == nullptr && handler_ != nullptr) { delete handler_; } handler_ = nullptr; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ConditionalEvent::kConditionFieldNumber; const int ConditionalEvent::kTransitionToSceneFieldNumber; const int ConditionalEvent::kHandlerFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ConditionalEvent::ConditionalEvent() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.actions.sdk.v2.interactionmodel.ConditionalEvent) } ConditionalEvent::ConditionalEvent(const ConditionalEvent& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); condition_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.condition().size() > 0) { condition_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.condition_); } transition_to_scene_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.transition_to_scene().size() > 0) { transition_to_scene_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transition_to_scene_); } if (from.has_handler()) { handler_ = new ::google::actions::sdk::v2::interactionmodel::EventHandler(*from.handler_); } else { handler_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.actions.sdk.v2.interactionmodel.ConditionalEvent) } void ConditionalEvent::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_ConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto.base); condition_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); transition_to_scene_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); handler_ = nullptr; } ConditionalEvent::~ConditionalEvent() { // @@protoc_insertion_point(destructor:google.actions.sdk.v2.interactionmodel.ConditionalEvent) SharedDtor(); } void ConditionalEvent::SharedDtor() { condition_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); transition_to_scene_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete handler_; } void ConditionalEvent::SetCachedSize(int size) const { _cached_size_.Set(size); } const ConditionalEvent& ConditionalEvent::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_ConditionalEvent_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto.base); return *internal_default_instance(); } void ConditionalEvent::Clear() { // @@protoc_insertion_point(message_clear_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; condition_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); transition_to_scene_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == nullptr && handler_ != nullptr) { delete handler_; } handler_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* ConditionalEvent::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<ConditionalEvent*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string condition = 1 [(.google.api.field_behavior) = REQUIRED]; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.interactionmodel.ConditionalEvent.condition"); object = msg->mutable_condition(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string transition_to_scene = 2 [(.google.api.field_behavior) = OPTIONAL]; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.interactionmodel.ConditionalEvent.transition_to_scene"); object = msg->mutable_transition_to_scene(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // .google.actions.sdk.v2.interactionmodel.EventHandler handler = 3 [(.google.api.field_behavior) = OPTIONAL]; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::actions::sdk::v2::interactionmodel::EventHandler::_InternalParse; object = msg->mutable_handler(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ConditionalEvent::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string condition = 1 [(.google.api.field_behavior) = REQUIRED]; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_condition())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->condition().data(), static_cast<int>(this->condition().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.condition")); } else { goto handle_unusual; } break; } // string transition_to_scene = 2 [(.google.api.field_behavior) = OPTIONAL]; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_transition_to_scene())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->transition_to_scene().data(), static_cast<int>(this->transition_to_scene().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.transition_to_scene")); } else { goto handle_unusual; } break; } // .google.actions.sdk.v2.interactionmodel.EventHandler handler = 3 [(.google.api.field_behavior) = OPTIONAL]; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_handler())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:google.actions.sdk.v2.interactionmodel.ConditionalEvent) return true; failure: // @@protoc_insertion_point(parse_failure:google.actions.sdk.v2.interactionmodel.ConditionalEvent) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ConditionalEvent::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string condition = 1 [(.google.api.field_behavior) = REQUIRED]; if (this->condition().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->condition().data(), static_cast<int>(this->condition().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.condition"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->condition(), output); } // string transition_to_scene = 2 [(.google.api.field_behavior) = OPTIONAL]; if (this->transition_to_scene().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->transition_to_scene().data(), static_cast<int>(this->transition_to_scene().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.transition_to_scene"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->transition_to_scene(), output); } // .google.actions.sdk.v2.interactionmodel.EventHandler handler = 3 [(.google.api.field_behavior) = OPTIONAL]; if (this->has_handler()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::handler(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.actions.sdk.v2.interactionmodel.ConditionalEvent) } ::google::protobuf::uint8* ConditionalEvent::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string condition = 1 [(.google.api.field_behavior) = REQUIRED]; if (this->condition().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->condition().data(), static_cast<int>(this->condition().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.condition"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->condition(), target); } // string transition_to_scene = 2 [(.google.api.field_behavior) = OPTIONAL]; if (this->transition_to_scene().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->transition_to_scene().data(), static_cast<int>(this->transition_to_scene().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.interactionmodel.ConditionalEvent.transition_to_scene"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->transition_to_scene(), target); } // .google.actions.sdk.v2.interactionmodel.EventHandler handler = 3 [(.google.api.field_behavior) = OPTIONAL]; if (this->has_handler()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::handler(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.actions.sdk.v2.interactionmodel.ConditionalEvent) return target; } size_t ConditionalEvent::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string condition = 1 [(.google.api.field_behavior) = REQUIRED]; if (this->condition().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->condition()); } // string transition_to_scene = 2 [(.google.api.field_behavior) = OPTIONAL]; if (this->transition_to_scene().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->transition_to_scene()); } // .google.actions.sdk.v2.interactionmodel.EventHandler handler = 3 [(.google.api.field_behavior) = OPTIONAL]; if (this->has_handler()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *handler_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ConditionalEvent::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) GOOGLE_DCHECK_NE(&from, this); const ConditionalEvent* source = ::google::protobuf::DynamicCastToGenerated<ConditionalEvent>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.actions.sdk.v2.interactionmodel.ConditionalEvent) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.actions.sdk.v2.interactionmodel.ConditionalEvent) MergeFrom(*source); } } void ConditionalEvent::MergeFrom(const ConditionalEvent& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.condition().size() > 0) { condition_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.condition_); } if (from.transition_to_scene().size() > 0) { transition_to_scene_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transition_to_scene_); } if (from.has_handler()) { mutable_handler()->::google::actions::sdk::v2::interactionmodel::EventHandler::MergeFrom(from.handler()); } } void ConditionalEvent::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) if (&from == this) return; Clear(); MergeFrom(from); } void ConditionalEvent::CopyFrom(const ConditionalEvent& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.actions.sdk.v2.interactionmodel.ConditionalEvent) if (&from == this) return; Clear(); MergeFrom(from); } bool ConditionalEvent::IsInitialized() const { return true; } void ConditionalEvent::Swap(ConditionalEvent* other) { if (other == this) return; InternalSwap(other); } void ConditionalEvent::InternalSwap(ConditionalEvent* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); condition_.Swap(&other->condition_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); transition_to_scene_.Swap(&other->transition_to_scene_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(handler_, other->handler_); } ::google::protobuf::Metadata ConditionalEvent::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto); return ::file_level_metadata_google_2factions_2fsdk_2fv2_2finteractionmodel_2fconditional_5fevent_2eproto[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace interactionmodel } // namespace v2 } // namespace sdk } // namespace actions } // namespace google namespace google { namespace protobuf { template<> PROTOBUF_NOINLINE ::google::actions::sdk::v2::interactionmodel::ConditionalEvent* Arena::CreateMaybeMessage< ::google::actions::sdk::v2::interactionmodel::ConditionalEvent >(Arena* arena) { return Arena::CreateInternal< ::google::actions::sdk::v2::interactionmodel::ConditionalEvent >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
47.16263
317
0.747542
[ "object" ]
8ec4a666c75021376ab7bfa13b06c2769fb12386
1,636
cpp
C++
assignments/a2-interpolation/particlecubic.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
assignments/a2-interpolation/particlecubic.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
assignments/a2-interpolation/particlecubic.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
#include "atkui/framework.h" using namespace glm; class ParticleCubic : public atkui::Framework { public: ParticleCubic() : atkui::Framework(atkui::Orthographic) { } void setup() { float interval = 1.0f / (60 + 1); points.push_back(B0); for (int i = 1; i <= 60; i++) { float t = interval * i; points.push_back(LERPALL(B0, B1, B2, B3, t)); } points.push_back(B3); } void scene() { // after 5 seconds t will go back to 0 and the dot will wrap back around float t= fmod(elapsedTime(), 5.0f) / 5.0f; position = LERPALL(B0, B1, B2, B3, t); setColor(vec3(1,1,0)); drawSphere(position, 10); setColor(vec3(0,1,1)); for (int i = 0; i < points.size() - 1; i++) { drawLine(points[i], points[i + 1]); } } vec3 LERP(const vec3& b1, const vec3& b2, float t) { return b1 * (1 - t) + b2 * t; } vec3 LERPALL(const vec3& b0, const vec3& b1, const vec3& b2, const vec3& b3, float t) { vec3 b01 = LERP(b0, b1, t); vec3 b11 = LERP(b1, b2, t); vec3 b21 = LERP(b2, b3, t); vec3 b02 = LERP(b01, b11, t); vec3 b12 = LERP(b11, b21, t); return LERP(b02, b12, t); } private: // hard coded control points, so I can create a curve for the dot to travel through vec3 B0 = vec3(width()*0.25f, height()*0.20f, 0); vec3 B1 = vec3(width()/3, height()*0.6f, 0); vec3 B2 = vec3(width()*2/3, height()*0.4f, 0); vec3 B3 = vec3(width()*.75, height()*0.80f, 0); vec3 position; std::vector<vec3> points; }; int main(int argc, char** argv) { ParticleCubic viewer; viewer.run(); }
25.169231
89
0.567848
[ "vector" ]
8ecc9a443ce6d14a63b86ea8feb57c361b4106eb
20,293
hpp
C++
framework/areg/base/private/posix/SynchLockAndWaitIX.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/base/private/posix/SynchLockAndWaitIX.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/base/private/posix/SynchLockAndWaitIX.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/base/private/posix/SynchLockAndWaitIX.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Lock and wait object for POSIX synchronization objects. * ************************************************************************/ /************************************************************************ * Includes ************************************************************************/ #include "areg/base/GEGlobal.h" #if defined(_POSIX) || defined(POSIX) #include "areg/base/NECommon.hpp" #include "areg/base/private/posix/NESynchTypesIX.hpp" #include "areg/base/IESynchObject.hpp" #include "areg/base/TEHashMap.hpp" #include "areg/base/TELinkedList.hpp" #include "areg/base/TEFixedArray.hpp" #include "areg/base/TEResourceMap.hpp" #include "areg/base/TEResourceListMap.hpp" #include <pthread.h> /************************************************************************ * dependencies. ************************************************************************/ class IEWaitableBaseIX; class SynchLockAndWaitIX; class SynchLockAndWaitIX; ////////////////////////////////////////////////////////////////////////// // SynchLockAndWaitIX class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief LockAndWait object that makes locking of single and multiple objects and waits until * one or all objects are signaled. The waiting criteria depends on the flag. * There is a limitation of waiting objects at once, and the maximum numbers are * equal to NECommon::MAXIMUM_WAITING_OBJECTS. * Use static methods for waiting functionalities. The internal methods are hidden. **/ class SynchLockAndWaitIX { /** * \brief Declaration of list helper object. **/ using ImplListLockAndWait = TEListImpl<const SynchLockAndWaitIX *>; /** * \brief The list of LockAndWait objects. **/ using ListLockAndWait = TELinkedList<SynchLockAndWaitIX *, SynchLockAndWaitIX *, ImplListLockAndWait>; /** * \brief Declaration of hash map helper object. **/ using ImplMapLockAndWait = TEPointerHashMapImpl<const IEWaitableBaseIX *, ListLockAndWait &>; /** * \brief The hash map container of waitable object and LockAndWait lists. **/ using MapLockAndWait = TEHashMap<IEWaitableBaseIX *, ListLockAndWait, IEWaitableBaseIX *, ListLockAndWait &, ImplMapLockAndWait>; ////////////////////////////////////////////////////////////////////////// // SynchWaitableMapIX class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief The helper class of resource list map that contains helper functions implementation. **/ class ImplResourceListMap : public TEResourceListMapImpl<IEWaitableBaseIX *, SynchLockAndWaitIX, ListLockAndWait> { public: /** * \brief Called when all resources are removed. * This function is called from RemoveAllResources() for every single * resource being unregistered. * \param Key The Key value of resource. * \param List The list of resource objects. **/ inline void implCleanResourceList( IEWaitableBaseIX * & /* Key */, ListLockAndWait & List ) { List.removeAll(); } /** * \brief Called when need to add resource object to the list. * \param List The list of resource objects. * \param Resource The resource object to add to the list. **/ inline void implAddResource( ListLockAndWait & List, SynchLockAndWaitIX * Resource ) { List.pushLast(Resource); } /** * \brief Called when need to remove resource object from the list. * \param List The list of resource objects. * \param Resource The resource object to remove from the list. **/ inline bool implRemoveResource( ListLockAndWait & List, SynchLockAndWaitIX * Resource ) { return List.removeEntry( Resource ); } }; /** * \brief The resource list map of waitable object where the keys are waitable objects * and the resource objects are WaitAndLock objects in the list. The WaitAndLock * objects in the entire map are not unique, but should be unique in the list. **/ using SynchResourceMapIX = TELockResourceListMap<IEWaitableBaseIX *, SynchLockAndWaitIX, MapLockAndWait, ListLockAndWait, ImplResourceListMap>; ////////////////////////////////////////////////////////////////////////// // The resource map for timer. ////////////////////////////////////////////////////////////////////////// /** * \brief Helper class of hash map basic methods implementation. **/ using ImplMapWaitID = TEHashMapImpl<id_type, SynchLockAndWaitIX * >; /** * \brief The resource map of waitable, where keys are id_type and the values are WaitAndLock objects **/ using MapWaitID = TEIdHashMap<SynchLockAndWaitIX *, SynchLockAndWaitIX *, ImplMapWaitID>; /** * \brief Helper object for resource map basic method implementations **/ using ImplWaitIDResource= TEResourceMapImpl<id_type, SynchLockAndWaitIX>; /** * \brief Resource map of waitable where the keys are id_type (thread ID) and the values are * LockAndWait objects. It is used in the timer. **/ using MapWaitIDResource = TELockResourceMap<id_type, SynchLockAndWaitIX, MapWaitID, ImplWaitIDResource>; ////////////////////////////////////////////////////////////////////////// // Friend classes ////////////////////////////////////////////////////////////////////////// friend class TimerManager; friend class WaitableTimerIX; ////////////////////////////////////////////////////////////////////////// // Constants and statics ////////////////////////////////////////////////////////////////////////// private: /** * \brief SynchLockAndWaitIX::eWaitType * Describes the waiting type. **/ typedef enum class E_WaitType { WaitSingleObject //!< Waits a single object , WaitMultipleObjects //!< Waits for multiple object } eWaitType; /** * \brief SynchLockAndWaitIX::eEventFired * Describes the fired state of each event. **/ typedef enum class E_EventFired { EventFiredNone //!< No event has been fired. , EventFiredOne //!< Fired one event. , EventFiredAll //!< All waiting events are fired. } eEventFired; /** * \brief The fixed array of waitable. The maximum size of array is NECommon::MAXIMUM_WAITING_OBJECTS **/ using WaitingList = TEFixedArray<IEWaitableBaseIX *, IEWaitableBaseIX *>; ////////////////////////////////////////////////////////////////////////// // Public static methods. ////////////////////////////////////////////////////////////////////////// public: /** * \brief Call to lock the synchronization object of wait until it is released by other thread. * If waitable is signaled, the function immediately returns. If waitable is not signaled, * the function block thread until either waitable is signaled or timeout expires. In case * of some waitable such as Mutex, this call takes the ownership. in case of Synchronization Events * this may reset signaled state or leave in signaled state, depending on Synchronization Event types. * For more details see the description of each waitable object. * \param synchWait The waitable object to check the signaled state. * \param msTimeout The timeout in milliseconds to wait until waitable is signaled. * If NECommon::WAIT_INFINITE, it will wait until event is signaled or failed. * Any other value indicates timeout to wait. * \return It returns one of following values: * - NESynchTypesIX::SynchObject0 if waitable was signaled; * - NESynchTypesIX::SynchObjectTimeout if waiting timeout is expired; * - NESynchTypesIX::SynchWaitInterrupted if waiting was interrupted by such event like timer; * - NESynchTypesIX::SynchObject0Error if error happened. For example, the waitable is invalidated. **/ static int waitForSingleObject( IEWaitableBaseIX & synchWait, unsigned int msTimeout = NECommon::WAIT_INFINITE ); /** * \brief Call to lock and wait the list of synchronization objects until one or all objects are signaled. * The waiting criteria depends on waitable signal state, waitAll parameter and timeout. * There can be maximum NECommon::MAXIMUM_WAITING_OBJECTS in the list to wait. This limitation is synchronized * with Microsoft limitation. In practice, normally there are very few events in the list. * In case of some waitable such as Mutex, this call takes the ownership. in case of Synchronization Events * this may reset signaled state or leave in signaled state, depending on Synchronization Event types. * For more details see the description of each waitable object. * \param listWaitables The list of waitables to check the signaled state. There should be no more than * NECommon::MAXIMUM_WAITING_OBJECTS entries in the list. * \param count The number of waitables in the list. There should be no more than * NECommon::MAXIMUM_WAITING_OBJECTS entries. * \param waitAll If true, the call is locks the thread until all waitables in the list are signaled. * If false, any waitable in signaled state unlocks the thread. * \param msTimeout The timeout in milliseconds to wait until waitable is signaled. * If NECommon::WAIT_INFINITE, it will wait until event is signaled or failed. * Any other value indicates timeout to wait. * \return It returns one of following values: * - NESynchTypesIX::SynchObject0 + N if 'waitAll' flag is false and waitable was signaled, where 'N' is the index of waitable in the list. * - NESynchTypesIX::SynchObjectAll if 'waitAll' flag is true and all waitables are signaled. * - NESynchTypesIX::SynchObjectTimeout if waiting timeout is expired; * - NESynchTypesIX::SynchWaitInterrupted if waiting was interrupted by such event like timer; * - NESynchTypesIX::SynchObject0Error + N if error happened, where 'N' is the indes of failed waitalbe object. For example, the waitable is invalidated. **/ static int waitForMultipleObjects( IEWaitableBaseIX ** listWaitables, int count, bool waitAll = false, unsigned int msTimeout = NECommon::WAIT_INFINITE); /** * \brief Called by waitable object to indicate that it is in signaled state. * \param synchWaitable The waitable object that is in signaled state. * \return Returns the number of threads that are notified. * In case of Mutex this should be one. In case of Synchronization Event there can be multiple threads. * For more details see description of each waitable object **/ static int eventSignaled( IEWaitableBaseIX & synchWaitable ); /** * \brief Called by waitable object to indicate wait failure. For example, when waitable object is invalidated. * This call unlocks all threads that wait for event and the waiting return indicates error. * \param synchWaitable The waitable object that should indicate error. **/ static void eventFailed( IEWaitableBaseIX & synchWaitable ); /** * \brief Call to remove waitable object from the waiting list. * \param synchWaitable The waitable object to remove from the list. **/ static void eventRemove( IEWaitableBaseIX & synchWaitable ); /** * \brief Checks whether the waitable is registered or not. * \param synchWaitable Waitable to check the registration. * \return Returns true if waitable is registered. **/ static bool isWaitableRegistered( IEWaitableBaseIX & synchWaitable ); /** * \brief Notifies the asynchronous execution within a locked thread. This call breaks waiting process of thread * that can be locked again when finished processing asynchronous execution. * \param threadId The ID of the thread that is going to break waiting. * \return Returns true if operation succeeded. The operation can fail if thread is not locked. **/ static bool notifyAsynchSignal( id_type threadId ); ////////////////////////////////////////////////////////////////////////// // Hidden constructor / destructor ////////////////////////////////////////////////////////////////////////// private: /** * \brief Initializes WaitAndLock object, sets flags and checks signaled sate of waitables. * \param listWaitables The list of waitables. The maximum number of entries should be NECommon::MAXIMUM_WAITING_OBJECTS * \param count The number of waitables in the list. The maximum number of entries should be NECommon::MAXIMUM_WAITING_OBJECTS. * \param matchCondition The signaled state matching criteria. Either it should have exact match, i.e. wait all events to be signaled, * or it should wait for any event to be in signaled state. * \param msTimeout Initializes the timeout in milliseconds to wait. **/ SynchLockAndWaitIX( IEWaitableBaseIX ** listWaitables, int count, NESynchTypesIX::eMatchCondition matchCondition, unsigned int msTimeout ); /** * \brief Destructor. **/ ~SynchLockAndWaitIX( void ); ////////////////////////////////////////////////////////////////////////// // Hidden operations and attributes ////////////////////////////////////////////////////////////////////////// /** * \brief Returns true if no event in the list is fired. **/ inline bool _noEventFired( void ) const; /** * \brief Initializes internal POSIX objects. Returns true if initialization succeeded. **/ inline bool _initPosixSynchObjects( void ); /** * \brief Releases internal POSIX objects to free resources. **/ inline void _releasePosixSynchObjects( void ); /** * \brief Returns true if object is valid. The LockAndWait object is valid if internal POSIX objects are * initialized and the waiting list not empty. **/ inline bool _isValid( void ) const; /** * \brief Locks the WaitAndLock object, waits for event fired criteria. * This may block the calling thread. * \return Returns true if locking succeeded. **/ inline bool _lock( void ); /** * \brief Unlocks WaitAndLock object. **/ inline void _unlock( void ); /** * \brief Called to wait for condition variable. Either it waits with infinite wait flag or with timeout. * \return Returns POSIX error code. If 0, the waiting method succeeded. **/ inline int _waitCondition( void ); /** * \brief Returns the index of registered waitable in the list. * \param synchWaitable The instance of waitable object to lookup in the list. **/ inline int _getWaitableIndex( const IEWaitableBaseIX & synchWaitable ) const; /** * \brief Called to notify the event has been fired. * \return Returns true if succeeded to notify. **/ inline bool _notifyEvent( void ); /** * \brief Checks whether the waiting list is empty. **/ inline bool _isEmpty( void ) const; /** * \brief Checks whether the waitable event is fired or not. * \param synchObject The waitable object to check. * \return Returns one of event fired state. **/ NESynchTypesIX::eSynchObjectFired _checkEventFired( IEWaitableBaseIX & synchObject ); /** * \brief Called to notify threads to take fired event ownership. * \param firedEvent The index of fired event in the list that notifies the threads to take ownership. * \return Returns true if threads are notified or took ownership. **/ bool _requestOwnership( const NESynchTypesIX::eSynchObjectFired firedEvent ); /** * \brief Called by timer manager to signal asynchronous signal. It is used for waitable timers. **/ bool _notifyAsynchSignal( void ); ////////////////////////////////////////////////////////////////////////// // Hidden member variables. ////////////////////////////////////////////////////////////////////////// private: /** * \brief Describes the waiting type. Either should wait for all events or for any. **/ const eWaitType mDescribe; /** * \brief Describes the lock and wait condition. **/ const NESynchTypesIX::eMatchCondition mMatchCondition; /** * \brief Timeout in milliseconds to wait when blocks the thread. **/ const unsigned int mWaitTimeout; /** * \brief The ID of thread that instantiated LockAndWait object. **/ const pthread_t mContext; /** * \brief Internal POSIX mutex object to synchronize data access. **/ mutable pthread_mutex_t mPosixMutex; /** * \brief The POSIX mutex validity flag. **/ mutable bool mMutexValid; /** * \brief Internal POSIX mutex attribute to initialize mutex. **/ mutable pthread_mutexattr_t mPosixMutexAttr; /** * \brief The POSIX mutex attribute validity flag. **/ mutable bool mMutexAttrValid; /** * \brief Internal POSIX conditional variable. **/ pthread_cond_t mCondVariable; /** * \brief The POSIX conditional variable validity flag. **/ bool mCondVarValid; /** * \brief Internal POSIX conditional variable attribute **/ pthread_condattr_t mCondAttribute; /** * \brief The POSIX conditional variable attribute validity flag. **/ bool mCondAttrValid; /** * \brief Indicates the fired event object or error code. **/ NESynchTypesIX::eSynchObjectFired mFiredEntry; /** * \brief The list of waitables. **/ WaitingList mWaitingList; /** * \brief Static list of waitables, where keys are id_type and values are waitables. **/ static MapWaitIDResource _mapWaitIdResource; /** * \brief The singleton instance of synchronization resource map. */ static SynchResourceMapIX _theSynchResourceMapIX; ////////////////////////////////////////////////////////////////////////// // Forbidden calls. ////////////////////////////////////////////////////////////////////////// private: SynchLockAndWaitIX( void ) = delete; DECLARE_NOCOPY_NOMOVE( SynchLockAndWaitIX ); }; #endif // defined(_POSIX) || defined(POSIX)
45.911765
170
0.59114
[ "object" ]
8ecea50f14811fb3037fdd6fe37dff64a99db976
4,874
cpp
C++
src/tsppd/solver/ruland/ruland_tsp_solver.cpp
ryanjoneil/tsppd
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
4
2018-03-30T20:58:57.000Z
2018-04-25T01:48:09.000Z
src/tsppd/solver/ruland/ruland_tsp_solver.cpp
ryanjoneil/tsppd
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
7
2019-04-21T13:42:09.000Z
2019-05-09T15:49:56.000Z
src/tsppd/solver/ruland/ruland_tsp_solver.cpp
ryanjoneil/tsppd-hybrid
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
1
2020-03-01T16:19:18.000Z
2020-03-01T16:19:18.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the tsppd program and library for solving */ /* Traveling Salesman Problems with Pickup and Delivery. tsppd requires */ /* other commercial and open source software to build. tsppd is decribed */ /* in the paper "Exact Methods for Solving Traveling Salesman Problems */ /* with Pickup and Delivery in Real Time". */ /* */ /* Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu> */ /* */ /* tsppd is distributed under the terms of the ZIB Academic License. */ /* You should have received a copy of the ZIB Academic License along with */ /* tsppd. See the file LICENSE. If not, email roneil1@gmu.edu. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <cmath> #include <memory> #include <tsppd/data/tsppd_search_statistics.h> #include <tsppd/solver/tsp_solver.h> #include <tsppd/solver/ruland/ruland_tsp_solver.h> #include <tsppd/solver/ruland/callback/ruland_subtour_elimination_callback.h> #include <tsppd/solver/ruland/callback/ruland_tsp_callback_handler.h> using namespace TSPPD::Data; using namespace TSPPD::IO; using namespace TSPPD::Solver; using namespace std; RulandTSPSolver::RulandTSPSolver( const TSPPDProblem& problem, const map<string, string> options, TSPSolutionWriter& writer) : TSPSolver(problem, options, writer), env(), model(env), arcs(), subtour_finder(problem), callbacks() { // Silence output. model.getEnv().set(GRB_IntParam_OutputFlag, 0); // Lazy constraints are used for subtour elimination. model.set(GRB_IntParam_LazyConstraints, true); initialize_tsp_options(); initialize_variables(); initialize_two_matching_relaxation(); } TSPPDSolution RulandTSPSolver::solve() { auto solver = static_cast<RulandTSPSolver*>(this); solver->initialize_callbacks(); // Set time limit. if (time_limit > 0) model.set(GRB_DoubleParam_TimeLimit, time_limit / 1000.0); // Set solution limit. if (solution_limit > 0) model.set(GRB_IntParam_SolutionLimit, solution_limit); // Set thread count. model.set(GRB_IntParam_Threads, threads); RulandTSPCallbackHandler callback(solver, problem, arcs, callbacks, writer); model.setCallback(&callback); model.optimize(); if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { // Convert arc variables into boolean values for subtour finder. map<pair<unsigned int, unsigned int>, bool> arc_values{}; for (auto pair : arcs) arc_values[pair.first] = *model.get(GRB_DoubleAttr_X, &(pair.second), 1) > 0.5; auto subtours = subtour_finder.subtours(arc_values); TSPPDSolution solution(problem, subtours[0]); TSPPDSearchStatistics stats(solution); stats.dual = ceil(model.get(GRB_DoubleAttr_ObjBound)); stats.optimal = true; writer.write(stats, true); return solution; } return {problem, problem.nodes}; } void RulandTSPSolver::initialize_tsp_options() { if (options["sec"] == "") options["sec"] = "subtour"; } void RulandTSPSolver::initialize_variables() { auto start_index = problem.index("+0"); auto end_index = problem.index("-0"); for (unsigned int from = 0; from < problem.nodes.size(); ++from) { for (unsigned int to = from + 1; to < problem.nodes.size(); ++to) { auto lb = (from == start_index && to == end_index) ? 1 : 0; auto var = model.addVar(lb, 1, problem.cost(from, to), GRB_BINARY); // Arc costs are symmetric. Recording them in both directions as the same // variable keeps us from having to do complicated transformations later. arcs[{from, to}] = var; arcs[{to, from}] = var; } } } void RulandTSPSolver::initialize_two_matching_relaxation() { for (unsigned int node1 = 0; node1 < problem.nodes.size(); ++node1) { GRBLinExpr expr = 0; for (unsigned int node2 = 0; node2 < problem.nodes.size(); ++node2) { if (node1 == node2) continue; expr += arcs[{node1, node2}]; } model.addConstr(expr == 2); } } void RulandTSPSolver::initialize_callbacks() { callbacks.push_back( static_cast<shared_ptr<RulandTSPCallback>>( make_shared<RulandSubtourEliminationCallback>(options["sec"], problem, arcs) ) ); }
37.206107
106
0.590685
[ "model" ]
8ede9d87743333ef88bdf89b3dbec74a04ee6288
1,406
cpp
C++
Master-Engine/MasterEngineLibAggregator/Vector2Wrapper.cpp
palmelund/Master-Engine
d947ca31c27e91bf72e22074883eec64e9c6fb9d
[ "MIT" ]
null
null
null
Master-Engine/MasterEngineLibAggregator/Vector2Wrapper.cpp
palmelund/Master-Engine
d947ca31c27e91bf72e22074883eec64e9c6fb9d
[ "MIT" ]
null
null
null
Master-Engine/MasterEngineLibAggregator/Vector2Wrapper.cpp
palmelund/Master-Engine
d947ca31c27e91bf72e22074883eec64e9c6fb9d
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Vector2Wrapper.h" #include <vector> #include "thread" #include "ThreadPool.h" #include "Vector2Delta.h" Vector2Wrapper::Vector2Wrapper() { value_ = {}; } void Vector2Wrapper::operator+=(const sf::Vector2f& rhs) { auto* pointer_deltas = &MasterEngine::LibAggregator::ThreadPool::deltas[std::this_thread::get_id()]; if (pointer_deltas->find(this) != pointer_deltas->end()) { auto delta = static_cast<Vector2Delta*>(pointer_deltas->at(this)); delta->addition(rhs); } else { auto new_delta = new Vector2Delta{ this }; new_delta->addition(rhs); pointer_deltas->insert(std::pair<void*, BaseDelta*>(this, new_delta)); } } void Vector2Wrapper::operator=(const sf::Vector2f& rhs) { assign(rhs, 1); } void Vector2Wrapper::assign(const sf::Vector2f& rhs, const int priority) { auto* pointer_deltas = &MasterEngine::LibAggregator::ThreadPool::deltas[std::this_thread::get_id()]; if (pointer_deltas->find(this) != pointer_deltas->end()) { auto delta = static_cast<Vector2Delta*>(pointer_deltas->at(this)); delta->assign(rhs, priority); } else { auto new_delta = new Vector2Delta{ this }; new_delta->assign(rhs, priority); pointer_deltas->insert(std::pair<void*, BaseDelta*>(this, new_delta)); } } sf::Vector2f Vector2Wrapper::get_vector() const { return value_; } void Vector2Wrapper::set_vector(const sf::Vector2f val) { value_ = val; }
21.30303
101
0.71266
[ "vector" ]
8eebe74a15adb327a0937d7a4b0bd8301da7088c
2,487
cc
C++
src/validate.cc
cchudant/anitomy-js
1d0dd38b443fb78776e0fd43d7a81822948e05bf
[ "MIT" ]
1
2020-04-01T17:06:59.000Z
2020-04-01T17:06:59.000Z
src/validate.cc
cchudant/anitomy-js
1d0dd38b443fb78776e0fd43d7a81822948e05bf
[ "MIT" ]
null
null
null
src/validate.cc
cchudant/anitomy-js
1d0dd38b443fb78776e0fd43d7a81822948e05bf
[ "MIT" ]
null
null
null
#include "validate.hpp" #include "util.hpp" namespace anitomy_js { using Nan::FunctionCallbackInfo; using Nan::Get; using Nan::Has; using Nan::Set; using Nan::To; using Nan::Undefined; using v8::Local; using v8::Object; using v8::Value; const char *ValidateData(const FunctionCallbackInfo<Value> &args, Local<Value> &input, Local<Value> &options) { Local<Value> callback = Undefined(); return ValidateData(args, input, options, callback); } const char *ValidateData(const FunctionCallbackInfo<Value> &args, Local<Value> &input, Local<Value> &options, Local<Value> &callback) { auto length = args.Length(); if (length < 1) { return "Input must be either a string or array"; } else { input = args[0]; } auto input_error = ValidateInput(args[0]); if (input_error) { return input_error; } bool async = callback.IsEmpty(); if (async && length == 2) { callback = args[1]; options = Undefined(); } else if (async && length >= 3) { callback = args[2]; options = args[1]; } else if (length == 1) { callback = Undefined(); options = Undefined(); } else { callback = Undefined(); options = args[1]; } auto options_error = ValidateOptions(options); if (options_error) { return options_error; } auto callback_error = ValidateCallback(callback); if (async && callback_error) { return callback_error; } return NULL; } const char *ValidateCallback(Local<Value> callback) { if (!callback->IsFunction()) { return "Callback must be a function"; } else { return NULL; } } const char *ValidateInput(Local<Value> input) { if (!input->IsString() && !input->IsArray()) { return "Input must be either a string or array"; } else { return NULL; } } const char *ValidateOptions(Local<Value> &value) { if (value->IsNullOrUndefined()) { return NULL; } if (!value->IsObject()) { value = Undefined(); return NULL; } auto options = To<Object>(value).ToLocalChecked(); auto delimiters = node_string("allowed_delimiters"); auto ignored = node_string("ignored_strings"); if (Has(options, delimiters).FromJust() && !Get(options, delimiters).ToLocalChecked()->IsString()) { Set(options, delimiters, Undefined()); } if (Has(options, ignored).FromJust() && !Get(options, ignored).ToLocalChecked()->IsArray()) { Set(options, ignored, Undefined()); } return NULL; } } // namespace anitomy_js
23.242991
102
0.64616
[ "object" ]
8ef3d5748089e1fbccb52dc70501bfe6e6fb4e4f
5,935
cpp
C++
leadsense/leadsenseVIO.cpp
monticle/ygz-stereo-inertial
04c253ad7b7362cf208a6f28d80c3e571192c4ec
[ "MIT" ]
null
null
null
leadsense/leadsenseVIO.cpp
monticle/ygz-stereo-inertial
04c253ad7b7362cf208a6f28d80c3e571192c4ec
[ "MIT" ]
null
null
null
leadsense/leadsenseVIO.cpp
monticle/ygz-stereo-inertial
04c253ad7b7362cf208a6f28d80c3e571192c4ec
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> #include<fstream> #include<iomanip> #include<chrono> #include<opencv2/opencv.hpp> #include<ygz/System.h> //Evo SDK header #include <evo_global_define.h>//global define #include <evo_stereocamera.h>//stereo camera #include <evo_mat.h>//evo Mat define #include <evo_matconverter.h>//evo Mat converter using namespace ygz; using namespace std; using namespace evo; using namespace evo::bino; bool genYaml(StereoParameters param, Resolution_FPS resfps){ ofstream fs("leadsense.yaml", ios_base::out); if (!fs.is_open()){ cerr << "error to open leadsense.yaml" << endl; return false; } fs << "%YAML:1.0" << endl << "---" << endl << endl; fs << "PureVisionMode: false" << endl; fs << "UseViewer: true" << endl << endl; fs << "Camera.fx: " << param.leftCam.focal.x << endl; fs << "Camera.fy: " << param.leftCam.focal.y << endl; fs << "Camera.cx: " << param.leftCam.center.x << endl; fs << "Camera.cy: " << param.leftCam.center.y << endl; fs << "Camera.k1: " << 0.0 << endl; fs << "Camera.k2: " << 0.0 << endl; fs << "Camera.p1: " << 0.0 << endl; fs << "Camera.p2: " << 0.0 << endl; fs << "Camera.width: " << resfps.width << endl; fs << "Camera.height: " << resfps.height << endl; // Camera frames per second fs << "Camera.fps: " << resfps.fps << endl; // stereo baseline[m] times fx fs << "Camera.bf: " << param.baseline() / 1000 * param.leftCam.focal.x << endl; fs.close(); return true; } StereoCamera camera; bool running; // imu std::mutex imu_lock; VecIMU vimu; std::vector<evo::imu::IMUData> imu_rawdata; void retrieveIMUData() { while (running){ imu_lock.lock(); float lastgx = -10000; imu_rawdata = camera.retrieveIMUData(); for (int i = 0; i < imu_rawdata.size(); i++) { if (lastgx != imu_rawdata.at(i).gyro[0]) { ygz::IMUData imudata = ygz::IMUData(imu_rawdata.at(i).gyro[0], imu_rawdata.at(i).gyro[1], imu_rawdata.at(i).gyro[2], imu_rawdata.at(i).accel[0], imu_rawdata.at(i).accel[1], imu_rawdata.at(i).accel[2], imu_rawdata.at(i).timestamp); vimu.push_back(imudata); lastgx = imu_rawdata.at(i).gyro[0]; } } imu_lock.unlock(); std::this_thread::sleep_for(std::chrono::microseconds(1)); } } int main(int argc, char **argv) { cout << endl << "add parameter to change resolution : ./leadsense [800|400(default)]" << endl; google::InitGoogleLogging(argv[0]); std::cout << "init evo stereo camera... " << std::endl; int width, height; int cnt = 0, limit = 100; double tempt = 0; StereoParameters stereoPara;//stereo parameter //open camera RESOLUTION_FPS_MODE res_mode = RESOLUTION_FPS_MODE_SD400_30; if (argc > 1) { int res_n = atoi(argv[1]); if (res_n == 800){ res_mode = RESOLUTION_FPS_MODE_HD800_30; } } RESULT_CODE res = camera.open(res_mode); std::cout << "stereo camera open: " << result_code2str(res) << std::endl; //show image size width = camera.getImageSizeFPS().width; height = camera.getImageSizeFPS().height; std::cout << "image width:" << width << ", height:" << height << std::endl; //check IMU if (camera.isIMUSupported() == false){ std::cout << "IMU not support for this camera." << std::endl; return 2; } if (camera.startRetrieveIMU() != RESULT_CODE::RESULT_CODE_OK){ std::cout << "Open IMU failed." << std::endl; return 3; } //camera.setIMUDataType(evo::imu::IMU_DATA_TYPE::IMU_DATA_TYPE_RAW); camera.setIMUDataType(evo::imu::IMU_DATA_TYPE::IMU_DATA_TYPE_RAW_CALIBRATED); if (genYaml(camera.getStereoParameters(), camera.getImageSizeFPS()) == false){ return 4; } // Create SLAM system. It initializes all system threads and gets ready to process frames. System system("leadsense.yaml"); // set TBC Matrix3d Rbc_; Vector3d tbc_; //Rbc_ << // 1, 0, 0, // 0, -1, 0, // 0, 0, -1; //tbc_ << // -0.0475, 0.0032, -0.004; Rbc_ << -1, 0, 0, 0, -1, 0, 0, 0, 1; tbc_ << 0.09195, 0.00, -0.0129; setting::TBC = SE3d(Rbc_, tbc_); if (res == RESULT_CODE_OK)//open camera successed { //evo Mat evo::Mat<unsigned char> evo_image; //cv Mat cv::Mat cv_image; cv::Mat imLeft, imRight; running = true; VecIMU vimu2; //std::thread imu_thread(retrieveIMUData); //imu_thread.detach(); std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now(); //main loop while (running) { // Get frames and launch the computation if (camera.grab(true) == RESULT_CODE_OK) { float lastgx = -10000; imu_rawdata = camera.retrieveIMUData(); for (int i = 0; i < imu_rawdata.size(); i++) { //if (lastgx != imu_rawdata.at(i).gyro[0]) { ygz::IMUData imudata = ygz::IMUData(imu_rawdata.at(i).gyro[0] , imu_rawdata.at(i).gyro[1], imu_rawdata.at(i).gyro[2], imu_rawdata.at(i).accel[0], imu_rawdata.at(i).accel[1], imu_rawdata.at(i).accel[2], imu_rawdata.at(i).timestamp); vimu.push_back(imudata); //lastgx = imu_rawdata.at(i).gyro[0]; } //std::cout <<"imu data size " << imu_rawdata.size() << std::endl; } evo_image = camera.retrieveImage(SIDE_SBS); //Mat convert cv_image = evoMat2cvMat(evo_image); // Read left and right images from file imLeft = cv_image(cv::Rect(0, 0, width, height)); imRight = cv_image(cv::Rect(width, 0, width, height)); double tframe = camera.getCurrentFrameTimeCode(); //cv::imshow("right", imRight); // Pass the images and imu data to the SLAM system system.AddStereoIMU(imLeft, imRight, tframe, vimu); double ttrack = std::chrono::duration_cast<std::chrono::duration<double> >(std::chrono::steady_clock::now() - t1).count(); t1 = std::chrono::steady_clock::now(); cnt++; tempt += ttrack; if (cnt == limit){ cout << "avg loop time:" << tempt / limit << endl; cnt = 0; tempt = 0; } vimu.clear(); } running = (cv::waitKey(5) != 27); } camera.stopRetrieveIMU(); camera.close(); } cout << "finished." << endl; return 0; }
28.127962
126
0.641449
[ "vector" ]
8ef56491503c594465fb46447bf3fd8cc4b7d9a6
1,557
cpp
C++
irohad/network/impl/peer_communication_service_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-01-15T08:47:16.000Z
2017-01-15T08:47:16.000Z
irohad/network/impl/peer_communication_service_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-11-08T02:34:24.000Z
2017-11-08T02:34:24.000Z
irohad/network/impl/peer_communication_service_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
null
null
null
/* Copyright Soramitsu Co., Ltd. 2016 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 "network/impl/peer_communication_service_impl.hpp" namespace iroha { namespace network { PeerCommunicationServiceImpl::PeerCommunicationServiceImpl( std::shared_ptr<OrderingGate> ordering_gate, std::shared_ptr<synchronizer::Synchronizer> synchronizer) : ordering_gate_(std::move(ordering_gate)), synchronizer_(std::move(synchronizer)) { log_ = logger::log("PCS"); } void PeerCommunicationServiceImpl::propagate_transaction( std::shared_ptr<const model::Transaction> transaction) { log_->info("propagate tx"); ordering_gate_->propagate_transaction(transaction); } rxcpp::observable<model::Proposal> PeerCommunicationServiceImpl::on_proposal() { return ordering_gate_->on_proposal(); } rxcpp::observable<Commit> PeerCommunicationServiceImpl::on_commit() { return synchronizer_->on_commit_chain(); } } // namespace network } // namespace iroha
34.6
73
0.7386
[ "model" ]
f104195cd7b66de39a57e51c59b6603e1482f180
3,321
cpp
C++
device.cpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
1
2019-07-19T03:37:33.000Z
2019-07-19T03:37:33.000Z
device.cpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
device.cpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
#include "device.hpp" #include "context.hpp" #include "wrapString.hpp" #include "wrapStringVector.hpp" device_t* device_create() { device_t* dm; dm = new device_t(alure::Device()); return dm; } device_t* device_set(alure::Device dev) { device_t* dm; dm = new device_t(dev); return dm; } void device_destroy(device_t* dm) { if (dm == nullptr) { return; } delete dm; } wrapString_t* device_getName(device_t* dm, alure::PlaybackName type) { if (dm == nullptr) { return nullptr; } return wrapString_create(dm->obj.getName(type)); } bool device_queryExtension(device_t* dm, const char* extension) { if (dm == nullptr) { return false; } return dm->obj.queryExtension(extension); } alureVersion_t device_getALCVersion(device_t* dm) { if (dm == nullptr) { return alureVersion(); } auto version = dm->obj.getALCVersion(); return alureVersion(version.getMajor(), version.getMinor()); } alureVersion_t device_getEFXVersion(device_t* dm) { if (dm == nullptr) { return alureVersion(); } auto version = dm->obj.getEFXVersion(); return alureVersion(version.getMajor(), version.getMinor()); } uint32_t device_getFrequency(device_t* dm) { if (dm == nullptr) { return false; } return dm->obj.getFrequency(); } uint32_t device_getMaxAuxiliarySends(device_t* dm) { if (dm == nullptr) { return false; } return dm->obj.getMaxAuxiliarySends(); } wrapStringVector_t* device_enumerateHRTFNames(device_t* dm) { if (dm == nullptr) { return nullptr; } auto result = dm->obj.enumerateHRTFNames(); std::vector<wrapString_t*> string_vector; for (size_t i = 0; i < result.size(); ++i) { string_vector.push_back(wrapString_create(result[i])); } return wrapStringVector_create(string_vector); } bool device_isHRTFEnabled(device_t* dm) { if (dm == nullptr) { return false; } return dm->obj.isHRTFEnabled(); } wrapString_t* device_getCurrentHRTF(device_t* dm) { if (dm == nullptr) { return nullptr; } return wrapString_create(dm->obj.getCurrentHRTF()); } void device_reset(device_t* dm, alure::AttributePair* attributes, uint64_t size) { if (dm == nullptr) { return; } if (attributes != nullptr && size > 0) { alure::ArrayView<alure::AttributePair> attr(attributes, size); dm->obj.reset(attr); } else { alure::ArrayView<alure::AttributePair> attr; dm->obj.reset(attr); } } context_t* device_createContextWithAttr(device_t* dm, alure::AttributePair* attributes, uint64_t size) noexcept { if (dm == nullptr) { return nullptr; } if (attributes != nullptr && size > 0) { alure::ArrayView<alure::AttributePair> attr(attributes, size); return context_set(dm->obj.createContext(attr, std::nothrow)); } else { return context_set(dm->obj.createContext(std::nothrow)); } } void device_pauseDSP(device_t* dm) { if (dm == nullptr) { return; } dm->obj.pauseDSP(); } void device_resumeDSP(device_t* dm) { if (dm == nullptr) { return; } dm->obj.resumeDSP(); } int64_t device_getClockTime(device_t* dm) { if (dm == nullptr) { return 0; } return dm->obj.getClockTime().count(); } void device_close(device_t* dm) { if (dm == nullptr) { return; } dm->obj.close(); }
15.966346
111
0.657934
[ "vector" ]
f104b9c27a8835c02fa412bbb6c9f34084c876c0
331
hpp
C++
src/gl/mesh_loader.hpp
Harrand/Topaz-2
c3cd3f67b1aaf20229075a593c8ffcad5585f362
[ "Apache-2.0" ]
null
null
null
src/gl/mesh_loader.hpp
Harrand/Topaz-2
c3cd3f67b1aaf20229075a593c8ffcad5585f362
[ "Apache-2.0" ]
9
2019-12-22T17:57:29.000Z
2020-03-30T22:06:53.000Z
src/gl/mesh_loader.hpp
Harrand/Topaz-2
c3cd3f67b1aaf20229075a593c8ffcad5585f362
[ "Apache-2.0" ]
null
null
null
#ifndef TOPAZ_GL_MESH_LOADER_HPP #define TOPAZ_GL_MESH_LOADER_HPP #include "gl/mesh.hpp" #include "gl/tz_assimp/scene.hpp" namespace tz::gl { /** * \addtogroup tz_gl Topaz Graphics Library (tz::gl) * @{ */ tz::gl::IndexedMesh load_mesh(const std::string& filename); /** * @} */ } #endif // TOPAZ_GL_MESH_LOADER_HPP
16.55
60
0.691843
[ "mesh" ]
f104e42c7945c9d86db5fc2f8b568b614cfc7196
39,939
cpp
C++
VulkanVisual/src/old.cpp
rEddieD/VulTerGen
0e6d7a1dcf3321ac570b27d9d031a110161766ff
[ "Apache-2.0" ]
null
null
null
VulkanVisual/src/old.cpp
rEddieD/VulTerGen
0e6d7a1dcf3321ac570b27d9d031a110161766ff
[ "Apache-2.0" ]
null
null
null
VulkanVisual/src/old.cpp
rEddieD/VulTerGen
0e6d7a1dcf3321ac570b27d9d031a110161766ff
[ "Apache-2.0" ]
null
null
null
#define VK_USE_PLATFORM_WIN32_KHR #define VK_NO_PROTOTYPE #include <iostream> #include <vulkan/vulkan.hpp> #include <vector> #include "old.h" #include "Shader.h" #include "Pipeline.h" #include <bitset> namespace VulTerGen { std::vector<const char*> layers = { "VK_LAYER_KHRONOS_validation" }; std::vector<const char*> instanceExtensions = { VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME }; std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<std::vector<float>> priorities; VkSemaphore semaphore; float positions[] = { -0.5f, -0.8f, 0.0f, 0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f }; uint32_t GetTotalInstanceExtensions() { std::vector<VkExtensionProperties> availableExtensions; uint32_t extensionCount = 0; vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); availableExtensions.resize(extensionCount); vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, &availableExtensions[0]); for (int i = 0; i < availableExtensions.size(); i++) { std::cout << availableExtensions[i].extensionName << std::endl; } return extensionCount; } uint32_t GetTotalLayers() { std::vector<VkLayerProperties> availableLayers; uint32_t layerCount = 0; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); availableLayers.resize(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, &availableLayers[0]); for (int i = 0; i < availableLayers.size(); i++) { std::cout << availableLayers[i].layerName << std::endl; } return layerCount; } VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallbackFunction( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { switch (flags) { case VK_DEBUG_REPORT_ERROR_BIT_EXT: std::cout << "ERROR: " << "[" << pLayerPrefix << "] " << pMessage << std::endl; break; case VK_DEBUG_REPORT_WARNING_BIT_EXT: std::cout << "WARNING: " << "[" << pLayerPrefix << "] " << pMessage << std::endl; break; case VK_DEBUG_REPORT_DEBUG_BIT_EXT: std::cout << "DEBUG: " << "[" << pLayerPrefix << "] " << pMessage << std::endl; break; case VK_DEBUG_REPORT_INFORMATION_BIT_EXT: std::cout << "INFORMATION: " << "[" << pLayerPrefix << "] " << pMessage << std::endl; break; case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT: std::cout << "PERFORMANCE: " << "[" << pLayerPrefix << "] " << pMessage << std::endl; break; default: return true; break; } return false; } void InitVulkanDebug() { vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); debugInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debugInfo.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT; debugInfo.pfnCallback = DebugCallbackFunction; vkCreateDebugReportCallbackEXT(instance, &debugInfo, nullptr, &debugReportCallback); } void DeinitVulkanDebug() { vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT(instance, debugReportCallback, nullptr); } void CreateVulkanInstance() { VkApplicationInfo applicationInfo = { applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, applicationInfo.pNext = nullptr, applicationInfo.pApplicationName = "VulTerGen", applicationInfo.applicationVersion = VK_MAKE_VERSION(0,0,1), applicationInfo.pEngineName = nullptr, applicationInfo.engineVersion = 1, applicationInfo.apiVersion = VK_API_VERSION_1_2 }; VkInstanceCreateInfo instanceInfo = { instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, //IF DEBUG ENABLED instanceInfo.pNext = &debugInfo, instanceInfo.flags = 0, instanceInfo.pApplicationInfo = &applicationInfo, instanceInfo.enabledLayerCount = layers.size(), instanceInfo.ppEnabledLayerNames = layers.data(), instanceInfo.enabledExtensionCount = instanceExtensions.size(), instanceInfo.ppEnabledExtensionNames = instanceExtensions.data() }; vkCreateInstance(&instanceInfo, nullptr, &instance); } void GetPhysicalDevice() { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); std::vector<VkPhysicalDevice> availablePhysicalDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, &availablePhysicalDevices[0]); physicalDevice = availablePhysicalDevices[0]; } void GetPhysicalDeviceProperties() { VkPhysicalDeviceProperties deviceProperties = {}; vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties); std::cout << deviceProperties.apiVersion << "\n" << deviceProperties.deviceName << deviceProperties.deviceType; } void GetPhysicalDeviceExtensions() { uint32_t extensionCount = 0; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableDeviceExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, &availableDeviceExtensions[0]); for (int i = 0; i < availableDeviceExtensions.size(); i++) { std::cout << availableDeviceExtensions[i].extensionName << " - " << availableDeviceExtensions[i].specVersion << std::endl; } } void SetPhysicalDeviceFeatures() { uint32_t featureCount = 0; VkPhysicalDeviceFeatures desiredDeviceFeatures; vkGetPhysicalDeviceFeatures(physicalDevice, &desiredDeviceFeatures); std::cout << desiredDeviceFeatures.alphaToOne << " " << desiredDeviceFeatures.sparseBinding << " " << desiredDeviceFeatures.fragmentStoresAndAtomics << " " << desiredDeviceFeatures.dualSrcBlend << " " << desiredDeviceFeatures.drawIndirectFirstInstance << " " << desiredDeviceFeatures.fillModeNonSolid; } void GetPhysicalDeviceQueueFamilies() { uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, &queueFamilyProperties[0]); priorities.resize(queueFamilyCount); for (uint32_t i = 0; i < queueFamilyProperties.size(); ++i) { //Add only those queue families that has graphic support. if ((queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) & VK_QUEUE_GRAPHICS_BIT) { priorities[i].assign(queueFamilyProperties[i].queueCount, 1.0f); VkDeviceQueueCreateInfo queueCreateInfo = { queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, queueCreateInfo.pNext = nullptr, //These are not those flags like VK_QUEUE_GRAPHICS_BIT queueCreateInfo.flags = 0, queueCreateInfo.queueFamilyIndex = i, queueCreateInfo.queueCount = queueFamilyProperties[i].queueCount, queueCreateInfo.pQueuePriorities = priorities[i].data() }; queueCreateInfos.push_back(queueCreateInfo); } } } void CreateLogicalDevice() { VkDeviceCreateInfo logicalDeviceCreateInfo = { logicalDeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, logicalDeviceCreateInfo.pNext = nullptr, logicalDeviceCreateInfo.flags = 0, logicalDeviceCreateInfo.queueCreateInfoCount = queueCreateInfos.size(), logicalDeviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(), logicalDeviceCreateInfo.enabledLayerCount = layers.size(), logicalDeviceCreateInfo.ppEnabledLayerNames = layers.data(), logicalDeviceCreateInfo.enabledExtensionCount = deviceExtensions.size(), logicalDeviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data(), logicalDeviceCreateInfo.pEnabledFeatures = nullptr }; vkCreateDevice(physicalDevice, &logicalDeviceCreateInfo, nullptr, &logicalDevice); } void DestroyLogicalDevice() { vkDestroyDevice(logicalDevice, nullptr); logicalDevice = VK_NULL_HANDLE; } void GetDeviceQueue() { vkGetDeviceQueue(logicalDevice, 0, 4, &mainGraphicQueue); } void DestroyVulkanInstance() { vkDestroyInstance(instance, nullptr); instance = VK_NULL_HANDLE; } void CreatePresentationSurface(HWND hWnd) { VkWin32SurfaceCreateInfoKHR surfaceCreateInfo = { surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, surfaceCreateInfo.pNext = nullptr, surfaceCreateInfo.flags = 0, surfaceCreateInfo.hinstance = GetModuleHandle(nullptr), surfaceCreateInfo.hwnd = hWnd }; vkCreateWin32SurfaceKHR(instance, &surfaceCreateInfo, nullptr, &presentationSurface); } bool ImagePresentationSupported() { VkBool32 supported = VK_FALSE; for (const auto &queueInfo : queueCreateInfos) { vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueInfo.queueFamilyIndex, presentationSurface, &supported); if (supported == VK_TRUE) { graphicQueueFamilyIndex = queueInfo.queueFamilyIndex; return supported; } } return supported; } bool IsMailboxPresentationSupported() { uint32_t presentModeCount = 0; vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, presentationSurface, &presentModeCount, nullptr); std::vector<VkPresentModeKHR> presentationModes(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, presentationSurface, &presentModeCount, &presentationModes[0]); for (auto& presentationMode : presentationModes) { if (presentationMode == VkPresentModeKHR::VK_PRESENT_MODE_MAILBOX_KHR) { return true; } } return false; } void CreateSwapchain() { vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, presentationSurface, &surfaceCapabilities); uint32_t formatCount = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, presentationSurface, &formatCount, nullptr); std::vector<VkSurfaceFormatKHR> surfaceFormats(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, presentationSurface, &formatCount, &surfaceFormats[0]); surfaceFormat = { surfaceFormats[0].format, surfaceFormats[0].colorSpace }; VkSwapchainCreateInfoKHR swapchainCreateInfo = { swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, swapchainCreateInfo.pNext = nullptr, swapchainCreateInfo.flags = 0, swapchainCreateInfo.surface = presentationSurface, swapchainCreateInfo.minImageCount = surfaceCapabilities.minImageCount, //Select the default ones. swapchainCreateInfo.imageFormat = surfaceFormats[0].format, swapchainCreateInfo.imageColorSpace = surfaceFormats[0].colorSpace, swapchainCreateInfo.imageExtent = surfaceCapabilities.currentExtent, swapchainCreateInfo.imageArrayLayers = 1, swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, swapchainCreateInfo.queueFamilyIndexCount = 0, swapchainCreateInfo.pQueueFamilyIndices = nullptr, swapchainCreateInfo.preTransform = surfaceCapabilities.currentTransform, swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, swapchainCreateInfo.presentMode = VK_PRESENT_MODE_FIFO_KHR, swapchainCreateInfo.clipped = VK_TRUE, swapchainCreateInfo.oldSwapchain = nullptr }; vkCreateSwapchainKHR(logicalDevice, &swapchainCreateInfo, nullptr, &swapchain); } void GetSwapchainImage() { uint32_t swapchainImageCount = 0; vkGetSwapchainImagesKHR(logicalDevice, swapchain, &swapchainImageCount, nullptr); swapchainImages.resize(swapchainImageCount); vkGetSwapchainImagesKHR(logicalDevice, swapchain, &swapchainImageCount, swapchainImages.data()); } void DestroySwapchain() { vkDestroySwapchainKHR(logicalDevice, swapchain, nullptr); } void GetMemoryTypes() { //Vertex Buffer create info VkBufferCreateInfo vertexBufferCreateInfo = { vertexBufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, vertexBufferCreateInfo.pNext = nullptr, vertexBufferCreateInfo.flags = 0, vertexBufferCreateInfo.size = 0, vertexBufferCreateInfo.usage = 0, vertexBufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE, vertexBufferCreateInfo.queueFamilyIndexCount = 0, vertexBufferCreateInfo.pQueueFamilyIndices = nullptr }; VkBuffer vertexBuffer; //Creation of vertex buffer vkCreateBuffer(logicalDevice, &vertexBufferCreateInfo, nullptr, &vertexBuffer); //Get the properties of the physical device VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &physicalDeviceMemoryProperties); //Get what the buffer needs VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(logicalDevice, vertexBuffer, &memoryRequirements); VkDeviceMemory memoryObject; VkMemoryPropertyFlagBits memoryProperties = VkMemoryPropertyFlagBits::VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; for (uint32_t type = 0; type < physicalDeviceMemoryProperties.memoryTypeCount; ++type) { //Check whether this type of memory can be used for the particular buffer if (memoryRequirements.memoryTypeBits & (1 << type) && (physicalDeviceMemoryProperties.memoryTypes[type].propertyFlags & memoryProperties) == memoryProperties) { VkMemoryAllocateInfo memoryAllocateInfo = { memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, memoryAllocateInfo.pNext = nullptr, memoryAllocateInfo.allocationSize = memoryRequirements.size, memoryAllocateInfo.memoryTypeIndex = 0 }; vkAllocateMemory(logicalDevice, &memoryAllocateInfo, nullptr, &memoryObject); vkBindBufferMemory(logicalDevice, vertexBuffer, memoryObject, 0); } } std::cout << physicalDeviceMemoryProperties.memoryTypes->propertyFlags << std::endl; std::cout << physicalDeviceMemoryProperties.memoryTypes->heapIndex << std::endl; std::cout << physicalDeviceMemoryProperties.memoryTypeCount << std::endl; std::cout << physicalDeviceMemoryProperties.memoryHeaps->flags << std::endl; std::cout << physicalDeviceMemoryProperties.memoryHeaps->size << std::endl; std::cout << physicalDeviceMemoryProperties.memoryHeapCount << std::endl; } VkSemaphore& CreateSemaphores() { VkSemaphore semaphore; VkSemaphoreCreateInfo semaphoreCreateInfo = { semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, semaphoreCreateInfo.pNext = nullptr, semaphoreCreateInfo.flags = 0 }; vkCreateSemaphore(logicalDevice, &semaphoreCreateInfo, nullptr, &semaphore); return semaphore; } void DestroySemaphores(VkSemaphore semaphore) { vkDestroySemaphore(logicalDevice, semaphore, nullptr); semaphore = VK_NULL_HANDLE; } void CreateRenderpass() { VkAttachmentDescription colorAttachment = { colorAttachment.flags = 0, colorAttachment.format = surfaceFormat.format, colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT, colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE, colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, //Before the render pass colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR //Automatically transition to when the render pass finishes }; VkAttachmentReference colorAttachmentRef = { colorAttachmentRef.attachment = 0, colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // Vulkan automatically converts the attachment to this layout }; VkSubpassDescription subpass = { subpass.flags = 0, subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, subpass.inputAttachmentCount = 0, //Attachments that are read from a shader subpass.pInputAttachments = nullptr, //Attachments that are read from a shader subpass.colorAttachmentCount = 1, subpass.pColorAttachments = &colorAttachmentRef, subpass.pResolveAttachments = nullptr, //Attachments used for multisampling color attachments subpass.pDepthStencilAttachment = nullptr, //Attachment for depth and stencil data subpass.preserveAttachmentCount = 0, //Attachments that are not used by this subpass, but for which the data must be preserved subpass.pPreserveAttachments = nullptr //Attachments that are not used by this subpass, but for which the data must be preserved }; VkSubpassDependency dependency = { dependency.srcSubpass = VK_SUBPASS_EXTERNAL, dependency.dstSubpass = 0, dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, dependency.srcAccessMask = 0, dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, dependency.dependencyFlags = 0, }; VkRenderPassCreateInfo renderPassCreateInfo = { renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, renderPassCreateInfo.pNext = nullptr, renderPassCreateInfo.flags = 0, renderPassCreateInfo.attachmentCount = 1, renderPassCreateInfo.pAttachments = &colorAttachment, renderPassCreateInfo.subpassCount = 1, renderPassCreateInfo.pSubpasses = &subpass, renderPassCreateInfo.dependencyCount = 1, renderPassCreateInfo.pDependencies = &dependency }; vkCreateRenderPass(logicalDevice, &renderPassCreateInfo, nullptr, &renderPass); } void CreateImageViews() { swapchainImageViews.resize(swapchainImages.size()); for (uint32_t i = 0; i < swapchainImages.size(); ++i) { //Create ImageView attachments VkImageViewCreateInfo imageViewCreateInfo = { imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, imageViewCreateInfo.pNext = nullptr, imageViewCreateInfo.flags = 0, imageViewCreateInfo.image = swapchainImages[i], imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D, imageViewCreateInfo.format = surfaceFormat.format, imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY, imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY, imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY, imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY, imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, imageViewCreateInfo.subresourceRange.baseMipLevel = 0, imageViewCreateInfo.subresourceRange.levelCount = 1, imageViewCreateInfo.subresourceRange.baseArrayLayer = 0, imageViewCreateInfo.subresourceRange.layerCount = 1, }; vkCreateImageView(logicalDevice, &imageViewCreateInfo, nullptr, &swapchainImageViews[i]); } } void CreateFramebuffers() { swapchainFramebuffers.resize(swapchainImages.size()); for (uint32_t i = 0; i < swapchainImages.size(); ++i) { VkImageView attachments[] = { swapchainImageViews[i] }; VkFramebufferCreateInfo framebufferCreateInfo = { framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, framebufferCreateInfo.pNext = nullptr, framebufferCreateInfo.flags = 0, framebufferCreateInfo.renderPass = renderPass, framebufferCreateInfo.attachmentCount = 1, framebufferCreateInfo.pAttachments = attachments, framebufferCreateInfo.width = surfaceCapabilities.currentExtent.width, framebufferCreateInfo.height = surfaceCapabilities.currentExtent.height, framebufferCreateInfo.layers = 1 }; vkCreateFramebuffer(logicalDevice, &framebufferCreateInfo, nullptr, &swapchainFramebuffers[i]); } } uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("failed to find suitable memory type!"); } void CreateVertexBuffer() { //Recreate pipeline if changing shaders VkBufferCreateInfo vertexBufferCreateInfo = { vertexBufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, vertexBufferCreateInfo.pNext = nullptr, vertexBufferCreateInfo.flags = 0, vertexBufferCreateInfo.size = sizeof(positions), vertexBufferCreateInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexBufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE, vertexBufferCreateInfo.queueFamilyIndexCount = 1, vertexBufferCreateInfo.pQueueFamilyIndices = &graphicQueueFamilyIndex }; //Creation of vertex buffer vkCreateBuffer(logicalDevice, &vertexBufferCreateInfo, nullptr, &vertexBuffer); //Get what the buffer needs VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(logicalDevice, vertexBuffer, &memoryRequirements); VkMemoryAllocateInfo memoryAllocateInfo = { memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, memoryAllocateInfo.pNext = nullptr, memoryAllocateInfo.allocationSize = memoryRequirements.size, memoryAllocateInfo.memoryTypeIndex = findMemoryType(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) }; vkAllocateMemory(logicalDevice, &memoryAllocateInfo, nullptr, &memoryObject); vkBindBufferMemory(logicalDevice, vertexBuffer, memoryObject, 0); void* data; vkMapMemory(logicalDevice, memoryObject, 0, vertexBufferCreateInfo.size, 0, &data); memcpy(data, positions, (size_t)vertexBufferCreateInfo.size); vkUnmapMemory(logicalDevice, memoryObject); } void CreatePipeline() { Shader vertexShader(logicalDevice, "D:\\Projects\\VulTerGen\\VulkanVisual\\shaders\\vert.spv", VK_SHADER_STAGE_VERTEX_BIT); Shader fragmentShader(logicalDevice, "D:\\Projects\\VulTerGen\\VulkanVisual\\shaders\\frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); /*std::cout << sizeof(positions) << std::endl; Model triangle(positions, sizeof(positions)/sizeof(positions[0])); triangle.PrintEach();*/ VkVertexInputBindingDescription vertexInputBindingDescription = { vertexInputBindingDescription.binding = 0, //where the data is taken from (from which binding) vertexInputBindingDescription.stride = 3 * sizeof(float), //what is the stride between consecutive elements in the buffer pos.x, pos.y, pos.z, //col.x, col.y, col.z vertexInputBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX //how this data is read }; std::vector<VkVertexInputAttributeDescription> vertexInputAttribDescriptions; //These are the vertex position coordinates VkVertexInputAttributeDescription vertexInputPosAttributeDescription = { vertexInputPosAttributeDescription.location = 0, vertexInputPosAttributeDescription.binding = 0, vertexInputPosAttributeDescription.format = VK_FORMAT_R32G32B32_SFLOAT, vertexInputPosAttributeDescription.offset = 0 }; vertexInputAttribDescriptions.push_back(vertexInputPosAttributeDescription); //VkVertexInputAttributeDescription vertexInputColAttributeDescription = { // vertexInputColAttributeDescription.location = 1, // vertexInputColAttributeDescription.binding = 0, // vertexInputColAttributeDescription.format = VK_FORMAT_R32G32B32_SFLOAT, // vertexInputColAttributeDescription.offset = 3 * sizeof(float) //}; //vertexInputAttribDescriptions.push_back(vertexInputColAttributeDescription); //If it is hardcoded in the shader then no need to specify VkPipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo = { pipelineVertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, pipelineVertexInputStateCreateInfo.pNext = nullptr, pipelineVertexInputStateCreateInfo.flags = 0, pipelineVertexInputStateCreateInfo.vertexBindingDescriptionCount = 1, //1, pipelineVertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexInputBindingDescription, //&vertexInputBindingDescription, pipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = vertexInputAttribDescriptions.size(), //vertexInputAttribDescriptions.size(), pipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttribDescriptions.data() //vertexInputAttribDescriptions.data() }; VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo = { pipelineInputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, pipelineInputAssemblyStateCreateInfo.pNext = nullptr, pipelineInputAssemblyStateCreateInfo.flags = 0, pipelineInputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, pipelineInputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE }; VkViewport viewport = { viewport.x = 0.0f, viewport.y = 0.0f, viewport.width = surfaceCapabilities.currentExtent.width, viewport.height = surfaceCapabilities.currentExtent.height, viewport.minDepth = 0.0f, viewport.maxDepth = 1.0f }; VkRect2D scissor = { scissor.offset = {0, 0}, scissor.extent = surfaceCapabilities.currentExtent }; VkPipelineViewportStateCreateInfo pipelineViewportStateCreateInfo = { pipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, pipelineViewportStateCreateInfo.pNext = nullptr, pipelineViewportStateCreateInfo.flags = 0, pipelineViewportStateCreateInfo.viewportCount = 1, pipelineViewportStateCreateInfo.pViewports = &viewport, pipelineViewportStateCreateInfo.scissorCount = 1, pipelineViewportStateCreateInfo.pScissors = &scissor }; VkPipelineRasterizationStateCreateInfo pipelineRasterizerStateCreateInfo = { pipelineRasterizerStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, pipelineRasterizerStateCreateInfo.pNext = nullptr, pipelineRasterizerStateCreateInfo.flags = 0, pipelineRasterizerStateCreateInfo.depthClampEnable = VK_FALSE, //REQUIRES FEATURE If True Fragments that are beyond the near and far planes are clamped to them as opposed to discarding them pipelineRasterizerStateCreateInfo.rasterizerDiscardEnable = VK_FALSE, //If True it won't allow the geometry to further pass through to later stages pipelineRasterizerStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL, pipelineRasterizerStateCreateInfo.cullMode = VK_CULL_MODE_NONE, pipelineRasterizerStateCreateInfo.frontFace = VK_FRONT_FACE_CLOCKWISE, //clockwise or counterclockwise pipelineRasterizerStateCreateInfo.depthBiasEnable = VK_FALSE, //used for shadow mapping pipelineRasterizerStateCreateInfo.depthBiasConstantFactor = 0.0f, //used for shadow mapping pipelineRasterizerStateCreateInfo.depthBiasClamp = 0.0f, //used for shadow mapping pipelineRasterizerStateCreateInfo.depthBiasSlopeFactor = 0.0f, //used for shadow mapping pipelineRasterizerStateCreateInfo.lineWidth = 1.0f //Not sure }; VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = { pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, pipelineLayoutCreateInfo.pNext = nullptr, pipelineLayoutCreateInfo.flags = 0, pipelineLayoutCreateInfo.setLayoutCount = 0, pipelineLayoutCreateInfo.pSetLayouts = nullptr, pipelineLayoutCreateInfo.pushConstantRangeCount = 0, pipelineLayoutCreateInfo.pPushConstantRanges = nullptr }; vkCreatePipelineLayout(logicalDevice, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout); VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfos[2] = { vertexShader.shaderStageCreateInfo, fragmentShader.shaderStageCreateInfo }; //Color blend state describes how blend factors are calculated (if used) //We need one blend attachment state per color attachment (even if blending is not used) VkPipelineColorBlendAttachmentState blendAttachmentState[1] = {}; blendAttachmentState[0].colorWriteMask = 0xf; blendAttachmentState[0].blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlendState = {}; colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendState.attachmentCount = 1; colorBlendState.pAttachments = blendAttachmentState; VkPipelineMultisampleStateCreateInfo multisampleState = {}; multisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampleState.pSampleMask = nullptr; VkGraphicsPipelineCreateInfo graphicPipelineCreateInfo = { graphicPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, graphicPipelineCreateInfo.pNext = nullptr, graphicPipelineCreateInfo.flags = 0, graphicPipelineCreateInfo.stageCount = 2, //The number of shader modules (Vertex stage, Fragment Stage) graphicPipelineCreateInfo.pStages = pipelineShaderStageCreateInfos, graphicPipelineCreateInfo.pVertexInputState = &pipelineVertexInputStateCreateInfo, graphicPipelineCreateInfo.pInputAssemblyState = &pipelineInputAssemblyStateCreateInfo, graphicPipelineCreateInfo.pTessellationState = nullptr, graphicPipelineCreateInfo.pViewportState = &pipelineViewportStateCreateInfo, graphicPipelineCreateInfo.pRasterizationState = &pipelineRasterizerStateCreateInfo, graphicPipelineCreateInfo.pMultisampleState = &multisampleState, graphicPipelineCreateInfo.pDepthStencilState = nullptr, graphicPipelineCreateInfo.pColorBlendState = &colorBlendState,//&colorBlending, graphicPipelineCreateInfo.pDynamicState = nullptr, graphicPipelineCreateInfo.layout = pipelineLayout, graphicPipelineCreateInfo.renderPass = renderPass, graphicPipelineCreateInfo.subpass = 0, graphicPipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE, graphicPipelineCreateInfo.basePipelineIndex = -1 }; vkCreateGraphicsPipelines(logicalDevice, nullptr, 1, &graphicPipelineCreateInfo, nullptr, &graphicPipeline); } void SetupRenderLoop() { VkCommandPoolCreateInfo commandPoolCreateInfo = { commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, commandPoolCreateInfo.pNext = nullptr, commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, commandPoolCreateInfo.queueFamilyIndex = graphicQueueFamilyIndex }; VkCommandPool commandPool; vkCreateCommandPool(logicalDevice, &commandPoolCreateInfo, nullptr, &commandPool); commandBuffers.resize(swapchainFramebuffers.size()); //Allocating command buffer from command pool; VkCommandBufferAllocateInfo commandBufferAllocateInfo = { commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, commandBufferAllocateInfo.pNext = nullptr, commandBufferAllocateInfo.commandPool = commandPool, commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, commandBufferAllocateInfo.commandBufferCount = (uint32_t)commandBuffers.size() }; vkAllocateCommandBuffers(logicalDevice, &commandBufferAllocateInfo, commandBuffers.data()); //Begin recording into command buffer; VkCommandBufferBeginInfo commandBufferBeginInfo = { commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, commandBufferBeginInfo.pNext = nullptr, commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, commandBufferBeginInfo.pInheritanceInfo = nullptr }; VkClearColorValue clearColorValue = { 0.6f, 0.1f, 0.1f, 0.0f }; VkClearValue clearColor = { 0.6f, 0.1f, 0.8f, 1.0f }; for (size_t i = 0; i < swapchainImages.size(); i++) { vkBeginCommandBuffer(commandBuffers[i], &commandBufferBeginInfo); VkRenderPassBeginInfo renderPassInfo = { renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, renderPassInfo.pNext = nullptr, renderPassInfo.renderPass = renderPass, renderPassInfo.framebuffer = swapchainFramebuffers[i], renderPassInfo.renderArea.offset = {0, 0}, renderPassInfo.renderArea.extent = surfaceCapabilities.currentExtent, renderPassInfo.clearValueCount = 1, renderPassInfo.pClearValues = &clearColor }; vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicPipeline); VkBuffer vertexBuffers[] = { vertexBuffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); vkCmdDraw(commandBuffers[i], 3, 1, 0, 0); vkCmdEndRenderPass(commandBuffers[i]); vkEndCommandBuffer(commandBuffers[i]); } imageAvailableSemaphore = CreateSemaphores(); commandBufferFinishedSemaphore = CreateSemaphores(); flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; submitInfo = { submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, submitInfo.pNext = nullptr, submitInfo.waitSemaphoreCount = 1, submitInfo.pWaitSemaphores = &imageAvailableSemaphore, submitInfo.pWaitDstStageMask = &flags, submitInfo.commandBufferCount = commandBuffers.size(), submitInfo.pCommandBuffers = commandBuffers.data(), submitInfo.signalSemaphoreCount = 1, submitInfo.pSignalSemaphores = &commandBufferFinishedSemaphore }; presentInfo = { presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, presentInfo.pNext = nullptr, presentInfo.waitSemaphoreCount = 1, presentInfo.pWaitSemaphores = &commandBufferFinishedSemaphore, presentInfo.swapchainCount = 1, presentInfo.pSwapchains = &swapchain, presentInfo.pImageIndices = &swapchainImageIndex, presentInfo.pResults = nullptr }; } void RenderLoop() { vkAcquireNextImageKHR(logicalDevice, swapchain, UINT64_MAX, imageAvailableSemaphore, VK_NULL_HANDLE, &swapchainImageIndex); //Wait previous actions vkQueueWaitIdle(mainGraphicQueue); vkQueueSubmit(mainGraphicQueue, 1, &submitInfo, nullptr); vkQueuePresentKHR(mainGraphicQueue, &presentInfo); } void DestroyRenderLoop() { //Destroy renderloop vkDeviceWaitIdle(logicalDevice); DestroySemaphores(commandBufferFinishedSemaphore); DestroySemaphores(imageAvailableSemaphore); } void Start(HWND hWnd) { LoadVulkanLibrary(); GetTotalInstanceExtensions(); GetTotalLayers(); CreateVulkanInstance(); InitVulkanDebug(); LoadInstanceLevelFunctions(instance); GetPhysicalDevice(); GetPhysicalDeviceProperties(); GetPhysicalDeviceExtensions(); SetPhysicalDeviceFeatures(); GetPhysicalDeviceQueueFamilies(); CreatePresentationSurface(hWnd); if (ImagePresentationSupported()) { CreateLogicalDevice(); LoadDeviceLevelFunctions(logicalDevice); GetDeviceQueue(); CreateSwapchain(); GetSwapchainImage(); CreateImageViews(); CreateRenderpass(); CreateFramebuffers(); CreateVertexBuffer(); //CreatePipeline(); Pipeline* p = new Pipeline(logicalDevice, swapchain, renderPass, surfaceCapabilities); graphicPipeline = p->graphicPipeline; SetupRenderLoop(); //RenderLoop(); //--------------------------------- } } void Loop() { RenderLoop(); } void Stop() { vkFreeMemory(logicalDevice, memoryObject, nullptr); for (auto framebuffer : swapchainFramebuffers) { vkDestroyFramebuffer(logicalDevice, framebuffer, nullptr); } vkDestroyBuffer(logicalDevice, vertexBuffer, nullptr); vkDestroyPipeline(logicalDevice, graphicPipeline, nullptr); vkDestroyPipelineLayout(logicalDevice, pipelineLayout, nullptr); vkDestroyRenderPass(logicalDevice, renderPass, nullptr); DestroyRenderLoop(); DestroySwapchain(); DestroyLogicalDevice(); DeinitVulkanDebug(); DestroyVulkanInstance(); FreeVulkanLibrary(); } } //void EmptyFunction(){} //void(*fncPtr)() = EmptyFunction; // //typedef long(*function)(void*, const char*); //function vkGetInstanceProcAddr = (function)GetProcAddress(vulkan_library, "vkGetInstanceProcAddr"); //vkGetInstanceProcAddr(NULL, "vkCreateInstance") // //auto vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)GetProcAddress(vulkan_library, "vkGetInstanceProcAddr"); //int main() //{ // HMODULE vulkan_library = LoadLibrary(L"vulkan-1.dll"); // if (vulkan_library == nullptr) // { // } // else // { // PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)GetProcAddress(vulkan_library, "vkGetInstanceProcAddr"); // // PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceExtensionProperties"); // PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceLayerProperties"); // PFN_vkCreateInstance vkCreateInstance = (PFN_vkCreateInstance)vkGetInstanceProcAddr(nullptr, "vkCreateInstance"); // // uint32_t extensionCount = 0; // // vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); // std::cout << extensionCount; // } // return 0; //} // // // VkImageSubresourceRange subResourceRange = // { // subResourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, // subResourceRange.baseMipLevel = 0, // subResourceRange.levelCount = 1, // subResourceRange.baseArrayLayer = 0, // subResourceRange.layerCount = 1 // }; // // VkImageMemoryBarrier imageMemoryBarrierPresentToClear = // { // imageMemoryBarrierPresentToClear.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // imageMemoryBarrierPresentToClear.pNext = nullptr, // imageMemoryBarrierPresentToClear.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT, // imageMemoryBarrierPresentToClear.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, // imageMemoryBarrierPresentToClear.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, // imageMemoryBarrierPresentToClear.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // imageMemoryBarrierPresentToClear.srcQueueFamilyIndex = graphicQueueFamilyIndex, // imageMemoryBarrierPresentToClear.dstQueueFamilyIndex = graphicQueueFamilyIndex, // imageMemoryBarrierPresentToClear.image = swapchainImages[i], // imageMemoryBarrierPresentToClear.subresourceRange = subResourceRange // }; // // VkImageMemoryBarrier imageMemoryBarrierClearToPresent = // { // imageMemoryBarrierClearToPresent.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // imageMemoryBarrierClearToPresent.pNext = nullptr, // imageMemoryBarrierClearToPresent.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, // imageMemoryBarrierClearToPresent.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, // imageMemoryBarrierClearToPresent.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // imageMemoryBarrierClearToPresent.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // imageMemoryBarrierClearToPresent.srcQueueFamilyIndex = graphicQueueFamilyIndex, // imageMemoryBarrierClearToPresent.dstQueueFamilyIndex = graphicQueueFamilyIndex, // imageMemoryBarrierClearToPresent.image = swapchainImages[i], // imageMemoryBarrierClearToPresent.subresourceRange = subResourceRange // }; // // vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrierPresentToClear); // // vkCmdClearColorImage(commandBuffer, swapchainImages[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearColorValue, 1, &subResourceRange); // // vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrierClearToPresent);
39.504451
205
0.791457
[ "geometry", "render", "object", "vector", "model" ]
f10e114447298e4179313103dc057874fd4844c4
37,028
cpp
C++
zircon/system/core/devmgr/devcoordinator/coordinator-test.cpp
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
zircon/system/core/devmgr/devcoordinator/coordinator-test.cpp
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
zircon/system/core/devmgr/devcoordinator/coordinator-test.cpp
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <ddk/binding.h> #include <ddk/driver.h> #include <fbl/algorithm.h> #include <fbl/vector.h> #include <fuchsia/device/manager/c/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/fidl/coding.h> #include <threads.h> #include <zircon/fidl.h> #include <zxtest/zxtest.h> #include "coordinator.h" #include "devfs.h" #include "devhost.h" #include "../shared/fdio.h" namespace devmgr { zx::channel fs_clone(const char* path) { return zx::channel(); } } // namespace devmgr namespace { constexpr char kSystemDriverPath[] = "/boot/driver/platform-bus.so"; constexpr char kDriverPath[] = "/boot/driver/test/mock-device.so"; devmgr::CoordinatorConfig DefaultConfig(async_dispatcher_t* dispatcher) { devmgr::CoordinatorConfig config{}; config.dispatcher = dispatcher; config.require_system = false; config.asan_drivers = false; zx::event::create(0, &config.fshost_event); return config; } TEST(CoordinatorTestCase, InitializeCoreDevices) { devmgr::Coordinator coordinator(DefaultConfig(nullptr)); zx_status_t status = coordinator.InitializeCoreDevices(kSystemDriverPath); ASSERT_EQ(ZX_OK, status); } TEST(CoordinatorTestCase, OpenVirtcon) { devmgr::Coordinator coordinator(DefaultConfig(nullptr)); zx::channel client, server; zx_status_t status = zx::channel::create(0, &client, &server); ASSERT_EQ(ZX_OK, status); coordinator.set_virtcon_channel(std::move(client)); zx::channel sender, receiver; status = zx::channel::create(0, &sender, &receiver); ASSERT_EQ(ZX_OK, status); status = coordinator.DmOpenVirtcon(std::move(sender)); ASSERT_EQ(ZX_OK, status); zx_signals_t signals; status = server.wait_one(ZX_CHANNEL_READABLE, zx::time::infinite(), &signals); ASSERT_EQ(ZX_OK, status); ASSERT_TRUE(signals & ZX_CHANNEL_READABLE); zx::channel sender_channel; uint32_t actual_handles; status = server.read(0, nullptr, sender_channel.reset_and_get_address(), 0, 1, nullptr, &actual_handles); ASSERT_EQ(ZX_OK, status); ASSERT_EQ(1, actual_handles); ASSERT_TRUE(sender_channel.is_valid()); } TEST(CoordinatorTestCase, DumpState) { devmgr::Coordinator coordinator(DefaultConfig(nullptr)); zx_status_t status = coordinator.InitializeCoreDevices(kSystemDriverPath); ASSERT_EQ(ZX_OK, status); constexpr int32_t kBufSize = 256; char buf[kBufSize + 1] = {0}; zx::vmo vmo; ASSERT_EQ(ZX_OK, zx::vmo::create(kBufSize, 0, &vmo)); devmgr::VmoWriter writer(std::move(vmo)); coordinator.DumpState(&writer); ASSERT_EQ(writer.written(), writer.available()); ASSERT_LT(writer.written(), kBufSize); ASSERT_GT(writer.written(), 0); ASSERT_EQ(ZX_OK, writer.vmo().read(buf, 0, writer.written())); ASSERT_NE(nullptr, strstr(buf, "[root]")); } TEST(CoordinatorTestCase, LoadDriver) { bool found_driver = false; auto callback = [&found_driver](devmgr::Driver* drv, const char* version) { delete drv; found_driver = true; }; devmgr::load_driver(kDriverPath, callback); ASSERT_TRUE(found_driver); } TEST(CoordinatorTestCase, BindDrivers) { async::Loop loop(&kAsyncLoopConfigNoAttachToThread); devmgr::Coordinator coordinator(DefaultConfig(loop.dispatcher())); zx_status_t status = coordinator.InitializeCoreDevices(kSystemDriverPath); ASSERT_EQ(ZX_OK, status); coordinator.set_running(true); devmgr::Driver* driver; auto callback = [&coordinator, &driver](devmgr::Driver* drv, const char* version) { driver = drv; return coordinator.DriverAdded(drv, version); }; devmgr::load_driver(kDriverPath, callback); loop.RunUntilIdle(); ASSERT_EQ(1, coordinator.drivers().size_slow()); ASSERT_EQ(driver, &coordinator.drivers().front()); } void InitializeCoordinator(devmgr::Coordinator* coordinator) { zx_status_t status = coordinator->InitializeCoreDevices(kSystemDriverPath); ASSERT_EQ(ZX_OK, status); // Load the component driver devmgr::load_driver(devmgr::kComponentDriverPath, fit::bind_member(coordinator, &devmgr::Coordinator::DriverAddedInit)); // Add the driver we're using as platform bus devmgr::load_driver(kSystemDriverPath, fit::bind_member(coordinator, &devmgr::Coordinator::DriverAddedInit)); // Initialize devfs. devmgr::devfs_init(coordinator->root_device(), coordinator->dispatcher()); status = devmgr::devfs_publish(coordinator->root_device(), coordinator->test_device()); status = devmgr::devfs_publish(coordinator->root_device(), coordinator->sys_device()); ASSERT_EQ(ZX_OK, status); coordinator->set_running(true); } // Reads a BindDriver request from remote, checks that it is for the expected // driver, and then sends a ZX_OK response. void CheckBindDriverReceived(const zx::channel& remote, const char* expected_driver) { // Read the BindDriver request. FIDL_ALIGNDECL uint8_t bytes[ZX_CHANNEL_MAX_MSG_BYTES]; zx_handle_t handles[ZX_CHANNEL_MAX_MSG_HANDLES]; uint32_t actual_bytes; uint32_t actual_handles; zx_status_t status = remote.read(0, bytes, handles, sizeof(bytes), fbl::count_of(handles), &actual_bytes, &actual_handles); ASSERT_OK(status); ASSERT_LT(0, actual_bytes); ASSERT_EQ(1, actual_handles); status = zx_handle_close(handles[0]); ASSERT_OK(status); // Validate the BindDriver request. auto hdr = reinterpret_cast<fidl_message_header_t*>(bytes); ASSERT_EQ(fuchsia_device_manager_DeviceControllerBindDriverOrdinal, hdr->ordinal); status = fidl_decode(&fuchsia_device_manager_DeviceControllerBindDriverRequestTable, bytes, actual_bytes, handles, actual_handles, nullptr); ASSERT_OK(status); auto req = reinterpret_cast<fuchsia_device_manager_DeviceControllerBindDriverRequest*>(bytes); ASSERT_EQ(req->driver_path.size, strlen(expected_driver)); ASSERT_BYTES_EQ(reinterpret_cast<const uint8_t*>(expected_driver), reinterpret_cast<const uint8_t*>(req->driver_path.data), req->driver_path.size, ""); // Write the BindDriver response. memset(bytes, 0, sizeof(bytes)); auto resp = reinterpret_cast<fuchsia_device_manager_DeviceControllerBindDriverResponse*>(bytes); resp->hdr.ordinal = fuchsia_device_manager_DeviceControllerBindDriverOrdinal; resp->status = ZX_OK; status = fidl_encode(&fuchsia_device_manager_DeviceControllerBindDriverResponseTable, bytes, sizeof(*resp), handles, fbl::count_of(handles), &actual_handles, nullptr); ASSERT_OK(status); ASSERT_EQ(0, actual_handles); status = remote.write(0, bytes, sizeof(*resp), nullptr, 0); ASSERT_OK(status); } TEST(CoordinatorTestCase, BindDevices) { async::Loop loop(&kAsyncLoopConfigNoAttachToThread); devmgr::Coordinator coordinator(DefaultConfig(loop.dispatcher())); ASSERT_NO_FATAL_FAILURES(InitializeCoordinator(&coordinator)); // Add the device. zx::channel local, remote; zx_status_t status = zx::channel::create(0, &local, &remote); ASSERT_EQ(ZX_OK, status); fbl::RefPtr<devmgr::Device> device; status = coordinator.AddDevice(coordinator.test_device(), std::move(local), nullptr /* props_data */, 0 /* props_count */, "mock-device", ZX_PROTOCOL_TEST, nullptr /* driver_path */, nullptr /* args */, false /* invisible */, zx::channel() /* client_remote */, &device); ASSERT_EQ(ZX_OK, status); ASSERT_EQ(1, coordinator.devices().size_slow()); // Add the driver. devmgr::load_driver(kDriverPath, fit::bind_member(&coordinator, &devmgr::Coordinator::DriverAdded)); loop.RunUntilIdle(); ASSERT_FALSE(coordinator.drivers().is_empty()); // Bind the device to a fake devhost. fbl::RefPtr<devmgr::Device> dev = fbl::WrapRefPtr(&coordinator.devices().front()); devmgr::Devhost host; host.AddRef(); // refcount starts at zero, so bump it up to keep us from being cleaned up dev->set_host(&host); status = coordinator.BindDevice(dev, kDriverPath, true /* new device */); ASSERT_EQ(ZX_OK, status); // Check the BindDriver request. ASSERT_NO_FATAL_FAILURES(CheckBindDriverReceived(remote, kDriverPath)); loop.RunUntilIdle(); // Reset the fake devhost connection. dev->set_host(nullptr); remote.reset(); loop.RunUntilIdle(); } // Reads a CreateDevice from remote, checks expectations, and sends a ZX_OK // response. void CheckCreateDeviceReceived(const zx::channel& remote, const char* expected_driver, zx::channel* device_remote) { // Read the CreateDevice request. FIDL_ALIGNDECL uint8_t bytes[ZX_CHANNEL_MAX_MSG_BYTES]; zx_handle_t handles[ZX_CHANNEL_MAX_MSG_HANDLES]; uint32_t actual_bytes; uint32_t actual_handles; zx_status_t status = remote.read(0, bytes, handles, sizeof(bytes), fbl::count_of(handles), &actual_bytes, &actual_handles); ASSERT_OK(status); ASSERT_LT(0, actual_bytes); ASSERT_EQ(3, actual_handles); *device_remote = zx::channel(handles[0]); status = zx_handle_close(handles[1]); ASSERT_OK(status); // Validate the CreateDevice request. auto hdr = reinterpret_cast<fidl_message_header_t*>(bytes); ASSERT_EQ(fuchsia_device_manager_DevhostControllerCreateDeviceOrdinal, hdr->ordinal); status = fidl_decode(&fuchsia_device_manager_DevhostControllerCreateDeviceRequestTable, bytes, actual_bytes, handles, actual_handles, nullptr); ASSERT_OK(status); auto req = reinterpret_cast<fuchsia_device_manager_DevhostControllerCreateDeviceRequest*>( bytes); ASSERT_EQ(req->driver_path.size, strlen(expected_driver)); ASSERT_BYTES_EQ(reinterpret_cast<const uint8_t*>(expected_driver), reinterpret_cast<const uint8_t*>(req->driver_path.data), req->driver_path.size, ""); } // Reads a Suspend request from remote, checks that it is for the expected // flags, and then sends the given response. void CheckSuspendReceived(const zx::channel& remote, uint32_t expected_flags, zx_status_t return_status) { // Read the Suspend request. FIDL_ALIGNDECL uint8_t bytes[ZX_CHANNEL_MAX_MSG_BYTES]; zx_handle_t handles[ZX_CHANNEL_MAX_MSG_HANDLES]; uint32_t actual_bytes; uint32_t actual_handles; zx_status_t status = remote.read(0, bytes, handles, sizeof(bytes), fbl::count_of(handles), &actual_bytes, &actual_handles); ASSERT_OK(status); ASSERT_LT(0, actual_bytes); ASSERT_EQ(0, actual_handles); // Validate the Suspend request. auto hdr = reinterpret_cast<fidl_message_header_t*>(bytes); ASSERT_EQ(fuchsia_device_manager_DeviceControllerSuspendOrdinal, hdr->ordinal); status = fidl_decode(&fuchsia_device_manager_DeviceControllerSuspendRequestTable, bytes, actual_bytes, handles, actual_handles, nullptr); ASSERT_OK(status); auto req = reinterpret_cast<fuchsia_device_manager_DeviceControllerSuspendRequest*>(bytes); ASSERT_EQ(req->flags, expected_flags); // Write the Suspend response. memset(bytes, 0, sizeof(bytes)); auto resp = reinterpret_cast<fuchsia_device_manager_DeviceControllerSuspendResponse*>(bytes); resp->hdr.ordinal = fuchsia_device_manager_DeviceControllerSuspendOrdinal; resp->status = return_status; status = fidl_encode(&fuchsia_device_manager_DeviceControllerSuspendResponseTable, bytes, sizeof(*resp), handles, fbl::count_of(handles), &actual_handles, nullptr); ASSERT_OK(status); ASSERT_EQ(0, actual_handles); status = remote.write(0, bytes, sizeof(*resp), nullptr, 0); ASSERT_OK(status); } // Reads a CreateCompositeDevice from remote, checks expectations, and sends // a ZX_OK response. void CheckCreateCompositeDeviceReceived(const zx::channel& remote, const char* expected_name, size_t expected_components_count, zx::channel* composite_remote) { // Read the CreateCompositeDevice request. FIDL_ALIGNDECL uint8_t bytes[ZX_CHANNEL_MAX_MSG_BYTES]; zx_handle_t handles[ZX_CHANNEL_MAX_MSG_HANDLES]; uint32_t actual_bytes; uint32_t actual_handles; zx_status_t status = remote.read(0, bytes, handles, sizeof(bytes), fbl::count_of(handles), &actual_bytes, &actual_handles); ASSERT_OK(status); ASSERT_LT(0, actual_bytes); ASSERT_EQ(1, actual_handles); composite_remote->reset(handles[0]); // Validate the CreateCompositeDevice request. auto hdr = reinterpret_cast<fidl_message_header_t*>(bytes); ASSERT_EQ(fuchsia_device_manager_DevhostControllerCreateCompositeDeviceOrdinal, hdr->ordinal); status = fidl_decode(&fuchsia_device_manager_DevhostControllerCreateCompositeDeviceRequestTable, bytes, actual_bytes, handles, actual_handles, nullptr); ASSERT_OK(status); auto req = reinterpret_cast<fuchsia_device_manager_DevhostControllerCreateCompositeDeviceRequest*>( bytes); ASSERT_EQ(req->name.size, strlen(expected_name)); ASSERT_BYTES_EQ(reinterpret_cast<const uint8_t*>(expected_name), reinterpret_cast<const uint8_t*>(req->name.data), req->name.size, ""); ASSERT_EQ(expected_components_count, req->components.count); // Write the CreateCompositeDevice response. memset(bytes, 0, sizeof(bytes)); auto resp = reinterpret_cast<fuchsia_device_manager_DevhostControllerCreateCompositeDeviceResponse*>( bytes); resp->hdr.ordinal = fuchsia_device_manager_DevhostControllerCreateCompositeDeviceOrdinal; resp->status = ZX_OK; status = fidl_encode( &fuchsia_device_manager_DevhostControllerCreateCompositeDeviceResponseTable, bytes, sizeof(*resp), handles, fbl::count_of(handles), &actual_handles, nullptr); ASSERT_OK(status); ASSERT_EQ(0, actual_handles); status = remote.write(0, bytes, sizeof(*resp), nullptr, 0); ASSERT_OK(status); } // Helper for BindComposite for issuing an AddComposite for a composite with the // given components. It's assumed that these components are children of // the platform_bus and have the given protocol_id void BindCompositeDefineComposite(const fbl::RefPtr<devmgr::Device>& platform_bus, const uint32_t* protocol_ids, size_t component_count, const zx_device_prop_t* props, size_t props_count, const char* name, zx_status_t expected_status = ZX_OK) { auto components = std::make_unique<fuchsia_device_manager_DeviceComponent[]>(component_count); for (size_t i = 0; i < component_count; ++i) { // Define a union type to avoid violating the strict aliasing rule. union InstValue { zx_bind_inst_t inst; uint64_t value; }; InstValue always = {.inst = BI_MATCH()}; InstValue protocol = {.inst = BI_MATCH_IF(EQ, BIND_PROTOCOL, protocol_ids[i])}; fuchsia_device_manager_DeviceComponent* component = &components[i]; component->parts_count = 2; component->parts[0].match_program_count = 1; component->parts[0].match_program[0] = always.value; component->parts[1].match_program_count = 1; component->parts[1].match_program[0] = protocol.value; } devmgr::Coordinator* coordinator = platform_bus->coordinator; ASSERT_EQ(coordinator->AddCompositeDevice(platform_bus, name, props, props_count, components.get(), component_count, 0 /* coresident index */), expected_status); } struct DeviceState { // The representation in the coordinator of the device fbl::RefPtr<devmgr::Device> device; // The remote end of the channel that the coordinator is talking to zx::channel remote; }; class MultipleDeviceTestCase : public zxtest::Test { public: ~MultipleDeviceTestCase() override = default; async::Loop* loop() { return &loop_; } devmgr::Coordinator* coordinator() { return &coordinator_; } devmgr::Devhost* devhost() { return &devhost_; } const zx::channel& devhost_remote() { return devhost_remote_; } const fbl::RefPtr<devmgr::Device>& platform_bus() const { return platform_bus_.device; } const zx::channel& platform_bus_remote() const { return platform_bus_.remote; } DeviceState* device(size_t index) const { return &devices_[index]; } void AddDevice(const fbl::RefPtr<devmgr::Device>& parent, const char* name, uint32_t protocol_id, fbl::String driver, size_t* device_index); void RemoveDevice(size_t device_index); bool DeviceHasPendingMessages(size_t device_index); bool DeviceHasPendingMessages(const zx::channel& remote); void DoSuspend(uint32_t flags); protected: void SetUp() override { ASSERT_NO_FATAL_FAILURES(InitializeCoordinator(&coordinator_)); // refcount starts at zero, so bump it up to keep us from being cleaned up devhost_.AddRef(); { zx::channel local; zx_status_t status = zx::channel::create(0, &local, &devhost_remote_); ASSERT_EQ(ZX_OK, status); devhost_.set_hrpc(local.release()); } // Set up the sys device proxy, inside of the devhost ASSERT_EQ(coordinator_.PrepareProxy(coordinator_.sys_device(), &devhost_), ZX_OK); loop_.RunUntilIdle(); ASSERT_NO_FATAL_FAILURES(CheckCreateDeviceReceived(devhost_remote_, kSystemDriverPath, &sys_proxy_remote_)); loop_.RunUntilIdle(); // Create a child of the sys_device (an equivalent of the platform bus) { zx::channel local; zx_status_t status = zx::channel::create(0, &local, &platform_bus_.remote); ASSERT_EQ(ZX_OK, status); status = coordinator_.AddDevice(coordinator_.sys_device()->proxy, std::move(local), nullptr /* props_data */, 0 /* props_count */, "platform-bus", 0, nullptr /* driver_path */, nullptr /* args */, false /* invisible */, zx::channel() /* client_remote */, &platform_bus_.device); ASSERT_EQ(ZX_OK, status); loop_.RunUntilIdle(); } } void TearDown() override { loop_.RunUntilIdle(); // Remove the devices in the opposite order that we added them while (!devices_.is_empty()) { devices_.pop_back(); loop_.RunUntilIdle(); } platform_bus_.device.reset(); loop_.RunUntilIdle(); devhost_.devices().clear(); } async::Loop loop_{&kAsyncLoopConfigNoAttachToThread}; devmgr::Coordinator coordinator_{DefaultConfig(loop_.dispatcher())}; // The fake devhost that the platform bus is put into devmgr::Devhost devhost_; // The remote end of the channel that the coordinator uses to talk to the // devhost zx::channel devhost_remote_; // The remote end of the channel that the coordinator uses to talk to the // sys device proxy zx::channel sys_proxy_remote_; // The device object representing the platform bus driver (child of the // sys proxy) DeviceState platform_bus_; // A list of all devices that were added during this test, and their // channels. These exist to keep them alive until the test is over. fbl::Vector<DeviceState> devices_; }; void MultipleDeviceTestCase::AddDevice(const fbl::RefPtr<devmgr::Device>& parent, const char* name, uint32_t protocol_id, fbl::String driver, size_t* index) { DeviceState state; zx::channel local; zx_status_t status = zx::channel::create(0, &local, &state.remote); ASSERT_EQ(ZX_OK, status); status = coordinator_.AddDevice(parent, std::move(local), nullptr /* props_data */, 0 /* props_count */, name, protocol_id, driver.data() /* driver_path */, nullptr /* args */, false /* invisible */, zx::channel() /* client_remote */, &state.device); ASSERT_EQ(ZX_OK, status); loop_.RunUntilIdle(); devices_.push_back(std::move(state)); *index = devices_.size() - 1; } void MultipleDeviceTestCase::RemoveDevice(size_t device_index) { auto& state = devices_[device_index]; ASSERT_OK(coordinator_.RemoveDevice(state.device, false)); state.device.reset(); state.remote.reset(); loop_.RunUntilIdle(); } bool MultipleDeviceTestCase::DeviceHasPendingMessages(const zx::channel& remote) { return remote.wait_one(ZX_CHANNEL_READABLE, zx::time(0), nullptr) == ZX_OK; } bool MultipleDeviceTestCase::DeviceHasPendingMessages(size_t device_index) { return DeviceHasPendingMessages(devices_[device_index].remote); } void MultipleDeviceTestCase::DoSuspend(uint32_t flags) { const bool vfs_exit_expected = (flags != DEVICE_SUSPEND_FLAG_SUSPEND_RAM); if (vfs_exit_expected) { zx::unowned_event event(coordinator()->fshost_event()); auto thrd_func = [](void* ctx) -> int { zx::unowned_event event(*static_cast<zx::unowned_event*>(ctx)); if (event->wait_one(FSHOST_SIGNAL_EXIT, zx::time::infinite(), nullptr) != ZX_OK) { return false; } if (event->signal(0, FSHOST_SIGNAL_EXIT_DONE) != ZX_OK) { return false; } return true; }; thrd_t fshost_thrd; ASSERT_EQ(thrd_create(&fshost_thrd, thrd_func, &event), thrd_success); coordinator()->Suspend(flags); loop()->RunUntilIdle(); int thread_status; ASSERT_EQ(thrd_join(fshost_thrd, &thread_status), thrd_success); ASSERT_TRUE(thread_status); // Make sure that vfs_exit() happened. ASSERT_OK(coordinator()->fshost_event().wait_one(FSHOST_SIGNAL_EXIT_DONE, zx::time(0), nullptr)); } else { coordinator()->Suspend(flags); loop()->RunUntilIdle(); // Make sure that vfs_exit() didn't happen. ASSERT_EQ( coordinator()->fshost_event().wait_one(FSHOST_SIGNAL_EXIT | FSHOST_SIGNAL_EXIT_DONE, zx::time(0), nullptr), ZX_ERR_TIMED_OUT); } } class SuspendTestCase : public MultipleDeviceTestCase { public: void SuspendTest(uint32_t flags); }; TEST_F(SuspendTestCase, Poweroff) { ASSERT_NO_FATAL_FAILURES(SuspendTest(DEVICE_SUSPEND_FLAG_POWEROFF)); } TEST_F(SuspendTestCase, Reboot) { ASSERT_NO_FATAL_FAILURES(SuspendTest(DEVICE_SUSPEND_FLAG_REBOOT)); } TEST_F(SuspendTestCase, RebootWithFlags) { ASSERT_NO_FATAL_FAILURES(SuspendTest(DEVICE_SUSPEND_FLAG_REBOOT_BOOTLOADER)); } TEST_F(SuspendTestCase, Mexec) { ASSERT_NO_FATAL_FAILURES(SuspendTest(DEVICE_SUSPEND_FLAG_MEXEC)); } TEST_F(SuspendTestCase, SuspendToRam) { ASSERT_NO_FATAL_FAILURES(SuspendTest(DEVICE_SUSPEND_FLAG_SUSPEND_RAM)); } // Verify the suspend order is correct void SuspendTestCase::SuspendTest(uint32_t flags) { struct DeviceDesc { // Index into the device desc array below. UINT32_MAX = platform_bus() const size_t parent_desc_index; const char* const name; // index for use with device() size_t index = 0; bool suspended = false; }; DeviceDesc devices[] = { { UINT32_MAX, "root_child1" }, { UINT32_MAX, "root_child2" }, { 0, "root_child1_1" }, { 0, "root_child1_2" }, { 2, "root_child1_1_1" }, { 1, "root_child2_1" }, }; for (auto& desc : devices) { fbl::RefPtr<devmgr::Device> parent; if (desc.parent_desc_index == UINT32_MAX) { parent = platform_bus(); } else { size_t index = devices[desc.parent_desc_index].index; parent = device(index)->device; } ASSERT_NO_FATAL_FAILURES(AddDevice(parent, desc.name, 0 /* protocol id */, "", &desc.index)); } ASSERT_NO_FATAL_FAILURES(DoSuspend(flags)); size_t num_to_suspend = fbl::count_of(devices); while (num_to_suspend > 0) { // Check that platform bus is not suspended yet. ASSERT_FALSE(DeviceHasPendingMessages(platform_bus_remote())); bool made_progress = false; // Since the table of devices above is topologically sorted (i.e. // any child is below its parent), this loop should always be able // to catch a parent receiving a suspend message before its child. for (size_t i = 0; i < fbl::count_of(devices); ++i) { auto& desc = devices[i]; if (desc.suspended) { continue; } if (!DeviceHasPendingMessages(desc.index)) { continue; } ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived( device(desc.index)->remote, flags, ZX_OK)); // Make sure all descendants of this device are already suspended. // We just need to check immediate children since this will // recursively enforce that property. for (auto& other_desc : devices) { if (other_desc.parent_desc_index == i) { ASSERT_TRUE(other_desc.suspended); } } desc.suspended = true; --num_to_suspend; made_progress = true; } // Make sure we're not stuck waiting ASSERT_TRUE(made_progress); loop()->RunUntilIdle(); } ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived(platform_bus_remote(), flags, ZX_OK)); } class CompositeTestCase : public MultipleDeviceTestCase { public: ~CompositeTestCase() override = default; void CheckCompositeCreation(const char* composite_name, const size_t* device_indexes, size_t device_indexes_count, size_t* component_indexes_out, zx::channel* composite_remote_out); protected: void SetUp() override { MultipleDeviceTestCase::SetUp(); ASSERT_NOT_NULL(coordinator_.component_driver()); } }; void CompositeTestCase::CheckCompositeCreation(const char* composite_name, const size_t* device_indexes, size_t device_indexes_count, size_t* component_indexes_out, zx::channel* composite_remote_out) { for (size_t i = 0; i < device_indexes_count; ++i) { auto device_state = device(device_indexes[i]); // Check that the components got bound fbl::String driver = coordinator()->component_driver()->libname; ASSERT_NO_FATAL_FAILURES(CheckBindDriverReceived(device_state->remote, driver.data())); loop()->RunUntilIdle(); // Synthesize the AddDevice request the component driver would send char name[32]; snprintf(name, sizeof(name), "component-device-%zu", i); ASSERT_NO_FATAL_FAILURES(AddDevice(device_state->device, name, 0, driver, &component_indexes_out[i])); } // Make sure the composite comes up ASSERT_NO_FATAL_FAILURES(CheckCreateCompositeDeviceReceived(devhost_remote(), composite_name, device_indexes_count, composite_remote_out)); } class CompositeAddOrderTestCase : public CompositeTestCase { public: enum class AddLocation { // Add the composite before any components BEFORE, // Add the composite after some components MIDDLE, // Add the composite after all components AFTER, }; void ExecuteTest(AddLocation add); }; void CompositeAddOrderTestCase::ExecuteTest(AddLocation add) { size_t device_indexes[3]; uint32_t protocol_id[] = { ZX_PROTOCOL_GPIO, ZX_PROTOCOL_I2C, ZX_PROTOCOL_ETHERNET, }; static_assert(fbl::count_of(protocol_id) == fbl::count_of(device_indexes)); const char* kCompositeDevName = "composite-dev"; auto do_add = [&]() { ASSERT_NO_FATAL_FAILURES(BindCompositeDefineComposite( platform_bus(), protocol_id, fbl::count_of(protocol_id), nullptr /* props */, 0, kCompositeDevName)); }; if (add == AddLocation::BEFORE) { ASSERT_NO_FATAL_FAILURES(do_add()); } // Add the devices to construct the composite out of. for (size_t i = 0; i < fbl::count_of(device_indexes); ++i) { char name[32]; snprintf(name, sizeof(name), "device-%zu", i); ASSERT_NO_FATAL_FAILURES(AddDevice(platform_bus(), name, protocol_id[i], "", &device_indexes[i])); if (i == 0 && add == AddLocation::MIDDLE) { ASSERT_NO_FATAL_FAILURES(do_add()); } } if (add == AddLocation::AFTER) { ASSERT_NO_FATAL_FAILURES(do_add()); } zx::channel composite_remote; size_t component_device_indexes[fbl::count_of(device_indexes)]; ASSERT_NO_FATAL_FAILURES(CheckCompositeCreation(kCompositeDevName, device_indexes, fbl::count_of(device_indexes), component_device_indexes, &composite_remote)); } TEST_F(CompositeAddOrderTestCase, DefineBeforeDevices) { ASSERT_NO_FATAL_FAILURES(ExecuteTest(AddLocation::BEFORE)); } TEST_F(CompositeAddOrderTestCase, DefineInbetweenDevices) { ASSERT_NO_FATAL_FAILURES(ExecuteTest(AddLocation::MIDDLE)); } TEST_F(CompositeAddOrderTestCase, DefineAfterDevices) { ASSERT_NO_FATAL_FAILURES(ExecuteTest(AddLocation::AFTER)); } TEST_F(CompositeTestCase, CantAddFromNonPlatformBus) { size_t index; ASSERT_NO_FATAL_FAILURES(AddDevice(platform_bus(), "test-device", 0, "", &index)); auto device_state = device(index); uint32_t protocol_id[] = { ZX_PROTOCOL_I2C, ZX_PROTOCOL_GPIO }; ASSERT_NO_FATAL_FAILURES(BindCompositeDefineComposite( device_state->device, protocol_id, fbl::count_of(protocol_id), nullptr /* props */, 0, "composite-dev", ZX_ERR_ACCESS_DENIED)); } TEST_F(CompositeTestCase, ComponentUnbinds) { size_t device_indexes[2]; uint32_t protocol_id[] = { ZX_PROTOCOL_GPIO, ZX_PROTOCOL_I2C, }; static_assert(fbl::count_of(protocol_id) == fbl::count_of(device_indexes)); const char* kCompositeDevName = "composite-dev"; ASSERT_NO_FATAL_FAILURES(BindCompositeDefineComposite( platform_bus(), protocol_id, fbl::count_of(protocol_id), nullptr /* props */, 0, kCompositeDevName)); // Add the devices to construct the composite out of. for (size_t i = 0; i < fbl::count_of(device_indexes); ++i) { char name[32]; snprintf(name, sizeof(name), "device-%zu", i); ASSERT_NO_FATAL_FAILURES(AddDevice(platform_bus(), name, protocol_id[i], "", &device_indexes[i])); } zx::channel composite_remote; size_t component_device_indexes[fbl::count_of(device_indexes)]; ASSERT_NO_FATAL_FAILURES(CheckCompositeCreation(kCompositeDevName, device_indexes, fbl::count_of(device_indexes), component_device_indexes, &composite_remote)); loop()->RunUntilIdle(); { // Remove device the composite, device 0's component device, and device 0 auto device1 = device(device_indexes[1])->device; auto composite = device1->component()->composite()->device(); ASSERT_OK(coordinator()->RemoveDevice(composite, false)); ASSERT_NO_FATAL_FAILURES(RemoveDevice(component_device_indexes[0])); ASSERT_NO_FATAL_FAILURES(RemoveDevice(device_indexes[0])); } // Add the device back and verify the composite gets created again ASSERT_NO_FATAL_FAILURES(AddDevice(platform_bus(), "device-0", protocol_id[0], "", &device_indexes[0])); { auto device_state = device(device_indexes[0]); // Wait for the components to get bound fbl::String driver = coordinator()->component_driver()->libname; ASSERT_NO_FATAL_FAILURES(CheckBindDriverReceived(device_state->remote, driver.data())); loop()->RunUntilIdle(); // Synthesize the AddDevice request the component driver would send ASSERT_NO_FATAL_FAILURES(AddDevice(device_state->device, "component-device-0", 0, driver, &component_device_indexes[0])); } ASSERT_NO_FATAL_FAILURES(CheckCreateCompositeDeviceReceived(devhost_remote(), kCompositeDevName, fbl::count_of(device_indexes), &composite_remote)); } TEST_F(CompositeTestCase, SuspendOrder) { size_t device_indexes[2]; uint32_t protocol_id[] = { ZX_PROTOCOL_GPIO, ZX_PROTOCOL_I2C, }; static_assert(fbl::count_of(protocol_id) == fbl::count_of(device_indexes)); const char* kCompositeDevName = "composite-dev"; ASSERT_NO_FATAL_FAILURES(BindCompositeDefineComposite( platform_bus(), protocol_id, fbl::count_of(protocol_id), nullptr /* props */, 0, kCompositeDevName)); // Add the devices to construct the composite out of. for (size_t i = 0; i < fbl::count_of(device_indexes); ++i) { char name[32]; snprintf(name, sizeof(name), "device-%zu", i); ASSERT_NO_FATAL_FAILURES(AddDevice(platform_bus(), name, protocol_id[i], "", &device_indexes[i])); } zx::channel composite_remote; size_t component_device_indexes[fbl::count_of(device_indexes)]; ASSERT_NO_FATAL_FAILURES(CheckCompositeCreation(kCompositeDevName, device_indexes, fbl::count_of(device_indexes), component_device_indexes, &composite_remote)); const uint32_t suspend_flags = DEVICE_SUSPEND_FLAG_POWEROFF; ASSERT_NO_FATAL_FAILURES(DoSuspend(suspend_flags)); // Make sure none of the components have received their suspend requests ASSERT_FALSE(DeviceHasPendingMessages(platform_bus_remote())); for (auto idx : device_indexes) { ASSERT_FALSE(DeviceHasPendingMessages(idx)); } for (auto idx : component_device_indexes) { ASSERT_FALSE(DeviceHasPendingMessages(idx)); } // The composite should have been the first to get one ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived(composite_remote, suspend_flags, ZX_OK)); loop()->RunUntilIdle(); // Next, all of the internal component devices should have them, but none of the devices // themselves ASSERT_FALSE(DeviceHasPendingMessages(platform_bus_remote())); for (auto idx : device_indexes) { ASSERT_FALSE(DeviceHasPendingMessages(idx)); } for (auto idx : component_device_indexes) { ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived(device(idx)->remote, suspend_flags, ZX_OK)); } loop()->RunUntilIdle(); // Next, the devices should get them ASSERT_FALSE(DeviceHasPendingMessages(platform_bus_remote())); for (auto idx : device_indexes) { ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived(device(idx)->remote, suspend_flags, ZX_OK)); } loop()->RunUntilIdle(); // Finally, the platform bus driver, which is the parent of all of the devices ASSERT_NO_FATAL_FAILURES(CheckSuspendReceived(platform_bus_remote(), suspend_flags, ZX_OK)); loop()->RunUntilIdle(); } } // namespace int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); }
41.464726
109
0.656692
[ "object", "vector" ]
f110fab1b8d20d81aab8fa2abf040b1606040a8a
33,596
cpp
C++
koptions.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
koptions.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
koptions.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
/* // // DEKAF(tm): Lighter, Faster, Smarter(tm) // // Copyright (c) 2018, Ridgeware, Inc. // // +-------------------------------------------------------------------------+ // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\| // |/+---------------------------------------------------------------------+/| // |/| |/| // |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\| // |/| |/| // |\| OPEN SOURCE LICENSE |\| // |/| |/| // |\| 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 "koptions.h" #include "kstream.h" #include "klog.h" #include "ksplit.h" #include "kfilesystem.h" #include "kstringutils.h" #include "kcgistream.h" #include "kurl.h" #include "khttp_header.h" #include "dekaf2.h" namespace dekaf2 { namespace { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /// small RAII helper to make sure we reset an output stream pointer /// when the reference for it goes out of scope struct KOutStreamRAII //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: { KOutStreamRAII(KOutStream** Var, KOutStream& Stream) : m_Old(*Var) , m_Var(Var) { *Var = &Stream; } ~KOutStreamRAII() { *m_Var = m_Old; } private: KOutStream* m_Old; KOutStream** m_Var; }; // KOutStreamRAII } // end of anonymous namespace //--------------------------------------------------------------------------- KOptions::OptionalParm::OptionalParm(KOptions& base, KStringView sOption, KStringViewZ sArgDescription, bool bIsCommand) //--------------------------------------------------------------------------- : CallbackParam(sOption, sArgDescription, bIsCommand ? fIsCommand : fNone) , m_base(&base) { if (m_iMinArgs == 0 && !m_sMissingArgs.empty()) { m_iMinArgs = 1; } } //--------------------------------------------------------------------------- KOptions::OptionalParm::~OptionalParm() //--------------------------------------------------------------------------- { m_base->Register(std::move(*this)); } //--------------------------------------------------------------------------- KOptions::OptionalParm& KOptions::OptionalParm::Help(KStringView sHelp) //--------------------------------------------------------------------------- { m_sHelp = sHelp.Trim(); return *this; } // Help //--------------------------------------------------------------------------- KOptions::OptionalParm& KOptions::OptionalParm::Range(int64_t iLowerBound, int64_t iUpperBound) //--------------------------------------------------------------------------- { if (iLowerBound > iUpperBound) { std::swap(iLowerBound, iUpperBound); } m_iLowerBound = iLowerBound; m_iUpperBound = iUpperBound; m_iFlags |= fCheckBounds; return *this; } // Range //--------------------------------------------------------------------------- KOptions::OptionalParm& KOptions::OptionalParm::Callback(CallbackN Func) //--------------------------------------------------------------------------- { m_Callback = std::move(Func); return *this; } //--------------------------------------------------------------------------- KOptions::OptionalParm& KOptions::OptionalParm::Callback(Callback1 Func) //--------------------------------------------------------------------------- { Callback([func = std::move(Func)](ArgList& args) { func(args.pop()); }); m_iMinArgs = 1; m_iMaxArgs = 1; return *this; } //--------------------------------------------------------------------------- KOptions::OptionalParm& KOptions::OptionalParm::Callback(Callback0 Func) //--------------------------------------------------------------------------- { Callback([func = std::move(Func)](ArgList& unused) { func(); }); m_iMinArgs = 0; m_iMaxArgs = 0; return *this; } //--------------------------------------------------------------------------- KOptions::CLIParms::Arg_t::Arg_t(KStringViewZ sArg_) //--------------------------------------------------------------------------- : sArg(sArg_) , bConsumed { false } , iDashes { 0 } { if (sArg.front() == '-') { if (sArg.size() > 1 && !KASCII::kIsDigit(sArg[1])) { if (sArg[1] == '-') { if (sArg.size() > 2) { sArg.remove_prefix(2); iDashes = 2; } // double dash, leave alone } else { sArg.remove_prefix(1); iDashes = 1; } } // single dash or negative number, leave alone } } // Arg_t ctor //--------------------------------------------------------------------------- KStringViewZ KOptions::CLIParms::Arg_t::Dashes() const //--------------------------------------------------------------------------- { KStringViewZ sReturn { s_sDoubleDash }; sReturn.remove_prefix(2 - iDashes); return sReturn; } // Dashes //--------------------------------------------------------------------------- void KOptions::CLIParms::Create(int argc, char const* const* argv) //--------------------------------------------------------------------------- { m_ArgVec.clear(); m_ArgVec.reserve(argc); for (int ii = 0; ii < argc; ++ii) { m_ArgVec.push_back(KStringViewZ(*argv++)); } if (!m_ArgVec.empty()) { m_sProgramPathName = m_ArgVec.front().sArg; m_ArgVec.front().bConsumed = true; } } // CLIParms::Create //--------------------------------------------------------------------------- void KOptions::CLIParms::Create(const std::vector<KStringViewZ>& parms) //--------------------------------------------------------------------------- { m_ArgVec.clear(); m_ArgVec.reserve(parms.size()); for (auto it : parms) { m_ArgVec.push_back(it); } if (!m_ArgVec.empty()) { m_sProgramPathName = m_ArgVec.front().sArg; m_ArgVec.front().bConsumed = true; } } // CLIParms::Create //--------------------------------------------------------------------------- KStringViewZ KOptions::CLIParms::GetProgramPath() const //--------------------------------------------------------------------------- { return m_sProgramPathName; } // CLIParms::GetProgramPath //--------------------------------------------------------------------------- KStringView KOptions::CLIParms::GetProgramName() const //--------------------------------------------------------------------------- { return kBasename(GetProgramPath()); } // CLIParms::GetProgramName //--------------------------------------------------------------------------- KOptions::KOptions(bool bEmptyParmsIsError, KStringView sCliDebugTo/*=KLog::STDOUT*/, bool bThrow/*=false*/) //--------------------------------------------------------------------------- : m_bThrow(bThrow) , m_bEmptyParmsIsError(bEmptyParmsIsError) { SetBriefDescription("KOptions based option parsing"); SetMaxHelpWidth(120); SetWrappedHelpIndent(0); Option("help") .Help("this text") ([this]() { auto& out = GetCurrentOutputStream(); if (m_sHelp) { for (size_t iCount = 0; iCount < m_iHelpSize; ++iCount) { out.WriteLine(m_sHelp[iCount]); } } else { BuildHelp(out); } // and abort further parsing throw NoError {}; }); Option("d0,d,dd,ddd") .Help("increasing optional stdout debug levels") ([this,sCliDebugTo]() { auto sArg = GetCurrentArg(); auto iLevel = (sArg == "d0") ? 0 : sArg.size(); KLog::getInstance().SetLevel (iLevel); KLog::getInstance().SetDebugLog (sCliDebugTo); KLog::getInstance().KeepCLIMode (true); kDebug (1, "debug level set to: {}", KLog::getInstance().GetLevel()); }); Option("dgrep,dgrepv <regex>", "grep expression") .Help("search (not) for grep expression in debug output") ([this,sCliDebugTo](KStringViewZ sGrep) { bool bIsInverted = GetCurrentArg() == "dgrepv"; // if no -d option has been applied yet switch to -ddd if (KLog::getInstance().GetLevel() <= 0) { KLog::getInstance().SetLevel (3); kDebug (1, "debug level set to: {}", KLog::getInstance().GetLevel()); } KLog::getInstance().SetDebugLog (sCliDebugTo); kDebug (1, "debug {} set to: '{}'", bIsInverted ? "egrep -v" : "egrep", sGrep); KLog::getInstance().LogWithGrepExpression(true, bIsInverted, sGrep); KLog::getInstance().KeepCLIMode (true); }); Option("ini <filename>", "ini file name") .Help("load options from ini file") ([this](KStringViewZ sIni) { if (ParseFile(sIni, KOut)) { // error was already displayed - just abort parsing throw NoError {}; } }); } // KOptions ctor namespace { //--------------------------------------------------------------------------- KStringView WrapOutput(KStringView& sInput, std::size_t iMaxSize) //--------------------------------------------------------------------------- { auto sWrapped = sInput; if (sWrapped.size() > iMaxSize) { sWrapped.erase(iMaxSize); if (!(sInput.size() > iMaxSize && KASCII::kIsSpace(sInput[sWrapped.size()]))) { sWrapped.erase(sWrapped.find_last_of(detail::kASCIISpaces)); } else { // do not erase the last part of sWrapped if it ended in a space, // instead only remove trailing spaces sWrapped.TrimRight(); } } if (sWrapped.empty()) { if (!sInput.empty()) { // this is only possible due to a logic error, // make sure we do not loop forever kDebugLog(1, "KOptions::WrapOutput() resulted in an empty string"); sWrapped = sInput; } } sInput.remove_prefix(sWrapped.size()); sInput.TrimLeft(); return sWrapped; } // WrapOutput } // end of anonymous namespace //--------------------------------------------------------------------------- void KOptions::BuildHelp(KOutStream& out) const //--------------------------------------------------------------------------- { std::size_t iMaxLen { 0 }; for (const auto& Callback : m_Callbacks) { auto iSize = (Callback.m_sNames.front() == '-') ? Callback.m_sNames.size() - 1 : Callback.m_sNames.size(); iMaxLen = std::max(iMaxLen, iSize); } out.WriteLine(); out.Format("{} -- ", GetProgramName()); { auto iIndent = GetProgramName().size() + 4; auto sDescription = GetBriefDescription(); auto sLimited = WrapOutput(sDescription, m_iMaxHelpRowWidth - iIndent); out.WriteLine(sLimited); iIndent += m_iWrappedHelpIndent; while (sDescription.size()) { auto iSpaces = iIndent; while (iSpaces--) { out.Write(' '); } auto sLimited = WrapOutput(sDescription, m_iMaxHelpRowWidth - iIndent); out.WriteLine(sLimited); } } out.WriteLine(); out.FormatLine("usage: {}{}{}", GetProgramName(), m_bHaveOptions ? " [<options>]" : "", m_bHaveCommands ? " [<actions>]" : ""); out.WriteLine(); auto iMaxHelp = m_iMaxHelpRowWidth - (iMaxLen + m_sSeparator.size() + 5); // format wrapped help texts so that they start earlier at the left if // argument size is bigger than help size bool bOverlapping = iMaxHelp < iMaxLen; // kFormat crashes when we insert the spacing parm at the same time with // the actual parms, therefore we prepare the format strings before inserting // the parms auto sFormat = kFormat(" {{}}{{:<{}}} {{}}{} {{}}", iMaxLen, m_sSeparator); auto sOverflow = kFormat(" {{:<{}}} {{}}", bOverlapping ? 1 + m_iWrappedHelpIndent // we need the + 1 to avoid a total of 0 which would crash kFormat : 2 + iMaxLen + m_sSeparator.size() + m_iWrappedHelpIndent); auto Show = [&](bool bCommands) { for (const auto& Callback : m_Callbacks) { if (Callback.IsCommand() == bCommands && Callback.m_sNames != "!") { bool bFirst = true; auto iHelp = iMaxHelp; auto sHelp = Callback.m_sHelp; if (sHelp.empty()) { sHelp = Callback.m_sMissingArgs; } while (bFirst || sHelp.size()) { auto sLimited = WrapOutput(sHelp, iHelp); if (bFirst) { bFirst = false; out.FormatLine(sFormat, (!Callback.IsCommand() && Callback.m_sNames.front() != '-') ? "-" : "", Callback.m_sNames, bCommands ? " " : "", sLimited); if (bOverlapping) { iHelp = m_iMaxHelpRowWidth - (1 + m_iWrappedHelpIndent); } else { iHelp -= m_iWrappedHelpIndent; } } else { out.FormatLine(sOverflow, "", sLimited); } } } } }; if (m_bHaveOptions) { out.WriteLine("where <options> are:"); Show(false); out.WriteLine(); } if (m_bHaveCommands) { out.FormatLine("{} <actions> are:", m_bHaveOptions ? "and" : "where"); Show(true); out.WriteLine(); } } // BuildHelp //--------------------------------------------------------------------------- void KOptions::Help(KOutStream& out) //--------------------------------------------------------------------------- { KOutStreamRAII KO(&m_CurrentOutputStream, out); // we have a help option registered through the constructor auto Callback = FindParam("help", true); if (!Callback) { SetError("no help registered"); } else { try { // yes - call the function with empty args ArgList Args; Callback->m_Callback(Args); } DEKAF2_CATCH (const NoError& error) { #ifdef _MSC_VER error.what(); #endif } } } // Help //--------------------------------------------------------------------------- KOptions::OptionalParm KOptions::Option(KStringView sOption, KStringViewZ sArgDescription) //--------------------------------------------------------------------------- { return OptionalParm(*this, sOption, sArgDescription, false); } //--------------------------------------------------------------------------- KOptions::OptionalParm KOptions::Command(KStringView sCommand, KStringViewZ sArgDescription) //--------------------------------------------------------------------------- { return OptionalParm(*this, sCommand, sArgDescription, true); } //--------------------------------------------------------------------------- const KOptions::CallbackParam* KOptions::FindParam(KStringView sName, bool bIsOption) const //--------------------------------------------------------------------------- { auto& Lookup = bIsOption ? m_Options : m_Commands; auto it = Lookup.find(sName); if (it == Lookup.end() || it->second >= m_Callbacks.size()) { return nullptr; } auto Callback = &m_Callbacks[it->second]; // mark option as used Callback->m_bUsed = true; return Callback; } // FindParam //--------------------------------------------------------------------------- void KOptions::Register(CallbackParam OptionOrCommand) //--------------------------------------------------------------------------- { auto& Lookup = OptionOrCommand.IsCommand() ? m_Commands : m_Options; auto iIndex = m_Callbacks.size(); for (auto sOption : OptionOrCommand.m_sNames.Split()) { if (sOption != "!") { sOption.TrimLeft(OptionOrCommand.IsCommand() ? " \f\v\t\r\n\b" : " -\f\v\t\r\n\b"); if (sOption.front() == '-') { SetError(kFormat("a command, other than an option, may not start with - : {}", sOption)); return; } // strip name at first special character or space auto pos = sOption.find_first_of(" <>[]|=\t\r\n\b"); if (pos != KStringView::npos) { sOption.erase(pos); } if (OptionOrCommand.IsCommand()) { m_bHaveCommands = true; } else { m_bHaveOptions = true; } } kDebug(3, "adding option: '{}'", sOption); auto Pair = Lookup.insert( { sOption, iIndex } ); if (!Pair.second) { kDebug(1, "overriding existing {}: {}", OptionOrCommand.IsCommand() ? "command" : "option", sOption); Pair.first->second = iIndex; } } m_Callbacks.push_back(std::move(OptionOrCommand)); if (m_Callbacks.size() != iIndex+1) { SetError("registration race"); } } // Register //--------------------------------------------------------------------------- void KOptions::RegisterUnknownOption(CallbackN Function) //--------------------------------------------------------------------------- { Register(CallbackParam("!", CallbackParam::fNone, 0, "", Function)); } //--------------------------------------------------------------------------- void KOptions::RegisterUnknownCommand(CallbackN Function) //--------------------------------------------------------------------------- { Register(CallbackParam("!", CallbackParam::fIsCommand, 0, "", Function)); } //--------------------------------------------------------------------------- void KOptions::RegisterOption(KStringView sOptions, uint16_t iMinArgs, KStringViewZ sMissingParms, CallbackN Function) //--------------------------------------------------------------------------- { Register(CallbackParam(sOptions, CallbackParam::fNone, iMinArgs, sMissingParms, Function)); } //--------------------------------------------------------------------------- void KOptions::RegisterCommand(KStringView sCommands, uint16_t iMinArgs, KStringViewZ sMissingParms, CallbackN Function) //--------------------------------------------------------------------------- { Register(CallbackParam(sCommands, CallbackParam::fIsCommand, iMinArgs, sMissingParms, Function)); } //--------------------------------------------------------------------------- void KOptions::RegisterOption(KStringView sOption, Callback0 Function) //--------------------------------------------------------------------------- { RegisterOption(sOption, 0, "", [func = std::move(Function)](ArgList& unused) { func(); }); } //--------------------------------------------------------------------------- void KOptions::RegisterCommand(KStringView sCommand, Callback0 Function) //--------------------------------------------------------------------------- { RegisterCommand(sCommand, 0, "", [func = std::move(Function)](ArgList& unused) { func(); }); } //--------------------------------------------------------------------------- void KOptions::RegisterOption(KStringView sOption, KStringViewZ sMissingParm, Callback1 Function) //--------------------------------------------------------------------------- { RegisterOption(sOption, 1, sMissingParm, [func = std::move(Function)](ArgList& args) { func(args.pop()); }); } //--------------------------------------------------------------------------- void KOptions::RegisterCommand(KStringView sCommand, KStringViewZ sMissingParm, Callback1 Function) //--------------------------------------------------------------------------- { RegisterCommand(sCommand, 1, sMissingParm, [func = std::move(Function)](ArgList& args) { func(args.pop()); }); } //--------------------------------------------------------------------------- int KOptions::Parse(int argc, char const* const* argv, KOutStream& out) //--------------------------------------------------------------------------- { return Execute(CLIParms(argc, argv), out); } // Parse //--------------------------------------------------------------------------- int KOptions::Parse(KString sCLI, KOutStream& out) //--------------------------------------------------------------------------- { kDebug (1, sCLI); // create a permanent buffer of the passed CLI m_ParmBuffer.push_front(std::move(sCLI)); std::vector<KStringViewZ> parms; kSplitArgsInPlace(parms, m_ParmBuffer.front(), /*svDelim =*/" \f\v\t\r\n\b", /*svQuotes =*/"\"'", /*chEscape =*/'\\'); return Execute(CLIParms(parms), out); } // Parse //----------------------------------------------------------------------------- int KOptions::Parse(KInStream& In, KOutStream& out) //----------------------------------------------------------------------------- { KString sCLI = kFirstNonEmpty(GetProgramPath(), Dekaf::getInstance().GetProgName(), "Unnamed"); for (auto& sLine : In) { sLine.Trim(); if (!sLine.empty() && sLine.front() != '#') { sCLI += ' '; sCLI += sLine; } } return Parse(std::move(sCLI), out); } // Parse //----------------------------------------------------------------------------- int KOptions::ParseFile(KStringViewZ sFileName, KOutStream& out) //----------------------------------------------------------------------------- { KInFile InFile(sFileName); if (!InFile.is_open()) { return SetError(kFormat("cannot open input file: {}", sFileName)); } return Parse(InFile, out); } // ParseFile //--------------------------------------------------------------------------- int KOptions::ParseCGI(KStringViewZ sProgramName, KOutStream& out) //--------------------------------------------------------------------------- { url::KQuery Query; // parse and dequote the query string parameters Query.Parse(kGetEnv(KCGIInStream::QUERY_STRING)); // create a permanent buffer for the strings, as the rest of // KOptions operates on string views m_ParmBuffer.push_front(sProgramName); // create a vector of string views pointing to the string buffers std::vector<KStringViewZ> QueryArgs; QueryArgs.push_back(m_ParmBuffer.front()); for (const auto& it : Query.get()) { m_ParmBuffer.push_front(std::move(it.first)); QueryArgs.push_back(m_ParmBuffer.front()); if (!it.second.empty()) { m_ParmBuffer.push_front(std::move(it.second)); QueryArgs.push_back(m_ParmBuffer.front()); } } kDebug(2, "parsed {} arguments from CGI query string: {}", QueryArgs.size() - 1, kJoined(QueryArgs, " ")); return Execute(CLIParms(QueryArgs), out); } // ParseCGI //--------------------------------------------------------------------------- bool KOptions::IsCGIEnvironment() //--------------------------------------------------------------------------- { return !kGetEnv(KCGIInStream::REQUEST_METHOD).empty(); } //--------------------------------------------------------------------------- KOutStream& KOptions::GetCurrentOutputStream() //--------------------------------------------------------------------------- { if (m_CurrentOutputStream) { return *m_CurrentOutputStream; } else { return KOut; } } // GetCurrentOutputStream //--------------------------------------------------------------------------- int KOptions::SetError(KStringViewZ sError, KOutStream& out) //--------------------------------------------------------------------------- { if (m_bThrow) { throw KException(sError); } else { out.WriteLine(sError); } return 1; } // SetError //--------------------------------------------------------------------------- KString KOptions::BadBoundsReason(ArgTypes Type, KStringView sParm, int64_t iMinBound, int64_t iMaxBound) const //--------------------------------------------------------------------------- { switch (Type) { case Integer: case Float: return kFormat("{} is not in limits [{}..{}]", sParm, iMinBound, iMaxBound); case Unsigned: return kFormat("{} is not in limits [{}..{}]", sParm, static_cast<uint64_t>(iMinBound), static_cast<uint64_t>(iMaxBound)); case String: case File: case Path: case Directory: case Email: case URL: return kFormat("length of {} not in limits [{}..{}]", sParm.size(), iMinBound, iMaxBound); default: break; } return {}; } // BadBoundsReason //--------------------------------------------------------------------------- bool KOptions::ValidBounds(ArgTypes Type, KStringView sParm, int64_t iMinBound, int64_t iMaxBound) const //--------------------------------------------------------------------------- { switch (Type) { case Integer: { auto iValue = sParm.Int64(); return iValue >= iMinBound && iValue <= iMaxBound; } case Unsigned: { auto iValue = sParm.UInt64(); return iValue >= static_cast<uint64_t>(iMinBound) && iValue <= static_cast<uint64_t>(iMaxBound); } case Float: { auto iValue = sParm.Double(); return iValue >= iMinBound && iValue <= iMaxBound; } case String: case File: case Path: case Directory: case Email: case URL: { auto iValue = static_cast<int64_t>(sParm.size()); return iValue >= iMinBound && iValue <= iMaxBound; } default: break; } return true; } // ValidBounds //--------------------------------------------------------------------------- KString KOptions::BadArgReason(ArgTypes Type, KStringView sParm) const //--------------------------------------------------------------------------- { switch (Type) { case Integer: return kFormat("not an integer: {}", sParm); case Unsigned: return kFormat("not an unsigned integer: {}", sParm); case Float: return kFormat("not a float: {}", sParm); case Boolean: return kFormat("not a boolean: {}", sParm); case String: return kFormat("not a string: {}", sParm); case File: return kFormat("not an existing file: {}", sParm); case Directory: return kFormat("not an existing directory: {}", sParm); case Path: return kFormat("not an existing directory base: {}", sParm); case Email: return kFormat("not an email: {}", sParm); case URL: return kFormat("not a URL: {}", sParm); } return {}; } // BadArgReason //--------------------------------------------------------------------------- bool KOptions::ValidArgType(ArgTypes Type, KStringViewZ sParm) const //--------------------------------------------------------------------------- { switch (Type) { case Integer: return kIsInteger(sParm); case Unsigned: return kIsUnsigned(sParm); case Float: return kIsFloat(sParm) || kIsInteger(sParm); case Boolean: return true; case String: return true; case File: return kFileExists(sParm); case Directory: return kDirExists(sParm); case Path: { KString sDirname = kDirname(sParm); return kDirExists(sDirname); } case Email: return kIsEmail(sParm); case URL: return kIsURL(sParm); } return true; } // ValidArgType //--------------------------------------------------------------------------- KStringViewZ KOptions::ModifyArgument(KStringViewZ sArg, const CallbackParam* Callback) //--------------------------------------------------------------------------- { if (Callback->ToLower()) { m_ParmBuffer.push_front(sArg.ToLower()); } else if (Callback->ToUpper()) { m_ParmBuffer.push_front(sArg.ToUpper()); } else { return sArg; } return m_ParmBuffer.front().ToView(); } // ModifyArgument //--------------------------------------------------------------------------- int KOptions::Execute(CLIParms Parms, KOutStream& out) //--------------------------------------------------------------------------- { KOutStreamRAII KO(&m_CurrentOutputStream, out); if (m_sProgramPathName.empty()) { m_sProgramPathName = Parms.GetProgramPath(); } CLIParms::iterator lastCommand; DEKAF2_TRY { if (!Parms.empty()) { // using explicit iterators so that options can move the loop forward more than one step for (auto it = Parms.begin() + 1; it != Parms.end(); ++it) { lastCommand = it; ArgList Args; bool bIsUnknown { false }; m_sCurrentArg = it->sArg; auto Callback = FindParam(it->sArg, it->IsOption()); if (DEKAF2_UNLIKELY(Callback == nullptr)) { // check if we have a handler for an unknown arg Callback = FindParam("!", it->IsOption()); if (Callback) { // we pass the current Arg as the first arg of Args, // but we need to take care to not take it into account // when we readjust the remaining args after calling the Args.push_front(it->sArg); bIsUnknown = true; } } if (Callback) { it->bConsumed = true; auto iMaxArgs = Callback->m_iMaxArgs; // isolate parms until next command and add them to the ArgList for (auto it2 = it + 1; iMaxArgs-- > 0 && it2 != Parms.end() && !it2->IsOption(); ++it2) { Args.push_front(ModifyArgument(it2->sArg, Callback)); if (Args.size() <= Callback->m_iMinArgs) { // check minimum arguments for compliance with the requested type if (!ValidArgType(Callback->m_ArgType, Args.front())) { DEKAF2_THROW(WrongParameterError(BadArgReason(Callback->m_ArgType, Args.front()))); } else if (Callback->CheckBounds() && !ValidBounds(Callback->m_ArgType, Args.front(), Callback->m_iLowerBound, Callback->m_iUpperBound)) { DEKAF2_THROW(WrongParameterError(BadBoundsReason(Callback->m_ArgType, Args.front(), Callback->m_iLowerBound, Callback->m_iUpperBound))); } } } if (Callback->m_iMinArgs > Args.size()) { if (!Callback->m_sMissingArgs.empty()) { DEKAF2_THROW(MissingParameterError(Callback->m_sMissingArgs)); } DEKAF2_THROW(MissingParameterError(kFormat("{} arguments required, but only {} found", Callback->m_iMinArgs, Args.size()))); } // keep record of the initial args count auto iOldSize = Args.size(); // finally call the callback Callback->m_Callback(Args); if (iOldSize < Args.size()) { DEKAF2_THROW(WrongParameterError("callback manipulated parameter count")); } if (bIsUnknown) { // adjust arg count --iOldSize; } // advance arg iter by count of consumed args while (iOldSize-- > Args.size()) { (++it)->bConsumed = true; } } } } return Evaluate(Parms, out); } DEKAF2_CATCH (const MissingParameterError& error) { return SetError(kFormat("{}: missing parameter after {}{}: {}", GetProgramName(), lastCommand->Dashes(), lastCommand->sArg, error.what())); } DEKAF2_CATCH (const WrongParameterError& error) { return SetError(kFormat("{}: wrong parameter after {}{}: {}", GetProgramName(), lastCommand->Dashes(), lastCommand->sArg, error.what())); } DEKAF2_CATCH (const BadOptionError& error) { return SetError(kFormat("{}: {}{}: {}", GetProgramName(), lastCommand->Dashes(), lastCommand->sArg, error.what())); } DEKAF2_CATCH (const Error& error) { return SetError(error.what()); } DEKAF2_CATCH (const NoError& error) { #ifdef _MSC_VER error.what(); #endif } return 1; } // Execute //--------------------------------------------------------------------------- int KOptions::Evaluate(const CLIParms& Parms, KOutStream& out) //--------------------------------------------------------------------------- { if (Parms.size() < 2) { if (m_bEmptyParmsIsError) { Help(out); return -1; } } bool bError { false }; size_t iUnconsumed {0}; for (const auto& it : Parms) { if (!it.bConsumed) { ++iUnconsumed; } } if (iUnconsumed) { out.FormatLine("have {} excess argument{}:", iUnconsumed, iUnconsumed == 1 ? "" : "s"); for (const auto& it : Parms) { if (!it.bConsumed) { out.Write(it.Dashes()); out.WriteLine(it.sArg); } } bError = true; } // now check for required options for (auto& Callback : m_Callbacks) { if (Callback.IsRequired() && !Callback.m_bUsed) { bError = true; out.FormatLine("missing required argument: {}{}", Callback.IsCommand() ? "" : "-", Callback.m_sNames); } else { // reset flag Callback.m_bUsed = false; } } return bError; // 0 or 1 } // Evaluate //--------------------------------------------------------------------------- KStringViewZ KOptions::GetProgramPath() const //--------------------------------------------------------------------------- { return m_sProgramPathName; } // GetProgramPath //--------------------------------------------------------------------------- KStringView KOptions::GetProgramName() const //--------------------------------------------------------------------------- { return kBasename(GetProgramPath()); } // GetProgramName #ifdef DEKAF2_REPEAT_CONSTEXPR_VARIABLE constexpr KStringViewZ KOptions::CLIParms::Arg_t::s_sDoubleDash; #endif } // end of namespace dekaf2
27.425306
144
0.491487
[ "vector" ]
47edfc2a7d64a2e9402ba6608f49f09a06aa4b64
286
hpp
C++
include/mpi/core/structs/sub_array_information.hpp
acdemiralp/mpi
c3d445404ed129f1f0dee61fa7b36033a11801d5
[ "MIT" ]
9
2021-11-09T06:07:00.000Z
2022-02-06T12:03:56.000Z
include/mpi/core/structs/sub_array_information.hpp
acdemiralp/mpi
c3d445404ed129f1f0dee61fa7b36033a11801d5
[ "MIT" ]
3
2021-10-19T00:04:53.000Z
2021-11-10T07:26:34.000Z
include/mpi/core/structs/sub_array_information.hpp
acdemiralp/mpi
c3d445404ed129f1f0dee61fa7b36033a11801d5
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <vector> namespace mpi { struct sub_array_information { std::vector<std::int32_t> sizes ; std::vector<std::int32_t> sub_sizes ; std::vector<std::int32_t> starts ; bool fortran_order = false; }; }
19.066667
50
0.611888
[ "vector" ]
47ee72b294bb1e0df44fe061a063d8b7d75d81cd
1,490
cpp
C++
cpp/atcoder/NTL_1_A.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
cpp/atcoder/NTL_1_A.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
cpp/atcoder/NTL_1_A.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <map> #include <algorithm> #include <queue> #include <iomanip> // clang-format off #define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } #define SZ(x) ((int)(x).size()) using ll = long long; // 2^60 const ll INF = 1LL << 60; // lower_bound(ALL(a), 4) #define ALL(a) (a).begin(),(a).end() int gcd(int a,int b){return b?gcd(b,a%b):a;} int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; using namespace std; // clang-format on // 素因数分解 vector<pair<long long, long long>> prime_factorize(long long N) { vector<pair<long long, long long>> res; for (long long a = 2; a * a <= N; ++a) { if (N % a != 0) continue; long long ex = 0; while (N % a == 0) { ++ex; N /= a; } res.push_back({a, ex}); } // 素数 if (N != 1) res.push_back({N, 1}); return res; } int main() { cout << fixed << setprecision(16); int n; cin >> n; auto vp = prime_factorize(n); cout << n << ":"; for (auto p : vp) { cout << " "; int cnt = p.second; rep(i, cnt) { if (i != 0) { cout << " "; } cout << p.first; } } cout << endl; }
21.594203
87
0.477852
[ "vector" ]
47f0a099e182a5f89647e5fa19a9f1d8978ed85a
1,363
cpp
C++
src/Common/FS.cpp
feral-lang/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "MIT" ]
131
2020-03-19T15:22:37.000Z
2021-12-19T02:37:01.000Z
src/Common/FS.cpp
Electrux/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "BSD-3-Clause" ]
14
2020-04-06T05:50:15.000Z
2021-06-26T06:19:04.000Z
src/Common/FS.cpp
Electrux/feral
1ce8eb72eec7c8a5ac19d3767e907b86387e29e0
[ "BSD-3-Clause" ]
20
2020-04-06T07:28:30.000Z
2021-09-05T14:46:25.000Z
/* MIT License Copyright (c) 2020 Feral Language repositories 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. */ #include "Common/FS.hpp" #include <cstdio> #include <cstdlib> #include <string> #include <unistd.h> #include <vector> #include "Common/Env.hpp" namespace fs { bool exists(const std::string &loc) { return access(loc.c_str(), F_OK) != -1; } std::string abs_path(const std::string &loc, std::string *dir, const bool &dir_add_double_dot) { static char abs[MAX_PATH_CHARS]; static char abs_tmp[MAX_PATH_CHARS]; realpath(loc.c_str(), abs); if(dir != nullptr) { std::string _abs = abs; *dir = _abs.substr(0, _abs.find_last_of('/')); if(dir_add_double_dot) { *dir += "/.."; realpath(dir->c_str(), abs_tmp); *dir = abs_tmp; } } return abs; } std::string cwd() { static char cwd[MAX_PATH_CHARS]; if(getcwd(cwd, sizeof(cwd)) != NULL) { return cwd; } return ""; } std::string home() { static std::string _home = env::get("HOME"); return _home; } } // namespace fs
21.983871
94
0.696258
[ "vector" ]
47f14204517bae22ffaf5129501955216d63d92f
1,256
cpp
C++
0289-Game of Life/0289-Game of Life.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0201-0300/0289-Game of Life/0289-Game of Life.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0201-0300/0289-Game of Life/0289-Game of Life.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(); if (m == 0) { return; } int n = board[0].size(); vector<int> deltaX = {-1, -1, -1, 0, 0, 1, 1, 1}; vector<int> deltaY = {-1, 0, 1, -1, 1, -1, 0, 1}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int count = 0; for (int k = 0; k < deltaX.size(); ++k) { int ni = i + deltaX[k]; int nj = j + deltaY[k]; if (ni >= 0 && ni < m && nj >= 0 && nj < n) { if (board[ni][nj] & 1) { ++count; } } } if (board[i][j] & 1) { if (count == 2 || count == 3) { board[i][j] |= 2; } } else if (count == 3) { board[i][j] |= 2; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { board[i][j] >>= 1; } } } };
29.209302
65
0.259554
[ "vector" ]
47f161ca00c82e56cb00b1f4710928cd43501230
9,968
cpp
C++
wfs/stored_queries/GetDataSetByIdHandler.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
null
null
null
wfs/stored_queries/GetDataSetByIdHandler.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2018-04-17T10:02:46.000Z
2019-10-21T08:57:55.000Z
wfs/stored_queries/GetDataSetByIdHandler.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2017-05-10T12:03:51.000Z
2021-07-06T07:05:25.000Z
#include "stored_queries/GetDataSetByIdHandler.h" #include "StoredQueryHandlerBase.h" #include "StoredQueryHandlerFactoryDef.h" #include "StoredQueryMap.h" #include "WfsConvenience.h" #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <macgyver/StringConversion.h> #include <macgyver/TypeName.h> #include <smartmet/macgyver/Exception.h> #include <smartmet/spine/Value.h> #include <sstream> #include <stdexcept> namespace ba = boost::algorithm; namespace bw = SmartMet::Plugin::WFS; namespace { const char* P_DATA_SET_ID = "datasetid"; } bw::GetDataSetByIdHandler::GetDataSetByIdHandler(SmartMet::Spine::Reactor* reactor, bw::StoredQueryConfig::Ptr config, PluginImpl& plugin_data) : bw::StoredQueryParamRegistry(config), bw::SupportsExtraHandlerParams(config), bw::StoredQueryHandlerBase(reactor, config, plugin_data, boost::optional<std::string>()) { try { register_scalar_param<std::string>(P_DATA_SET_ID); auto& ds_list = config->get_mandatory_config_param<libconfig::Setting&>("datasetids"); config->assert_is_list(ds_list); const int N = ds_list.getLength(); for (int i = 0; i < N; i++) { libconfig::Setting& item = ds_list[i]; config->assert_is_group(item); const std::string ds_id = config->get_mandatory_config_param<std::string>(item, "data_set"); const std::string sq_id = config->get_mandatory_config_param<std::string>(item, "stored_query"); const std::string ns = config->get_optional_config_param<std::string>(item, "namespace", "FI"); if (not data_set_map.insert(std::make_pair(ds_id, sq_id)).second) { throw Fmi::Exception(BCP, "Duplicate data set ID '" + ds_id + "'!"); } plugin_data.get_capabilities().register_data_set(ds_id, ns); } } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } bw::GetDataSetByIdHandler::~GetDataSetByIdHandler() {} void bw::GetDataSetByIdHandler::init_handler() {} void bw::GetDataSetByIdHandler::query(const StoredQuery& query, const std::string& language, const boost::optional<std::string>& hostname, std::ostream& output) const { try { (void)query; (void)language; (void)output; Fmi::Exception exception(BCP, "Operation processing failed!"); exception.addDetail("The method not expected to be called (should have been redirected)."); exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED); throw exception; } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } bool bw::GetDataSetByIdHandler::redirect(const StoredQuery& query, std::string& new_stored_query_id) const { try { const std::string data_set_id = query.get_param_map().get_single<std::string>(P_DATA_SET_ID); auto it2 = data_set_map.find(Fmi::ascii_tolower_copy(data_set_id)); if (it2 == data_set_map.end()) { bool start = true; std::ostringstream msg; msg << "Available data set IDs are "; BOOST_FOREACH (const auto& x, data_set_map) { if (not start) msg << ", "; msg << "'" << x.first << "'"; start = false; } Fmi::Exception exception(BCP, "Data set ID '" + data_set_id + "' not found!"); exception.addDetail(msg.str()); exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED); throw exception.disableStackTrace(); } else { new_stored_query_id = it2->second; return true; } } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } std::vector<std::string> bw::GetDataSetByIdHandler::get_return_types() const { try { // FIXME: update this return get_stored_query_map().get_return_type_names(); } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } namespace { boost::shared_ptr<bw::StoredQueryHandlerBase> wfs_get_data_set_by_id_handler_create( SmartMet::Spine::Reactor* reactor, bw::StoredQueryConfig::Ptr config, bw::PluginImpl& plugin_data, boost::optional<std::string> /* unused template_file_name */) { try { bw::StoredQueryHandlerBase* qh = new bw::GetDataSetByIdHandler(reactor, config, plugin_data); boost::shared_ptr<bw::StoredQueryHandlerBase> result(qh); return result; } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } } // namespace bw::StoredQueryHandlerFactoryDef wfs_get_data_set_by_id_handler_factory( &wfs_get_data_set_by_id_handler_create); /** @page WFS_SQ_DATA_SET_BY_ID Stored query handler for getting predefined data sets @section WFS_SQ_DATA_SET_BY_ID_INTRO Introduction This stored query handler provides access to predefined data sets. The access to predefined data sets is implemented by redirecting request to another stored query specified in configuration. One may use stored query configuration entry @b hidden to hide these stored queries which implements access to data sets <table border="1"> <tr> <td>Implementation</td> <td>SmartMet::Plugin::WFS::GetDataSetByIdHandler</td> </tr> <tr> <td>constructor name (for stored query configuration)</td> <td>@b wfs_get_data_set_by_id_handler_factory</td> </table> @section WFS_SQ_DATA_SET_BY_ID_PARAM Stored query handler built-in parameters <table border="1"> <tr> <th>Entry name</th> <th>Type</th> <th>Data type</th> <th>Description</th> </tr> <tr> <td>datasetid</td> <td>@ref WFS_CFG_SCALAR_PARAM_TMPL "cfgScalarParameterTemplate"</td> <td>string</td> <td>Specifies predefined data set to return</td> </tr> </table> @section WFS_SQ_DATA_SET_BY_ID_EXTRA_CFG Additional Stored Query configuration entries <table border="1"> <tr> <th>Entry name</th> <th>Type</th> <th>Use</th> <th>Description</th> </tr> <tr> <td>datasetids</td> <td>list of @ref WFS_SQ_DATA_SET_DEF "cfgDataSetDef"</td> <td>mandatory</td> <td>Lists available data sets</td> </tr> </table> Additional data types - @subpage WFS_SQ_DATA_SET_DEF "cfgDataSetDef" @section WFS_SQ_DATA_SET_BY_ID_EXAMPLE Example @verbatim disabled = false; demo = false; id = "GetDataSetById"; constructor_name = "wfs_get_data_set_by_id_handler_factory"; title: { eng = "GetDataSetById"; fin = "GetDataSetById"; }; abstract: { eng = "GetDataSetById returns INSPIRE data sets. Consult catalog.fmi.fi to investigate possible data sets."; fin = "GetDataSetById palauttaa INSPIRE-datasettejä. Mahdolliset datasetit löydät catalog.fmi.fi-palvelusta."; }; parameters: ( { name = "datasetid"; abstract: { eng = "Specifies ID of data set to return"; fin = "Määritää haettavan datasetin id:n."; }; title: { eng = "Data set ID"; fin = "Data setin ID"; }; xmlType = "xsi:string"; type = "string"; } ); returnTypeNames = []; datasetids: ( # Aallokkohavainnot { data_set = "1000549"; stored_query = "fmi::observations::wave::timevaluepair"; namespace = "FI"; }, # Asemakohtaiset ilmastolliset vertailuarvot 30-vuotisjaksoilla 1971-2000 sekä 1981-2010 # { data_set = "1000550"; stored_query = ""; namespace = "FI"; }, # Ilmastonmuutosennusteet { data_set = "1000551"; stored_query = "fmi::forecast::climatology::scenario::grid"; namespace = "FI"; }, # Interpoloidut lämpötilan ja sateen kuukausiarvot { data_set = "1000552"; stored_query = "fmi::observations::weather::monthly::timevaluepair"; namespace = "FI"; }, # Ilmatieteen laitoksen pintasäähavaintoasemien kuukausiarvot { data_set = "1000554"; stored_query = "fmi::datasets::observations::weather::monthly::timevaluepair"; namespace = "FI"; }, # Ilmatieteen laitoksen meriveden korkeusennuste { data_set = "1000555"; stored_query = "fmi::forecast::oaas::sealevel::point::timevaluepair"; namespace = "FI"; }, # Ilmatieteen laitoksen meriveden korkeushavainnot { data_set = "1000556"; stored_query = "fmi::observations::mareograph::timevaluepair"; namespace = "FI"; }, # Ilmatieteen laitoksen pintasäähavainnot { data_set = "1000557"; stored_query = "fmi::datasets::observations::weather::timevaluepair"; namespace = "FI"; }, # Ilmatieteen laitoksen säämalli RCR Hirlam { data_set = "1000558"; stored_query = "fmi::forecast::hirlam::surface::grid"; namespace = "FI"; }, # Ilmatieteen laitoksen säätutkahavainnot { data_set = "1000559"; stored_query = "fmi::radar"; namespace = "FI"; }, # Salamahavainnot { data_set = "1000560"; stored_query = "fmi::observations::lightning::multipointcoverage"; namespace = "FI"; }, # Ilmatieteen laitoksen auringon säteilyhavainnot { data_set = "1000561"; stored_query = "fmi::observations::radiation::timevaluepair"; namespace = "FI"; }, # Taustailmanlaatuhavainnot # { data_set = "1000562"; stored_query = ""; namespace = "FI"; }, # Ilmatieteen laitoksen vuorokausiarvot { data_set = "1000565"; stored_query = "fmi::datasets::observations::weather::daily::timevaluepair"; namespace = "FI"; } ); handler_params: { datasetid = "${datasetid}"; }; @endverbatim */ /** @page WFS_SQ_DATA_SET_DEF Definition of predefined data set Only used by @ref WFS_SQ_DATA_SET_BY_ID <table border="1"> <tr> <th>Entry name</th> <th>Type</th> <th>Use</th> <th>Description</th> </tr> <tr> <td>@b data_set</td> <td>string</td> <td>mandatory</td> <td>Specifies data set ID</td> </tr> <tr> <td>@b stored_query</td> <td>string</td> <td>mandatory</td> <td>Specifies stored query ID to use for getting data set</td> </tr> <tr> <td>namespace</td> <td>string</td> <td>optional (default @b FI)</td> <td>Namespace value to use for @b GetCapabilities response)</td> </tr> </table> */
27.234973
100
0.67827
[ "vector" ]
47fc3ce826fc988ecbcd868c96d710e53cd064b9
1,984
cpp
C++
RUEngine/Engine/Texture.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
4
2017-11-10T07:57:36.000Z
2021-04-04T15:34:23.000Z
RUEngine/Engine/Texture.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
null
null
null
RUEngine/Engine/Texture.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
null
null
null
#include "Texture.h" GLuint tex::loadTexture(const char* path) { //Make a texture GLuint textureID; int textureWidth, textureHeight; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); //GL_REPEAT for multiplication in fragment shader glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //Load SOIL image unsigned char* image = SOIL_load_image(path, &textureWidth, &textureHeight, 0, SOIL_LOAD_RGBA); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); //Enable alpha //Make a mipmap glGenerateMipmap(GL_TEXTURE_2D); //Delete image since it's already made and stored in textureID SOIL_free_image_data(image); //Bind default texture glBindTexture(GL_TEXTURE_2D, 0); return textureID; } GLuint tex::loadCubemap(std::vector<const char*> faces) { //Load a cubemap GLuint textureID; int textureWidth, textureHeight; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); for (GLuint i = 0; i < faces.size(); i++) { unsigned char* image = SOIL_load_image(faces[i], &textureWidth, &textureHeight, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, textureWidth, textureHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); SOIL_free_image_data(image); } glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return textureID; }
31.492063
127
0.78377
[ "vector" ]
47fec840d80fa1a6a8c77962ef5426663f17066e
785
cpp
C++
src/Triangle.cpp
benpigchu/CG-RayTracing
4e5f2bea6e3f537ac0ef109d5b503595c2898516
[ "Unlicense" ]
1
2019-04-26T17:44:13.000Z
2019-04-26T17:44:13.000Z
src/Triangle.cpp
benpigchu/CG-RayTracing
4e5f2bea6e3f537ac0ef109d5b503595c2898516
[ "Unlicense" ]
null
null
null
src/Triangle.cpp
benpigchu/CG-RayTracing
4e5f2bea6e3f537ac0ef109d5b503595c2898516
[ "Unlicense" ]
null
null
null
#include "Geometry.h" #include "Vector3.h" #include "Matrix4.h" #include "Ray.h" #include "Triangle.h" IntersectInfo Triangle::testIntersect(Ray r)const noexcept{ // x+dt=au+bv+cw // a+b+c=1 // [M4x4][a,b,c,d]T=[...x,1] IntersectInfo ii; // uv not supported yet ii.u=0; ii.v=0; Vector3 t=r.getDirection(); Vector3 u=this->point[0]; Vector3 v=this->point[1]; Vector3 w=this->point[2]; Matrix4 factor(u.x,v.x,w.x,-t.x,u.y,v.y,w.y,-t.y,u.z,v.z,w.z,-t.z,1,1,1,0); double a=r.start.x,b=r.start.y,c=r.start.z,d=1; if(factor.determinant()==0){ ii.isIntersect=false; return ii; } applyTo(factor.inverse(),a,b,c,d); if(d>0&&c>0&&b>0&&a>0){ ii.isIntersect=true; ii.distance=d; ii.pos=r.start+d*t; ii.normal=this->nm; }else{ ii.isIntersect=false; } return ii; }
22.428571
76
0.638217
[ "geometry" ]
9a0516556a04f97270517b7199c1f67eaec37288
9,805
cpp
C++
game/Source/OptionsMenu.cpp
alexgesti/PROYECTO-2
c67aad3c674127147d1cf762e3636a4beceeebce
[ "MIT" ]
4
2021-03-08T20:06:56.000Z
2021-03-14T18:46:46.000Z
game/Source/OptionsMenu.cpp
alexgesti/Odd-Space
c67aad3c674127147d1cf762e3636a4beceeebce
[ "MIT" ]
1
2021-02-25T11:10:08.000Z
2021-02-25T11:10:08.000Z
game/Source/OptionsMenu.cpp
alexgesti/Odd-Space
c67aad3c674127147d1cf762e3636a4beceeebce
[ "MIT" ]
1
2021-03-03T17:04:57.000Z
2021-03-03T17:04:57.000Z
#include "OptionsMenu.h" #include "SceneManager.h" // Constructor OptionsMenu::OptionsMenu(SceneManager* sceneManager) { this->sceneManager = sceneManager; } // Destructor OptionsMenu::~OptionsMenu() { Unload(); } bool OptionsMenu::Load() { texture = sceneManager->tex->Load("sprites/ui/ui_menupause.png"); /*explosion = sceneManager->tex->Load("sprites/ui/ui_explosion.png"); explosionAnim->loop = false; explosionAnim->speed = 0.8f; explosionAnim->PushBack({ 208, 20, 158, 158 }); explosionAnim->PushBack({ 399, 20, 158, 158 }); explosionAnim->PushBack({ 591, 20, 158, 158 }); explosionAnim->PushBack({ 782, 20, 158, 158 }); explosionAnim->PushBack({ 208, 210, 158, 158 }); explosionAnim->PushBack({ 16, 210,158, 158 }); explosionAnim->PushBack({ 401, 210,158, 158 }); explosionAnim->PushBack({ 590, 210,158, 158 }); explosionAnim->PushBack({ 785, 210,158, 158 }); explosionAnim->PushBack({ 16, 410, 158, 158 }); explosionAnim->PushBack({ 204, 410,158, 158 }); explosionAnim->PushBack({ 593, 410,158, 158 }); explosionAnim->PushBack({ 783, 410,158, 158 }); explosionAnim->PushBack({ 21, 608,158, 158 }); explosionAnim->PushBack({ 400, 608, 158, 158 }); explosionAnim->PushBack({ 784, 608,158, 158 }); explosionAnim->PushBack({ 16, 802,158, 158 }); explosionAnim->PushBack({ 209, 802,158, 158 }); explosionAnim->PushBack({ 592, 802,158, 158 }); explosionAnim->PushBack({ 783, 802, 158, 158 });*/ fullScreen = new GuiCheckBox(1, { 400, 200, 32, 32 }, "Fullscreen", sceneManager->audio); fullScreen->SetObserver(this); VSync = new GuiCheckBox(2, { 400, 300, 32, 32 }, "VSync", sceneManager->audio); VSync->SetObserver(this); music = new GuiSlider(3, { 400, 400, 500, 16 }, "Music", sceneManager->audio); music->SetObserver(this); fx = new GuiSlider(4, { 400, 500, 500, 16 }, "Fx", sceneManager->audio); fx->SetObserver(this); stepedAnimation = new StepedAnimation(); stepedAnimation->speed = 80.0f; if(sceneManager->currentscenetype == SceneType::TITLE) { stepedAnimation->Pushback(354, 1166, 120, 120, 1200 - 334, 5); stepedAnimation->Pushback(1161, 1161, 120, 650, 5, 572); stepedAnimation->Pushback(1166, 354, 650, 650, 1103 - 253, 5); stepedAnimation->Pushback(354, 354, 650, 120, 5, 622 - 476); } else { stepedAnimation->Pushback(83, 339, 382, 382, 1083, 5); stepedAnimation->Pushback(334, 334, 382, 100, 5, 282); stepedAnimation->Pushback(334, 1177, 100, 100, 1177 - 334, 5); stepedAnimation->Pushback(1177, 1177, 100, 665, 5, 572); stepedAnimation->Pushback(1182, 334, 665, 665, 1103 - 253, 5); stepedAnimation->Pushback(334, 334, 668, 476, 5, 622 - 476); stepedAnimation->Pushback(334, 83, 476, 476, 233, 5); stepedAnimation->Pushback(83, 83, 476, 382, 5, 94); } c = 0; return true; } bool OptionsMenu::Update(float dt) { GamePad& pad = sceneManager->input->pads[0]; if (sceneManager->input->GetKey(SDL_SCANCODE_DOWN) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_DOWN) == KEY_DOWN) c++; if (sceneManager->input->GetKey(SDL_SCANCODE_UP) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_UP) == KEY_DOWN) c--; //Establecer limites fila/columna botones if (sceneManager->currentscenetype != SceneType::TITLE) { if (c > 4) c = 0; if (c < 0) c = 4; } else { if (c > 3) c = 0; if (c < 0) c = 3; } fullScreen->Update(sceneManager->input, &sceneManager->fullscreenCheck, buttonOption[c], dt); VSync->Update(sceneManager->input, &sceneManager->capped, buttonOption[c], dt); music->Update(sceneManager->input, buttonOption[c], dt); fx->Update(sceneManager->input, buttonOption[c], dt); /*if (VSync->explode) { VSync->explode = false; playingExplosionVsync = true; explosionAnim->Reset(); } if (fullScreen->explode) { VSync->explode = false; playingExplosionfullScreen = true; explosionAnim->Reset(); }*/ return true; } bool OptionsMenu::Draw() { sceneManager->render->DrawText(sceneManager->font, "Fullscreen", 375, 160, 25, 0, { 255, 255, 255, 255 }); fullScreen->Draw(sceneManager->render, texture); sceneManager->render->DrawText(sceneManager->font, "VSync", 375, 260, 25, 0, { 255, 255, 255, 255 }); VSync->Draw(sceneManager->render, texture); sceneManager->render->DrawText(sceneManager->font, "Music", 375, 360, 25, 0, { 255, 255, 255, 255 }); music->Draw(sceneManager->render, sceneManager->volumeMusic, texture); sceneManager->render->DrawText(sceneManager->font, "Fx", 375, 460, 25, 0, { 255, 255, 255, 255 }); fx->Draw(sceneManager->render, sceneManager->volumeFx, texture); int amountDisapeared = 0; for (int i = 0; i < stepedAnimation->currentStep; i++) { SDL_Rect temp = stepedAnimation->GetStep(i); sceneManager->render->DrawRectangle(temp, 255, 255, 255, stepedAnimation->steps[i].alpha, true, false); if (stepedAnimation->steps[i].disapear) stepedAnimation->steps[i].alpha -= 3; if (stepedAnimation->steps[i].alpha <= 0) { stepedAnimation->steps[i].alpha = 0; stepedAnimation->steps[i].disapear = false; } if (!stepedAnimation->steps[i].disapear) amountDisapeared++; } if (!stepedAnimation->animationCompleted) { SDL_Rect temp = stepedAnimation->Update(); sceneManager->render->DrawRectangle(temp, 255, 255, 255, 255, true, false); } else if(amountDisapeared >= stepedAnimation->stepAmount) { stepedAnimation->Reset(); if (sceneManager->currentscenetype == SceneType::TITLE) { stepedAnimation->Pushback(354, 1166, 120, 120, 1200 - 334, 5); stepedAnimation->Pushback(1161, 1161, 120, 650, 5, 572); stepedAnimation->Pushback(1166, 354, 650, 650, 1103 - 253, 5); stepedAnimation->Pushback(354, 354, 650, 120, 5, 622 - 476); } else { stepedAnimation->Pushback(83, 339, 382, 382, 1083, 5); stepedAnimation->Pushback(334, 334, 382, 100, 5, 282); stepedAnimation->Pushback(334, 1177, 100, 100, 1177 - 334, 5); stepedAnimation->Pushback(1177, 1177, 100, 665, 5, 572); stepedAnimation->Pushback(1182, 334, 665, 665, 1103 - 253, 5); stepedAnimation->Pushback(334, 334, 668, 476, 5, 622 - 476); stepedAnimation->Pushback(334, 83, 476, 476, 233, 5); stepedAnimation->Pushback(83, 83, 476, 382, 5, 94); } } /*if (music->state == GuiControlState::PRESSED) { SDL_Rect rect = { 375, 160, 200, 300 }; SDL_Color color1 = { 255, 0, 0, 255 }; SDL_Color color2 = { 0, 255, 0, 255 }; sceneManager->render->DrawDegradedRectVertical(rect, color1, color2); }*/ /*if (playingExplosionVsync) { explosionAnim->Update(); SDL_Rect rec = explosionAnim->GetCurrentFrame(); sceneManager->render->DrawTexture(explosion, VSync->bounds.x - 125 / 2, VSync->bounds.y - 125 / 2, &rec); if (explosionAnim->HasFinished()) playingExplosionVsync = false; } if (playingExplosionfullScreen) { explosionAnim->Update(); SDL_Rect rec = explosionAnim->GetCurrentFrame(); sceneManager->render->DrawTexture(explosion, fullScreen->bounds.x - 125 / 2, fullScreen->bounds.y - 125 / 2, &rec); if (explosionAnim->HasFinished()) playingExplosionfullScreen = false; }*/ return true; } bool OptionsMenu::Unload() { //sceneManager->tex->UnLoad(explosion); sceneManager->tex->UnLoad(texture); sceneManager->openOptions = false; fullScreen->UnLoad(); RELEASE(fullScreen); VSync->UnLoad(); RELEASE(VSync); music->UnLoad(); RELEASE(music); fx->UnLoad(); RELEASE(fx); RELEASE(stepedAnimation); return true; } //---------------------------------------------------------- // Manage GUI events for this screen //---------------------------------------------------------- bool OptionsMenu::OnGuiMouseClickEvent(GuiControl* control) { GamePad& pad = sceneManager->input->pads[0]; switch (control->id) { case 1: sceneManager->win->ToggleFullscreen(sceneManager->win->window); if (showCursor) { SDL_ShowCursor(0); showCursor = false; } else if (!showCursor) { SDL_ShowCursor(1); showCursor = true; } break; case 3: if (sceneManager->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_LEFT) == KEY_DOWN) if (sceneManager->volumeMusic > 0) sceneManager->volumeMusic -= 32; if (sceneManager->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_RIGHT) == KEY_DOWN) if (sceneManager->volumeMusic < 128) sceneManager->volumeMusic += 32; Mix_VolumeMusic(sceneManager->volumeMusic); break; case 4: if (sceneManager->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_LEFT) == KEY_DOWN) if (sceneManager->volumeFx > 0) sceneManager->volumeFx -= 32; if (sceneManager->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN || pad.GetPadKey(SDL_CONTROLLER_BUTTON_DPAD_RIGHT) == KEY_DOWN) if (sceneManager->volumeFx < 128) sceneManager->volumeFx += 32; Mix_Volume(-1, sceneManager->volumeFx); break; default: break; } return true; }
35.143369
135
0.615706
[ "render" ]
9a08502499b874a77b6df8ced316c132f5f1aab4
10,473
hpp
C++
include/GlobalNamespace/GameLiftConnectionManager_-GameLiftConnectToServer-d__81.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/GameLiftConnectionManager_-GameLiftConnectToServer-d__81.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/GameLiftConnectionManager_-GameLiftConnectToServer-d__81.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: GameLiftConnectionManager #include "GlobalNamespace/GameLiftConnectionManager.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Runtime.CompilerServices.IAsyncStateMachine #include "System/Runtime/CompilerServices/IAsyncStateMachine.hpp" // Including type: System.Runtime.CompilerServices.AsyncVoidMethodBuilder #include "System/Runtime/CompilerServices/AsyncVoidMethodBuilder.hpp" // Including type: System.Threading.CancellationToken #include "System/Threading/CancellationToken.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter`1 #include "System/Runtime/CompilerServices/TaskAwaiter_1.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter #include "System/Runtime/CompilerServices/TaskAwaiter.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: BGNet::Core::GameLift namespace BGNet::Core::GameLift { // Forward declaring type: PlayerSessionInfo class PlayerSessionInfo; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IAuthenticationTokenProvider class IAuthenticationTokenProvider; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81, "", "GameLiftConnectionManager/<GameLiftConnectToServer>d__81"); // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: GameLiftConnectionManager/<GameLiftConnectToServer>d__81 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF struct GameLiftConnectionManager::$GameLiftConnectToServer$d__81/*, public ::System::ValueType, public ::System::Runtime::CompilerServices::IAsyncStateMachine*/ { public: public: // public System.Int32 <>1__state // Size: 0x4 // Offset: 0x0 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // public System.Runtime.CompilerServices.AsyncVoidMethodBuilder <>t__builder // Size: 0x20 // Offset: 0x8 ::System::Runtime::CompilerServices::AsyncVoidMethodBuilder $$t__builder; // Field size check static_assert(sizeof(::System::Runtime::CompilerServices::AsyncVoidMethodBuilder) == 0x20); // public GameLiftConnectionManager <>4__this // Size: 0x8 // Offset: 0x28 ::GlobalNamespace::GameLiftConnectionManager* $$4__this; // Field size check static_assert(sizeof(::GlobalNamespace::GameLiftConnectionManager*) == 0x8); // public System.String secret // Size: 0x8 // Offset: 0x30 ::StringW secret; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String code // Size: 0x8 // Offset: 0x38 ::StringW code; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.Threading.CancellationToken cancellationToken // Size: 0x8 // Offset: 0x40 ::System::Threading::CancellationToken cancellationToken; // Field size check static_assert(sizeof(::System::Threading::CancellationToken) == 0x8); // private BGNet.Core.GameLift.PlayerSessionInfo <playerSessionInfo>5__2 // Size: 0x8 // Offset: 0x48 ::BGNet::Core::GameLift::PlayerSessionInfo* $playerSessionInfo$5__2; // Field size check static_assert(sizeof(::BGNet::Core::GameLift::PlayerSessionInfo*) == 0x8); // private IAuthenticationTokenProvider <authenticationTokenProvider>5__3 // Size: 0x8 // Offset: 0x50 ::GlobalNamespace::IAuthenticationTokenProvider* $authenticationTokenProvider$5__3; // Field size check static_assert(sizeof(::GlobalNamespace::IAuthenticationTokenProvider*) == 0x8); // private System.Runtime.CompilerServices.TaskAwaiter`1<IAuthenticationTokenProvider> <>u__1 // Size: 0xFFFFFFFF // Offset: 0x58 ::System::Runtime::CompilerServices::TaskAwaiter_1<::GlobalNamespace::IAuthenticationTokenProvider*> $$u__1; // private System.Runtime.CompilerServices.TaskAwaiter`1<BGNet.Core.GameLift.PlayerSessionInfo> <>u__2 // Size: 0xFFFFFFFF // Offset: 0x60 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BGNet::Core::GameLift::PlayerSessionInfo*> $$u__2; // private System.Runtime.CompilerServices.TaskAwaiter <>u__3 // Size: 0x8 // Offset: 0x68 ::System::Runtime::CompilerServices::TaskAwaiter $$u__3; // Field size check static_assert(sizeof(::System::Runtime::CompilerServices::TaskAwaiter) == 0x8); public: // Creating value type constructor for type: $GameLiftConnectToServer$d__81 constexpr $GameLiftConnectToServer$d__81(int $$1__state_ = {}, ::System::Runtime::CompilerServices::AsyncVoidMethodBuilder $$t__builder_ = {}, ::GlobalNamespace::GameLiftConnectionManager* $$4__this_ = {}, ::StringW secret_ = {}, ::StringW code_ = {}, ::System::Threading::CancellationToken cancellationToken_ = {}, ::BGNet::Core::GameLift::PlayerSessionInfo* $playerSessionInfo$5__2_ = {}, ::GlobalNamespace::IAuthenticationTokenProvider* $authenticationTokenProvider$5__3_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter_1<::GlobalNamespace::IAuthenticationTokenProvider*> $$u__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter_1<::BGNet::Core::GameLift::PlayerSessionInfo*> $$u__2_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter $$u__3_ = {}) noexcept : $$1__state{$$1__state_}, $$t__builder{$$t__builder_}, $$4__this{$$4__this_}, secret{secret_}, code{code_}, cancellationToken{cancellationToken_}, $playerSessionInfo$5__2{$playerSessionInfo$5__2_}, $authenticationTokenProvider$5__3{$authenticationTokenProvider$5__3_}, $$u__1{$$u__1_}, $$u__2{$$u__2_}, $$u__3{$$u__3_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating interface conversion operator: operator ::System::Runtime::CompilerServices::IAsyncStateMachine operator ::System::Runtime::CompilerServices::IAsyncStateMachine() noexcept { return *reinterpret_cast<::System::Runtime::CompilerServices::IAsyncStateMachine*>(this); } // Get instance field reference: public System.Int32 <>1__state int& dyn_$$1__state(); // Get instance field reference: public System.Runtime.CompilerServices.AsyncVoidMethodBuilder <>t__builder ::System::Runtime::CompilerServices::AsyncVoidMethodBuilder& dyn_$$t__builder(); // Get instance field reference: public GameLiftConnectionManager <>4__this ::GlobalNamespace::GameLiftConnectionManager*& dyn_$$4__this(); // Get instance field reference: public System.String secret ::StringW& dyn_secret(); // Get instance field reference: public System.String code ::StringW& dyn_code(); // Get instance field reference: public System.Threading.CancellationToken cancellationToken ::System::Threading::CancellationToken& dyn_cancellationToken(); // Get instance field reference: private BGNet.Core.GameLift.PlayerSessionInfo <playerSessionInfo>5__2 ::BGNet::Core::GameLift::PlayerSessionInfo*& dyn_$playerSessionInfo$5__2(); // Get instance field reference: private IAuthenticationTokenProvider <authenticationTokenProvider>5__3 ::GlobalNamespace::IAuthenticationTokenProvider*& dyn_$authenticationTokenProvider$5__3(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter`1<IAuthenticationTokenProvider> <>u__1 ::System::Runtime::CompilerServices::TaskAwaiter_1<::GlobalNamespace::IAuthenticationTokenProvider*>& dyn_$$u__1(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter`1<BGNet.Core.GameLift.PlayerSessionInfo> <>u__2 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BGNet::Core::GameLift::PlayerSessionInfo*>& dyn_$$u__2(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter <>u__3 ::System::Runtime::CompilerServices::TaskAwaiter& dyn_$$u__3(); // private System.Void MoveNext() // Offset: 0x1644D18 void MoveNext(); // private System.Void SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine stateMachine) // Offset: 0x16456B4 void SetStateMachine(::System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine); }; // GameLiftConnectionManager/<GameLiftConnectToServer>d__81 // WARNING Not writing size check since size may be invalid! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::*)()>(&GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::SetStateMachine // Il2CppName: SetStateMachine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::*)(::System::Runtime::CompilerServices::IAsyncStateMachine*)>(&GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81::SetStateMachine)> { static const MethodInfo* get() { static auto* stateMachine = &::il2cpp_utils::GetClassFromName("System.Runtime.CompilerServices", "IAsyncStateMachine")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::GameLiftConnectionManager::$GameLiftConnectToServer$d__81), "SetStateMachine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{stateMachine}); } };
61.970414
1,104
0.758331
[ "vector" ]
9a0fa85edff25a670320661c8cb48055162a976d
7,169
cpp
C++
projects/Physics2D/Actor.cpp
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
projects/Physics2D/Actor.cpp
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
projects/Physics2D/Actor.cpp
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
#include "Actor.h" void Actor::Update(float a_deltaTime, const glm::vec3& a_gravity) { if (nullptr != m_geometry) { // static movement Spin(m_angularVelocity * a_deltaTime); Move(m_velocity * a_deltaTime); if (m_dynamic) { // linear force glm::vec3 force = m_force + a_gravity; if (0 < m_material.linearDrag) force -= GetVelocity() * m_material.linearDrag; // linear acceleration float m = GetMass(); if (glm::vec3(0) != force && 0 != m) { glm::vec3 deltaV = (force / m) * a_deltaTime; Move(0.5f * deltaV * a_deltaTime); Accelerate(deltaV); } // angular force glm::vec3 torque = m_torque; if (0 < m_material.rotationalDrag) { torque -= GetAngularVelocity() * m_material.rotationalDrag; } // angular acceleration float i = GetRotationalInertia(torque); if (0 != i) { glm::vec3 deltaAV = torque * a_deltaTime / i; Spin(0.5f * deltaAV * a_deltaTime); AccelerateRotation(deltaAV); } EnforceMinSpeed(); } } } void Actor::ResolveCollision(Actor* a_actor1, Actor* a_actor2) { Geometry::Collision collision; if (nullptr != a_actor1 && nullptr != a_actor2 && a_actor1 != a_actor2 && (a_actor1->IsDynamic() || a_actor2->IsDynamic()) && Geometry::DetectCollision(a_actor1->GetGeometry(), a_actor2->GetGeometry(), &collision)) { // resolve interpenetration if (a_actor1->IsDynamic() && a_actor2->IsDynamic()) { a_actor1->Move(-collision.normal * collision.interpenetration * 0.5f); a_actor2->Move(collision.normal * collision.interpenetration * 0.5f); } else if (a_actor1->IsDynamic()) { a_actor1->Move(-collision.normal * collision.interpenetration); collision.point -= collision.normal * 0.5f; } else if (a_actor2->IsDynamic()) { a_actor2->Move(collision.normal * collision.interpenetration); collision.point += collision.normal * 0.5f; } // (in)elastic collision float e = 1.0f + fmin(a_actor1->m_material.elasticity, a_actor2->m_material.elasticity); glm::vec3 n = collision.normal; glm::vec3 Vr = a_actor2->GetVelocity() - a_actor1->GetVelocity(); float invM = (a_actor1->IsDynamic() ? 1.0f / a_actor1->GetMass() : 0) + (a_actor2->IsDynamic() ? 1.0f / a_actor2->GetMass() : 0); glm::vec3 r1 = collision.point - a_actor1->GetPosition(); glm::vec3 r2 = collision.point - a_actor2->GetPosition(); glm::mat3 invI1 = (a_actor1->IsDynamic() ? glm::inverse(a_actor1->GetInertiaTensor()) : glm::mat3(0)); glm::mat3 invI2 = (a_actor2->IsDynamic() ? glm::inverse(a_actor2->GetInertiaTensor()) : glm::mat3(0)); glm::vec3 J = -e * n * glm::dot(Vr, n) / (invM + glm::dot(n, glm::cross(invI1 * glm::cross(r1, n), r1)) + glm::dot(n, glm::cross(invI2 * glm::cross(r2, n), r2))); if (glm::dot(J, n) <= 0) return; if (a_actor1->IsDynamic()) a_actor1->ApplyImpulse(-J, collision.point); if (a_actor2->IsDynamic()) a_actor2->ApplyImpulse(J, collision.point); // friction glm::vec3 Vs = a_actor2->GetPointVelocity(collision.point, false) - a_actor1->GetPointVelocity(collision.point, false); Vs -= n * glm::dot(n, Vs); if (glm::vec3(0) == Vs) return; glm::vec3 t = glm::normalize(Vs); float us = (a_actor1->m_material.staticFriction + a_actor2->m_material.staticFriction) / 2; float ud = (a_actor1->m_material.dynamicFriction + a_actor2->m_material.dynamicFriction) / 2; float denominator = invM + glm::dot(t, glm::cross(invI1 * glm::cross(r1, t), r1)) + glm::dot(t, glm::cross(invI2 * glm::cross(r2, t), r2)); if (0 == denominator) return; glm::vec3 Jtan = -Vs / denominator; if (glm::length2(Jtan) > glm::length2(J * us)) Jtan = -Vs * ud * glm::length(J); if (a_actor1->IsDynamic()) a_actor1->ApplyImpulse(Jtan, collision.point); if (a_actor2->IsDynamic()) a_actor2->ApplyImpulse(-Jtan, collision.point); /* // collision force glm::vec3 v1 = collision.normal * glm::dot(collision.normal, a_actor1->GetVelocity()); glm::vec3 v2 = collision.normal * glm::dot(collision.normal, a_actor2->GetVelocity()); glm::vec3 dv = v2 - v1; //glm::vec3 surfaceDV = (a_actor2->GetPointVelocity(collision.point) - v2) - // (a_actor1->GetPointVelocity(collision.point) - v1); //surfaceDV -= collision.normal * glm::dot(collision.normal, surfaceDV); float m = (!a_actor2->IsDynamic() ? a_actor1->GetMass() : !a_actor1->IsDynamic() ? a_actor2->GetMass() : a_actor1->GetMass() * a_actor2->GetMass() / (a_actor1->GetMass() + a_actor2->GetMass())); glm::vec3 f = dv * (fmin(a_actor1->m_material.elasticity, a_actor2->m_material.elasticity) + 1) * m; if (a_actor1->IsDynamic()) a_actor1->ApplyImpulse(f, collision.point); if (a_actor2->IsDynamic()) a_actor2->ApplyImpulse(-f, collision.point); // friction force glm::vec3 surfaceDV = a_actor2->GetPointVelocity(collision.point) - a_actor1->GetPointVelocity(collision.point); surfaceDV -= collision.normal * glm::dot(collision.normal, surfaceDV); if (glm::length2(surfaceDV * m) > glm::length2(f * 0.5f * (a_actor1->m_material.staticFriction + a_actor2->m_material.staticFriction))) { glm::vec3 friction = -surfaceDV * glm::length(f) * 0.5f * (a_actor1->m_material.dynamicFriction + a_actor2->m_material.dynamicFriction); if (a_actor1->IsDynamic()) a_actor1->ApplyImpulse(friction, collision.point); if (a_actor2->IsDynamic()) a_actor2->ApplyImpulse(-friction, collision.point); }/**/ } } glm::vec3 Actor::GetPointVelocity(const glm::vec3& a_point, bool a_ignoreOutside) const { if (a_ignoreOutside && !m_geometry->Contains(a_point)) return glm::vec3(0); if (a_point == GetPosition() || glm::vec3(0) == m_angularVelocity) return m_velocity; return m_velocity + glm::cross(m_angularVelocity, a_point - GetPosition()); } static bool validImpulse(const glm::vec3& a_vec3, float a_threshold = 0.0001f) { return !(isnan(a_vec3.x) || isnan(a_vec3.y) || isnan(a_vec3.z) || glm::vec3(0) == a_vec3 || glm::length2(a_vec3) < a_threshold); } void Actor::ApplyLinearImpulse(const glm::vec3& a_impulse) { if (validImpulse(a_impulse)) { float m = GetMass(); if (0 != m) Accelerate(a_impulse / m); EnforceMinSpeed(); } } void Actor::ApplyAngularImpulse(const glm::vec3& a_angularImpulse) { if (validImpulse(a_angularImpulse)) { float i = GetRotationalInertia(a_angularImpulse); if (0 != i) AccelerateRotation(glm::inverse(GetInertiaTensor()) * a_angularImpulse); EnforceMinSpeed(); } } void Actor::ApplyImpulse(const glm::vec3& a_impulse, const glm::vec3& contactPoint) { if (validImpulse(a_impulse)) { glm::vec3 r = GetPosition() - contactPoint; glm::vec3 d = glm::normalize(r); if (glm::vec3(0) == r) { ApplyLinearImpulse(a_impulse); } else { glm::vec3 linearImpulse = d * fabs(glm::dot(a_impulse, d)); ApplyLinearImpulse(linearImpulse); ApplyAngularImpulse(glm::cross(r, a_impulse));// -linearImpulse)); } } } void Actor::EnforceMinSpeed() { if (glm::length2(m_velocity) < m_minSpeed2) m_velocity = glm::vec3(0); if (glm::length2(m_angularVelocity) < m_minAngularSpeed2) m_angularVelocity = glm::vec3(0); }
34.301435
104
0.669131
[ "geometry" ]
9a1103b8bfb2f4df39f3e8ded56c7e6690665c50
2,793
cc
C++
src/abc025/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc025/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc025/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bitset> #include <cstring> #include <iostream> #include <vector> using namespace std; const int MOD = 1000000007; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int x[5][5]; int iniPlaceI[30], iniPlaceJ[30]; static int dp[(1 << 25) + 10]; inline int toInd(int i, int j) { return i * 5 + j; } bool check(int bit, int nextNum, int i, int j) { // left-right check int li = i, lj = j - 1; int ri = i, rj = j + 1; if(lj >= 0 && rj < 5) { int leftBit = ((bit & (1 << toInd(li, lj))) != 0); int rightBit = ((bit & (1 << toInd(ri, rj))) != 0); if(leftBit + rightBit == 1) return false; } // ue-shita check int ui = i - 1, uj = j; int si = i + 1, sj = j; if(ui >= 0 && si < 5) { int ueBit = ((bit & (1 << toInd(ui, uj))) != 0); int shitaBit = ((bit & (1 << toInd(si, sj))) != 0); if(ueBit + shitaBit == 1) return false; } return true; } int solve(vector<vector<int>> x) { memset(iniPlaceI, -1, sizeof(iniPlaceI)); memset(iniPlaceJ, -1, sizeof(iniPlaceJ)); for(int i = 0; i < 5; ++i) for(int j = 0; j < 5; ++j) { if(x[i][j] != 0) { iniPlaceI[x[i][j]] = i; iniPlaceJ[x[i][j]] = j; } } memset(dp, 0, sizeof(dp)); dp[0] = 1; for(int bit = 0; bit < (1 << 25); ++bit) { if(dp[bit] == 0) continue; int nextNum = __builtin_popcount(bit) + 1; // if (dp[bit]) cout << bitset<25>(bit) << ": " << dp[bit] << endl; if(iniPlaceI[nextNum] != -1) { if(bit & (1 << toInd(iniPlaceI[nextNum], iniPlaceJ[nextNum]))) continue; if(check(bit, nextNum, iniPlaceI[nextNum], iniPlaceJ[nextNum])) { int nextBit = bit | (1 << toInd(iniPlaceI[nextNum], iniPlaceJ[nextNum])); dp[nextBit] += dp[bit]; if(dp[nextBit] >= MOD) dp[nextBit] -= MOD; } } else { for(int i = 0; i < 5; ++i) { for(int j = 0; j < 5; ++j) { if(bit & (1 << toInd(i, j))) continue; if(check(bit, nextNum, i, j)) { int nextBit = bit | (1 << toInd(i, j)); dp[nextBit] += dp[bit]; if(dp[nextBit] >= MOD) dp[nextBit] -= MOD; } } } } } return dp[(1 << 25) - 1]; } /* int main() { vector<vector<int>> x(5, vector<int>(5, 0)); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { cin >> x[i][j]; } } cout << solve(x) << endl; } */
27.382353
79
0.412818
[ "vector" ]
9a1695272f04cf64c31b4cb06e5979c008092933
26,192
cpp
C++
Source/System/Math/Algebra/Matrix33.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Math/Algebra/Matrix33.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Math/Algebra/Matrix33.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "Matrix33.hpp" #include "Quaternion.hpp" #include "../Utility/Utility.hpp" #include "Vector2.hpp" #include <ostream> #include "Matrix44.hpp" #include "../../Core/Utility/CoreUtility.hpp" #include "../Utility/VectorDef.hpp" namespace Engine5 { Matrix33::Matrix33(Real c0, Real c1, Real c2, Real c3, Real c4, Real c5, Real c6, Real c7, Real c8) { data[0] = c0; data[1] = c1; data[2] = c2; data[3] = c3; data[4] = c4; data[5] = c5; data[6] = c6; data[7] = c7; data[8] = c8; } Matrix33::Matrix33(const Matrix33& rhs) { data[0] = rhs.data[0]; data[1] = rhs.data[1]; data[2] = rhs.data[2]; data[3] = rhs.data[3]; data[4] = rhs.data[4]; data[5] = rhs.data[5]; data[6] = rhs.data[6]; data[7] = rhs.data[7]; data[8] = rhs.data[8]; } Matrix33::Matrix33(const Quaternion& quaternion) { SetRotation(quaternion); } Matrix33::Matrix33(const EulerAngle& euler_angle) { SetRotation(euler_angle); } Matrix33::Matrix33(const AxisRadian& axis_radian) { SetRotation(axis_radian); } Matrix33::Matrix33(const Vector3& axis, Real radian) { SetRotation(axis, radian); } Matrix33::Matrix33(const Matrix44& matrix) { data[0] = matrix.data[0]; data[1] = matrix.data[1]; data[2] = matrix.data[2]; data[3] = matrix.data[4]; data[4] = matrix.data[5]; data[5] = matrix.data[6]; data[6] = matrix.data[8]; data[7] = matrix.data[9]; data[8] = matrix.data[10]; } Matrix33::~Matrix33() { } void Matrix33::SetRows(const Vector3& row1, const Vector3& row2, const Vector3& row3) { data[0] = row1.x; data[1] = row1.y; data[2] = row1.z; data[3] = row2.x; data[4] = row2.y; data[5] = row2.z; data[6] = row3.x; data[7] = row3.y; data[8] = row3.z; } void Matrix33::SetColumns(const Vector3& col1, const Vector3& col2, const Vector3& col3) { data[0] = col1.x; data[1] = col2.x; data[2] = col3.x; data[3] = col1.y; data[4] = col2.y; data[5] = col3.y; data[6] = col1.z; data[7] = col2.z; data[8] = col3.z; } void Matrix33::SetDiagonal(Real a, Real b, Real c) { data[0] = a; data[4] = b; data[8] = c; } void Matrix33::SetClean() { for (size_t i = 0; i < 9; ++i) { if (Math::IsZero(data[i])) data[i] = 0.0f; } } void Matrix33::SetIdentity() { data[0] = 1.0f; data[1] = 0.0f; data[2] = 0.0f; data[3] = 0.0f; data[4] = 1.0f; data[5] = 0.0f; data[6] = 0.0f; data[7] = 0.0f; data[8] = 1.0f; } void Matrix33::SetInverse() { *this = this->Inverse(); } void Matrix33::SetTranspose() { *this = this->Transpose(); } void Matrix33::SetZero() { data[0] = 0.0f; data[1] = 0.0f; data[2] = 0.0f; data[3] = 0.0f; data[4] = 0.0f; data[5] = 0.0f; data[6] = 0.0f; data[7] = 0.0f; data[8] = 0.0f; } void Matrix33::SetRotation(const Quaternion& quaternion) { if (quaternion.IsUnit()) { Real xs = quaternion.i + quaternion.i; Real ys = quaternion.j + quaternion.j; Real zs = quaternion.k + quaternion.k; Real wx = quaternion.r * xs; Real wy = quaternion.r * ys; Real wz = quaternion.r * zs; Real xx = quaternion.i * xs; Real xy = quaternion.i * ys; Real xz = quaternion.i * zs; Real yy = quaternion.j * ys; Real yz = quaternion.j * zs; Real zz = quaternion.k * zs; data[0] = 1.0f - (yy + zz); data[1] = xy - wz; data[2] = xz + wy; data[3] = xy + wz; data[4] = 1.0f - (xx + zz); data[5] = yz - wx; data[6] = xz - wy; data[7] = yz + wx; data[8] = 1.0f - (xx + yy); } } void Matrix33::SetRotation(const EulerAngle& euler_angle) { Real sin_x = sinf(euler_angle.x_rotation); Real cos_x = cosf(euler_angle.x_rotation); Real sin_y = sinf(euler_angle.y_rotation); Real cos_y = cosf(euler_angle.y_rotation); Real sin_z = sinf(euler_angle.z_rotation); Real cos_z = cosf(euler_angle.z_rotation); data[0] = (cos_y * cos_z); data[1] = -(cos_y * sin_z); data[2] = sin_y; data[3] = (sin_x * sin_y * cos_z) + (cos_x * sin_z); data[4] = -(sin_x * sin_y * sin_z) + (cos_x * cos_z); data[5] = -(sin_x * cos_y); data[6] = -(cos_x * sin_y * cos_z) + (sin_x * sin_z); data[7] = (cos_x * sin_y * sin_z) + (sin_x * cos_z); data[8] = (cos_x * cos_y); } void Matrix33::SetRotation(const AxisRadian& axis_radian) { Real sin = sinf(axis_radian.radian); Real cos = cosf(axis_radian.radian); Real t = 1.0f - cos; Vector3 unit_axis = axis_radian.axis.Unit(); Real tx = t * unit_axis.x; Real ty = t * unit_axis.y; Real tz = t * unit_axis.z; Real sx = sin * unit_axis.x; Real sy = sin * unit_axis.y; Real sz = sin * unit_axis.z; Real txy = tx * unit_axis.y; Real tyz = tx * unit_axis.z; Real txz = tx * unit_axis.z; data[0] = (tx * unit_axis.x + cos); data[1] = (txy - sz); data[2] = (txz + sy); data[3] = (txy + sz); data[4] = (ty * unit_axis.y + cos); data[5] = (tyz - sx); data[6] = (txz - sy); data[7] = (tyz + sx); data[8] = (tz * unit_axis.z + cos); } void Matrix33::SetRotation(const Vector3& axis, Real radian) { Real sin = sinf(radian); Real cos = cosf(radian); Real t = 1.0f - cos; Vector3 unit_axis = axis.Unit(); Real tx = t * unit_axis.x; Real ty = t * unit_axis.y; Real tz = t * unit_axis.z; Real sx = sin * unit_axis.x; Real sy = sin * unit_axis.y; Real sz = sin * unit_axis.z; Real txy = tx * unit_axis.y; Real tyz = tx * unit_axis.z; Real txz = tx * unit_axis.z; data[0] = (tx * unit_axis.x + cos); data[1] = (txy - sz); data[2] = (txz + sy); data[3] = (txy + sz); data[4] = (ty * unit_axis.y + cos); data[5] = (tyz - sx); data[6] = (txz - sy); data[7] = (tyz + sx); data[8] = (tz * unit_axis.z + cos); } void Matrix33::SetRotationX(Real radian) { Real sin = sinf(radian); Real cos = cosf(radian); data[0] = 1.0f; data[1] = 0.0f; data[2] = 0.0f; data[3] = 0.0f; data[4] = cos; data[5] = -sin; data[6] = 0.0f; data[7] = sin; data[8] = cos; } void Matrix33::SetRotationY(Real radian) { Real sin = sinf(radian); Real cos = cosf(radian); data[0] = cos; data[1] = 0.0f; data[2] = sin; data[3] = 0.0f; data[4] = 1.0f; data[5] = 0.0f; data[6] = -sin; data[7] = 0.0f; data[8] = cos; } void Matrix33::SetRotationZ(Real radian) { Real sin = sinf(radian); Real cos = cosf(radian); data[0] = cos; data[1] = -sin; data[2] = 0.0f; data[3] = sin; data[4] = cos; data[5] = 0.0f; data[6] = 0.0f; data[7] = 0.0f; data[8] = 1.0f; } void Matrix33::SetScale(const Vector3& scale) { data[0] = scale.x; data[1] = 0.0f; data[2] = 0.0f; data[3] = 0.0f; data[4] = scale.y; data[5] = 0.0f; data[6] = 0.0f; data[7] = 0.0f; data[8] = scale.z; } void Matrix33::SetTranslation(const Vector2& translation) { data[0] = 1.0f; data[1] = 0.0f; data[2] = translation.x; data[3] = 0.0f; data[4] = 1.0f; data[5] = translation.y; data[6] = 0.0f; data[7] = 0.0f; data[8] = 1.0f; } void Matrix33::SetSkew(const Vector3& v) { data[0] = 0.0f; data[1] = -v.z; data[2] = v.y; data[3] = v.z; data[4] = 0.0f; data[5] = -v.x; data[6] = -v.y; data[7] = v.x; data[8] = 0.0f; } bool Matrix33::IsZero() const { for (size_t i = 0; i < 9; ++i) { if (Math::IsZero(data[i]) == false) return false; } return true; } bool Matrix33::IsIdentity() const { return Math::IsEqual(1.0f, data[0]) && Math::IsEqual(1.0f, data[4]) && Math::IsEqual(1.0f, data[8]) && Math::IsZero(data[1]) && Math::IsZero(data[2]) && Math::IsZero(data[3]) && Math::IsZero(data[5]) && Math::IsZero(data[6]) && Math::IsZero(data[7]); } bool Matrix33::IsEqual(const Matrix33& rhs) const { for (size_t i = 0; i < 9; ++i) { if (Math::IsEqual(data[i], rhs.data[i]) == false) return false; } return true; } bool Matrix33::IsNotEqual(const Matrix33& rhs) const { for (size_t i = 0; i < 9; ++i) { if (Math::IsEqual(data[i], rhs.data[i]) == false) return true; } return false; } void Matrix33::GetRows(Vector3& row1, Vector3& row2, Vector3& row3) const { row1.x = data[0]; row1.y = data[1]; row1.z = data[2]; row2.x = data[3]; row2.y = data[4]; row2.z = data[5]; row3.x = data[6]; row3.y = data[7]; row3.z = data[8]; } Vector3 Matrix33::GetRow(size_t i) const { size_t val = i % 3; return Vector3(data[3 * val], data[3 * val + 1], data[3 * val + 2]); } void Matrix33::GetColumns(Vector3& col1, Vector3& col2, Vector3& col3) const { col1.x = data[0]; col2.x = data[1]; col3.x = data[2]; col1.y = data[3]; col2.y = data[4]; col3.y = data[5]; col1.z = data[6]; col2.z = data[7]; col3.z = data[8]; } Vector3 Matrix33::GetColumn(size_t i) const { size_t val = i % 3; return Vector3(data[val], data[val + 3], data[val + 6]); } Quaternion Matrix33::ToQuaternion() const { Quaternion result; Real trace = Trace(); if (trace > 0.0f) { Real s = sqrtf(trace + 1.0f); result.r = s * 0.5f; Real multiplier = 0.5f / s; result.i = ((*this)(2, 1) - (*this)(1, 2)) * multiplier; result.j = ((*this)(0, 2) - (*this)(2, 0)) * multiplier; result.k = ((*this)(1, 0) - (*this)(0, 1)) * multiplier; } else { size_t _i = 0; if ((*this)(1, 1) > (*this)(0, 0)) { _i = 1; } if ((*this)(2, 2) > (*this)(_i, _i)) { _i = 2; } size_t _j = (_i + 1) % 3; size_t _k = (_j + 1) % 3; Real s = sqrtf((*this)(_i, _i) - (*this)(_j, _j) - (*this)(_k, _k) + 1.0f); result[_i] = 0.5f * s; Real multiplier = 0.5f / s; result.r = ((*this)(_k, _j) - (*this)(_j, _k)) * multiplier; result[_j] = ((*this)(_j, _i) + (*this)(_i, _j)) * multiplier; result[_k] = ((*this)(_k, _i) + (*this)(_i, _k)) * multiplier; } return result; } AxisRadian Matrix33::ToAxisRadian() const { Real trace = data[0] + data[4] + data[8]; Real cos_theta = 0.5f * (trace - 1.0f); Real radian = acosf(cos_theta); Vector3 axis; // angle is zero, axis can be anything if (Math::IsZero(radian)) { axis = Math::Vector3::Y_AXIS; } // standard case else if (radian < Math::PI - Math::EPSILON) { axis.Set(data[7] - data[5], data[2] - data[6], data[3] - data[1]); axis.SetNormalize(); } // angle is 180 degrees else { size_t i = 0; if (data[4] > data[0]) { i = 1; } if (data[8] > data[i + 3 * i]) { i = 2; } size_t j = (i + 1) % 3; size_t k = (j + 1) % 3; Real s = sqrtf(data[i + 3 * i] - data[j + 3 * j] - data[k + 3 * k] + 1.0f); axis[i] = 0.5f * s; Real multiplier = 1.0f / s; axis[j] = (data[3 * i + j]) * multiplier; axis[k] = (data[3 * k + i]) * multiplier; } return AxisRadian(axis, radian); } EulerAngle Matrix33::ToEulerAngle() const { Real cos_x, sin_x, cos_z, sin_z; Real sin_y = data[2]; Real cos_y = sqrtf(1.0f - sin_y * sin_y); if (Math::IsZero(cos_y) == false) { Real factor = 1.0f / cos_y; sin_x = -data[5] * factor; cos_x = data[8] * factor; sin_z = -data[1] * factor; cos_z = data[0] * factor; } else // x and z axes aligned { sin_z = 0.0f; cos_z = 1.0f; sin_x = data[7]; cos_x = data[4]; } Real x_rotation = atan2f(sin_x, cos_x); Real y_rotation = atan2f(sin_y, cos_y); Real z_rotation = atan2f(sin_z, cos_z); return EulerAngle(x_rotation, y_rotation, z_rotation); } Matrix33 Matrix33::Adjoint() const { Matrix33 result; // compute transpose of cofactors result.data[0] = data[4] * data[8] - data[7] * data[5]; result.data[3] = data[6] * data[5] - data[3] * data[8]; result.data[6] = data[3] * data[7] - data[6] * data[4]; result.data[1] = data[7] * data[2] - data[1] * data[8]; result.data[4] = data[0] * data[8] - data[6] * data[2]; result.data[7] = data[6] * data[1] - data[0] * data[7]; result.data[2] = data[1] * data[5] - data[4] * data[2]; result.data[5] = data[3] * data[2] - data[0] * data[5]; result.data[8] = data[0] * data[4] - data[3] * data[1]; return result; } Real Matrix33::Determinant() const { return data[0] * (data[4] * data[8] - data[5] * data[7]) + data[1] * (data[5] * data[6] - data[3] * data[8]) + data[2] * (data[3] * data[7] - data[4] * data[6]); } Real Matrix33::Trace() const { return data[0] + data[4] + data[8]; } Matrix33 Matrix33::Inverse() const { Matrix33 result; // compute determinant Real cofactor0 = this->data[4] * this->data[8] - this->data[5] * this->data[7]; Real cofactor3 = this->data[5] * this->data[6] - this->data[3] * this->data[8]; Real cofactor6 = this->data[3] * this->data[7] - this->data[4] * this->data[6]; Real det = this->data[0] * cofactor0 + this->data[1] * cofactor3 + this->data[2] * cofactor6; if (Math::IsZero(det)) { //E5_ASSERT(false, "Inverse singular matrix"); return result; } // create adjoint matrix and multiply by 1/det to get inverse Real inv_det = 1.0f / det; result.data[0] = inv_det * cofactor0; result.data[3] = inv_det * cofactor3; result.data[6] = inv_det * cofactor6; result.data[1] = inv_det * (this->data[2] * this->data[7] - this->data[1] * this->data[8]); result.data[4] = inv_det * (this->data[0] * this->data[8] - this->data[2] * this->data[6]); result.data[7] = inv_det * (this->data[1] * this->data[6] - this->data[0] * this->data[7]); result.data[2] = inv_det * (this->data[1] * this->data[5] - this->data[2] * this->data[4]); result.data[5] = inv_det * (this->data[2] * this->data[3] - this->data[0] * this->data[5]); result.data[8] = inv_det * (this->data[0] * this->data[4] - this->data[1] * this->data[3]); return result; } Matrix33 Matrix33::Transpose() const { Matrix33 result; result.data[0] = this->data[0]; result.data[1] = this->data[3]; result.data[2] = this->data[6]; result.data[3] = this->data[1]; result.data[4] = this->data[4]; result.data[5] = this->data[7]; result.data[6] = this->data[2]; result.data[7] = this->data[5]; result.data[8] = this->data[8]; return result; } Matrix33 Matrix33::HadamardProduct(const Matrix33& rhs) const { return Matrix33( data[0] * rhs.data[0], data[1] * rhs.data[1], data[2] * rhs.data[2], data[3] * rhs.data[3], data[4] * rhs.data[4], data[5] * rhs.data[5], data[6] * rhs.data[6], data[7] * rhs.data[7], data[8] * rhs.data[8]); } Matrix33 Inverse(const Matrix33& mat) { return mat.Inverse(); } Matrix33 Transpose(const Matrix33& mat) { return mat.Transpose(); } Matrix33 HadamardProduct(const Matrix33& mat1, const Matrix33& mat2) { return mat1.HadamardProduct(mat2); } Matrix33 Skew(const Vector3& v) { return Matrix33( 0.0f, -v.z, v.y, v.z, 0.0f, -v.x, -v.y, v.x, 0.0f ); } Matrix33& Matrix33::operator=(const Matrix33& rhs) { if (this != &rhs) { for (int i = 0; i < 9; ++i) { this->data[i] = rhs.data[i]; } } return *this; } Matrix33& Matrix33::operator=(const Matrix44& rhs) { data[0] = rhs.data[0]; data[1] = rhs.data[1]; data[2] = rhs.data[2]; data[3] = rhs.data[4]; data[4] = rhs.data[5]; data[5] = rhs.data[6]; data[6] = rhs.data[8]; data[7] = rhs.data[9]; data[8] = rhs.data[10]; return *this; } Real Matrix33::operator()(size_t i, size_t j) const { return data[3 * (i % 3) + (j % 3)]; } Real& Matrix33::operator()(size_t i, size_t j) { return data[3 * (i % 3) + (j % 3)]; } Real Matrix33::operator[](size_t i) const { return data[i]; } Real& Matrix33::operator[](size_t i) { return data[i]; } bool Matrix33::operator==(const Matrix33& rhs) const { for (size_t i = 0; i < 9; ++i) { if (Math::IsEqual(data[i], rhs.data[i]) == false) return false; } return true; } bool Matrix33::operator!=(const Matrix33& rhs) const { for (size_t i = 0; i < 9; ++i) { if (Math::IsEqual(data[i], rhs.data[i]) == false) return true; } return false; } Matrix33 Matrix33::operator+(const Matrix33& rhs) const { Matrix33 result; for (size_t i = 0; i < 9; ++i) { result.data[i] = data[i] + rhs.data[i]; } return result; } Matrix33& Matrix33::operator+=(const Matrix33& rhs) { for (size_t i = 0; i < 9; ++i) { data[i] += rhs.data[i]; } return *this; } Matrix33 Matrix33::operator-(const Matrix33& rhs) const { Matrix33 result; for (size_t i = 0; i < 9; ++i) { result.data[i] = data[i] - rhs.data[i]; } return result; } Matrix33& Matrix33::operator-=(const Matrix33& rhs) { for (size_t i = 0; i < 9; ++i) { data[i] -= rhs.data[i]; } return *this; } Matrix33 Matrix33::operator-() const { Matrix33 result; for (size_t i = 0; i < 9; ++i) { result.data[i] = -data[i]; } return result; } Matrix33 Matrix33::operator*(const Matrix33& matrix) const { Matrix33 result; result.data[0] = data[0] * matrix.data[0] + data[1] * matrix.data[3] + data[2] * matrix.data[6]; result.data[1] = data[0] * matrix.data[1] + data[1] * matrix.data[4] + data[2] * matrix.data[7]; result.data[2] = data[0] * matrix.data[2] + data[1] * matrix.data[5] + data[2] * matrix.data[8]; result.data[3] = data[3] * matrix.data[0] + data[4] * matrix.data[3] + data[5] * matrix.data[6]; result.data[4] = data[3] * matrix.data[1] + data[4] * matrix.data[4] + data[5] * matrix.data[7]; result.data[5] = data[3] * matrix.data[2] + data[4] * matrix.data[5] + data[5] * matrix.data[8]; result.data[6] = data[6] * matrix.data[0] + data[7] * matrix.data[3] + data[8] * matrix.data[6]; result.data[7] = data[6] * matrix.data[1] + data[7] * matrix.data[4] + data[8] * matrix.data[7]; result.data[8] = data[6] * matrix.data[2] + data[7] * matrix.data[5] + data[8] * matrix.data[8]; return result; } Matrix33& Matrix33::operator*=(const Matrix33& matrix) { Matrix33 result; result.data[0] = data[0] * matrix.data[0] + data[1] * matrix.data[3] + data[2] * matrix.data[6]; result.data[1] = data[0] * matrix.data[1] + data[1] * matrix.data[4] + data[2] * matrix.data[7]; result.data[2] = data[0] * matrix.data[2] + data[1] * matrix.data[5] + data[2] * matrix.data[8]; result.data[3] = data[3] * matrix.data[0] + data[4] * matrix.data[3] + data[5] * matrix.data[6]; result.data[4] = data[3] * matrix.data[1] + data[4] * matrix.data[4] + data[5] * matrix.data[7]; result.data[5] = data[3] * matrix.data[2] + data[4] * matrix.data[5] + data[5] * matrix.data[8]; result.data[6] = data[6] * matrix.data[0] + data[7] * matrix.data[3] + data[8] * matrix.data[6]; result.data[7] = data[6] * matrix.data[1] + data[7] * matrix.data[4] + data[8] * matrix.data[7]; result.data[8] = data[6] * matrix.data[2] + data[7] * matrix.data[5] + data[8] * matrix.data[8]; for (size_t i = 0; i < 9; ++i) { data[i] = result.data[i]; } return *this; } Vector3 Matrix33::operator*(const Vector3& vector) const { Vector3 result; result.x = data[0] * vector.x + data[1] * vector.y + data[2] * vector.z; result.y = data[3] * vector.x + data[4] * vector.y + data[5] * vector.z; result.z = data[6] * vector.x + data[7] * vector.y + data[8] * vector.z; return result; } Vector3 operator*(const Vector3& vector, const Matrix33& matrix) { Vector3 result; result.x = matrix.data[0] * vector.x + matrix.data[3] * vector.y + matrix.data[6] * vector.z; result.y = matrix.data[1] * vector.x + matrix.data[4] * vector.y + matrix.data[7] * vector.z; result.z = matrix.data[2] * vector.x + matrix.data[5] * vector.y + matrix.data[8] * vector.z; return result; } Matrix33 Matrix33::operator*(Real real) const { Matrix33 result; result.data[0] = data[0] * real; result.data[1] = data[1] * real; result.data[2] = data[2] * real; result.data[3] = data[3] * real; result.data[4] = data[4] * real; result.data[5] = data[5] * real; result.data[6] = data[6] * real; result.data[7] = data[7] * real; result.data[8] = data[8] * real; return result; } Matrix33& Matrix33::operator*=(Real real) { data[0] *= real; data[1] *= real; data[2] *= real; data[3] *= real; data[4] *= real; data[5] *= real; data[6] *= real; data[7] *= real; data[8] *= real; return *this; } Matrix33 operator*(Real real, const Matrix33& matrix) { Matrix33 result; result.data[0] = matrix.data[0] * real; result.data[1] = matrix.data[1] * real; result.data[2] = matrix.data[2] * real; result.data[3] = matrix.data[3] * real; result.data[4] = matrix.data[4] * real; result.data[5] = matrix.data[5] * real; result.data[6] = matrix.data[6] * real; result.data[7] = matrix.data[7] * real; result.data[8] = matrix.data[8] * real; return result; } std::ostream& operator<<(std::ostream& os, const Matrix33& rhs) { os << "|" << rhs.data[0] << ", " << rhs.data[1] << ", " << rhs.data[2] << "|\n"; os << "|" << rhs.data[3] << ", " << rhs.data[4] << ", " << rhs.data[5] << "|\n"; os << "|" << rhs.data[6] << ", " << rhs.data[7] << ", " << rhs.data[8] << "|"; return os; } Matrix33 Matrix33::Identity() { return Matrix33(); } Matrix33 Matrix33::Zero() { return Matrix33( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); } }
30.562427
107
0.460331
[ "vector" ]
9a1979b539c7e54ecc738b59c3c0fe392adbb36d
28,348
cpp
C++
tests/unittests/transforms/unittest_streamingmemory.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
tests/unittests/transforms/unittest_streamingmemory.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
tests/unittests/transforms/unittest_streamingmemory.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #define BOOST_TEST_MODULE streamingmemory_unittest #include <testutil/irquery/irquery.hpp> #include <testutil/test_graphs/graph_test_models.hpp> #include <boost/test/unit_test.hpp> #include <popart/graphutils.hpp> #include <popart/ir.hpp> #include <popart/op.hpp> #include <popart/op/accumulate.hpp> #include <popart/op/adamupdater.hpp> #include <popart/op/adamvarupdate.hpp> #include <popart/op/collectives/collectives.hpp> #include <popart/op/collectives/replicatedallgather.hpp> #include <popart/op/collectives/replicatedallreduce.hpp> #include <popart/op/collectives/replicatedreducescatter.hpp> #include <popart/op/exchange/hostcopy.hpp> #include <popart/op/exchange/remote.hpp> #include <popart/op/init.hpp> #include <popart/op/lamb.hpp> #include <popart/op/scale.hpp> #include <popart/op/scaledadd.hpp> #include <popart/op/sgd0varupdate.hpp> #include <popart/op/sgd1acclupdate.hpp> #include <popart/op/sgd1varupdate.hpp> #include <popart/op/sgd2acclupdate.hpp> #include <popart/op/sgd2varupdate.hpp> #include <popart/transforms/prune.hpp> #include <popart/transforms/streamingmemory.hpp> using namespace popart; using namespace popart::irquery; // Test if weights and optimizer states are sharded correctly with different // optimizers BOOST_AUTO_TEST_CASE(BasicReplicatedTensorShardingTest) { SessionOptions options; options.enableReplicatedGraphs = true; options.enableDistributedReplicatedGraphs = false; options.replicatedGraphCount = 4; options.globalReplicaOffset = 0; options.globalReplicationFactor = 1; options.weightTensorLocationSettings.minElementsForReplicatedTensorSharding = 4; options.weightTensorLocationSettings.location.replicatedTensorSharding = ReplicatedTensorSharding::On; options.optimizerStateTensorLocationSettings .minElementsForReplicatedTensorSharding = 4; options.optimizerStateTensorLocationSettings.location .replicatedTensorSharding = ReplicatedTensorSharding::On; std::set<TestOptimizer> testOptimizers{TestOptimizer::SGD0, TestOptimizer::SGD1, TestOptimizer::SGD2, TestOptimizer::Adam, TestOptimizer::Lamb}; for (auto testOptimizer : testOptimizers) { OptimizerTestModel model(testOptimizer, 1, options); auto &ir = model.getIr(); DeviceManager &dm = DeviceManager::createDeviceManager(); std::map<std::string, std::string> deviceOpts; deviceOpts["numIPUs"] = "4"; auto device = dm.createOfflineIPUDevice(deviceOpts); BOOST_REQUIRE_NE(device.get(), nullptr); ir.setDeviceInfo(*device); BOOST_REQUIRE_EQUAL(std::to_string(ir.getDeviceInfo()->getNumIpus()), deviceOpts["numIPUs"]); ir.applyTransform(StreamingMemory::id(1), ir.getMainGraph()); ir.applyTransform(StreamingMemory::id(2), ir.getMainGraph()); ir.updateVertices(); ir.applyTransform(Prune::id(), ir.getMainGraph()); ir.updateVertices(); ir.setIsPrepared(); ir.dotCheckpoint(ir, "Final"); IrTestWrapper tw_ir{ir}; auto tw_mainGraph = tw_ir.hasGraph(ir.getMainGraph().id, Require::MustBeTrue); auto &graph = tw_mainGraph->unwrap().get(); switch (testOptimizer) { case TestOptimizer::SGD0: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { return op->isConvertibleTo<SGD0VarUpdateOp>(); }}; graphutils::Edges edges{{0, 1}, {1, 2}, {1, 4}, {3, 4}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::SGD1: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD1AcclUpdateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD1VarUpdateOp>(); }}; graphutils::Edges edges{ {0, 2}, {1, 3}, {2, 4}, {2, 8}, {3, 6}, {5, 6}, {6, 7}, {6, 8}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::SGD2: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, [](const Op *op) { return op->isConvertibleTo<SGD2PartialAcclUpdateOp>(); }, [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD2VarUpdateOp>(); }}; graphutils::Edges edges{{0, 2}, {1, 3}, {2, 6}, {2, 4}, {2, 8}, {3, 6, 0, 1}, {5, 7}, {6, 7}, {7, 8}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::Adam: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 0 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 1 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 2 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 3 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 4 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 5 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, // 6 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, // 7 [](const Op *op) { return op->isConvertibleTo<AdamUpdaterOp>(); }, // 8 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 9 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 10 [](const Op *op) { return op->isConvertibleTo<AdamVarUpdateOp>(); }, // 11 [](const Op *op) { return op->isConvertibleTo<ScaleOp>(); }, // 12 [](const Op *op) { return op->isConvertibleTo<ScaledAddOp>(); } // 13 }; graphutils::Edges edges{ {0, 3}, // Init -> RemoteLoad {1, 4}, // Init -> RemoteLoad {2, 5}, // Init -> RemoteLoad {3, 11}, // RemoteLoad -> AdamVarUpdateOp {3, 6}, // RemoteLoad -> ReplicatedAllGatherOp {4, 9}, // RemoteLoad -> AccumulateOp {5, 10}, // RemoteLoad -> AccumulateOp {9, 8, 0, AdamUpdaterOp::getAccl1InIndex()}, // Accumulate -> AdamUpdater {10, 8, 0, AdamUpdaterOp::getAccl2InIndex()}, // Accumulate -> AdamUpdater {8, 11}, // AdamUpdater -> AdamVarUpdateOp {7, 12}, // ReplicatedReduceScatterOp -> Scale {12, 13}, // Scale -> ScaledAdd {13, 9}, // ScaledAdd -> Accumulate {13, 10} // ScaledAdd -> Accumulate }; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::Lamb: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 0 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 1 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 2 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 3 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 4 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 5 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, // 6 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); }, // 7 [](const Op *op) { return op->isConvertibleTo<AdamUpdaterOp>(); }, // 8 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 9 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 10 [](const Op *op) { return op->isConvertibleTo<AdamVarUpdateOp>(); }, // 11 [](const Op *op) { return op->isConvertibleTo<ScaleOp>(); }, // 12 [](const Op *op) { return op->isConvertibleTo<ScaledAddOp>(); }, // 13 [](const Op *op) { return op->isConvertibleTo<LambSquareOp>(); }, // 14 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceInplaceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::All, 0); } // 15 }; graphutils::Edges edges{ {0, 3}, // Init -> RemoteLoad {1, 4}, // Init -> RemoteLoad {2, 5}, // Init -> RemoteLoad {3, 11}, // RemoteLoad -> AdamVarUpdateOp {3, 6}, // RemoteLoad -> ReplicatedAllGatherOp {4, 9}, // RemoteLoad -> AccumulateOp {5, 10}, // RemoteLoad -> AccumulateOp {9, 8, 0, AdamUpdaterOp::getAccl1InIndex()}, // Accumulate -> AdamUpdater {10, 8, 0, AdamUpdaterOp::getAccl2InIndex()}, // Accumulate -> AdamUpdater {8, 11}, // AdamUpdater -> AdamVarUpdateOp {7, 12}, // ReplicatedReduceScatterOp -> Scale {12, 13}, // Scale -> ScaledAdd {13, 9}, // ScaledAdd -> Accumulate {13, 10}, // ScaledAdd -> Accumulate {8, 14}, // AdamUpdater -> LambSquare {14, 15}, // LambSquare -> ReplicatedAllReduceInplace {15, 11}, // ReplicatedAllReduceInplace -> AdamVarUpdate }; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; } } } // Test if weights and optimizer states are sharded correctly with different // optimizers split across two GCDs BOOST_AUTO_TEST_CASE(DistributedReplicatedTensorShardingTest) { SessionOptions options; options.enableReplicatedGraphs = true; options.enableDistributedReplicatedGraphs = true; options.replicatedGraphCount = 4; options.globalReplicaOffset = 0; options.globalReplicationFactor = 8; options.weightTensorLocationSettings.minElementsForReplicatedTensorSharding = 4; options.weightTensorLocationSettings.location.replicatedTensorSharding = ReplicatedTensorSharding::On; options.weightTensorLocationSettings.location.shardingDomain = CommGroup(CommGroupType::Consecutive, 4); options.optimizerStateTensorLocationSettings .minElementsForReplicatedTensorSharding = 4; options.optimizerStateTensorLocationSettings.location .replicatedTensorSharding = ReplicatedTensorSharding::On; options.optimizerStateTensorLocationSettings.location.shardingDomain = CommGroup(CommGroupType::Consecutive, 4); std::set<TestOptimizer> testOptimizers{TestOptimizer::SGD0, TestOptimizer::SGD1, TestOptimizer::SGD2, TestOptimizer::Adam, TestOptimizer::Lamb}; for (auto testOptimizer : testOptimizers) { OptimizerTestModel model(testOptimizer, 1, options); auto &ir = model.getIr(); DeviceManager &dm = DeviceManager::createDeviceManager(); std::map<std::string, std::string> deviceOpts; deviceOpts["numIPUs"] = "4"; auto device = dm.createOfflineIPUDevice(deviceOpts); BOOST_REQUIRE_NE(device.get(), nullptr); ir.setDeviceInfo(*device); BOOST_REQUIRE_EQUAL(std::to_string(ir.getDeviceInfo()->getNumIpus()), deviceOpts["numIPUs"]); ir.applyTransform(StreamingMemory::id(1), ir.getMainGraph()); ir.applyTransform(StreamingMemory::id(2), ir.getMainGraph()); ir.updateVertices(); ir.applyTransform(Prune::id(), ir.getMainGraph()); ir.updateVertices(); ir.setIsPrepared(); ir.dotCheckpoint(ir, "Final"); IrTestWrapper tw_ir{ir}; auto tw_mainGraph = tw_ir.hasGraph(ir.getMainGraph().id, Require::MustBeTrue); auto &graph = tw_mainGraph->unwrap().get(); switch (testOptimizer) { case TestOptimizer::SGD0: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Orthogonal, 2); }, [](const Op *op) { return op->isConvertibleTo<SGD0VarUpdateOp>(); }}; graphutils::Edges edges{{0, 1}, {1, 2}, {1, 5}, {3, 4}, {4, 5}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::SGD1: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Orthogonal, 2); }, [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD1AcclUpdateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD1VarUpdateOp>(); }}; graphutils::Edges edges{{0, 2}, {1, 3}, {2, 4}, {2, 9}, {3, 7}, {5, 6}, {6, 7}, {7, 8}, {7, 9}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::SGD2: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Orthogonal, 2); }, [](const Op *op) { return op->isConvertibleTo<SGD2PartialAcclUpdateOp>(); }, [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, [](const Op *op) { return op->isConvertibleTo<SGD2VarUpdateOp>(); }}; graphutils::Edges edges{{0, 2}, {1, 3}, {2, 7}, {2, 4}, {2, 9}, {3, 7, 0, 1}, {5, 6}, {6, 8}, {7, 8}, {8, 9}}; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::Adam: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 0 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 1 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 2 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 3 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 4 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 5 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, // 6 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, // 7 [](const Op *op) { return op->isConvertibleTo<AdamUpdaterOp>(); }, // 8 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 9 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 10 [](const Op *op) { return op->isConvertibleTo<AdamVarUpdateOp>(); }, // 11 [](const Op *op) { return op->isConvertibleTo<ScaleOp>(); }, // 12 [](const Op *op) { return op->isConvertibleTo<ScaledAddOp>(); }, // 13 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Orthogonal, 2); } // 14 }; graphutils::Edges edges{ {0, 3}, // Init -> RemoteLoad {1, 4}, // Init -> RemoteLoad {2, 5}, // Init -> RemoteLoad {3, 11}, // RemoteLoad -> AdamVarUpdateOp {3, 6}, // RemoteLoad -> ReplicatedAllGatherOp {4, 9}, // RemoteLoad -> AccumulateOp {5, 10}, // RemoteLoad -> AccumulateOp {9, 8, 0, AdamUpdaterOp::getAccl1InIndex()}, // Accumulate -> AdamUpdater {10, 8, 0, AdamUpdaterOp::getAccl2InIndex()}, // Accumulate -> AdamUpdater {8, 11}, // AdamUpdater -> AdamVarUpdateOp {7, 14}, // ReplicatedReduceScatterOp -> ReplicatedAllReduce {14, 12}, // ReplicatedAllReduce -> Scale {12, 13}, // Scale -> ScaledAdd {13, 9}, // ScaledAdd -> Accumulate {13, 10} // ScaledAdd -> Accumulate }; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; case TestOptimizer::Lamb: { graphutils::OpPreds preds{ [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 0 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 1 [](const Op *op) { return op->isConvertibleTo<InitOp>(); }, // 2 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 3 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 4 [](const Op *op) { return op->isConvertibleTo<RemoteLoadOp>(); }, // 5 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllGatherOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, // 6 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedReduceScatterOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, // 7 [](const Op *op) { return op->isConvertibleTo<AdamUpdaterOp>(); }, // 8 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 9 [](const Op *op) { return op->isConvertibleTo<AccumulateOp>(); }, // 10 [](const Op *op) { return op->isConvertibleTo<AdamVarUpdateOp>(); }, // 11 [](const Op *op) { return op->isConvertibleTo<ScaleOp>(); }, // 12 [](const Op *op) { return op->isConvertibleTo<ScaledAddOp>(); }, // 13 [](const Op *op) { return op->isConvertibleTo<LambSquareOp>(); }, // 14 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceInplaceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Consecutive, 4); }, // 15 [](const Op *op) { auto rop = dynamic_cast<const ReplicatedAllReduceOp *>(op); return rop && rop->getGCLCommGroup() == CommGroup(CommGroupType::Orthogonal, 2); } // 16 }; graphutils::Edges edges{ {0, 3}, // Init -> RemoteLoad {1, 4}, // Init -> RemoteLoad {2, 5}, // Init -> RemoteLoad {3, 11}, // RemoteLoad -> AdamVarUpdateOp {3, 6}, // RemoteLoad -> ReplicatedAllGatherOp {4, 9}, // RemoteLoad -> AccumulateOp {5, 10}, // RemoteLoad -> AccumulateOp {9, 8, 0, AdamUpdaterOp::getAccl1InIndex()}, // Accumulate -> AdamUpdater {10, 8, 0, AdamUpdaterOp::getAccl2InIndex()}, // Accumulate -> AdamUpdater {8, 11}, // AdamUpdater -> AdamVarUpdateOp {7, 16}, // ReplicatedReduceScatterOp -> ReplicatedAllReduce {16, 12}, // ReplicatedAllReduce -> Scale {12, 13}, // Scale -> ScaledAdd {13, 9}, // ScaledAdd -> Accumulate {13, 10}, // ScaledAdd -> Accumulate {8, 14}, // AdamUpdater -> LambSquare {14, 15}, // LambSquare -> ReplicatedAllReduceInplace {15, 11}, // ReplicatedAllReduceInplace -> AdamVarUpdate }; auto matches = graphutils::findMatchingOps(graph, preds, edges); // Expect two instances of the remote exchange / collectives / optimizer // pattern (one per weight tensor) BOOST_REQUIRE_EQUAL(matches.size(), 2); break; }; } } }
44.018634
80
0.536369
[ "model" ]
9a1b8122a40c090b5100b844dca2f0e1ee15394d
27,980
cpp
C++
common/CommonStructures.cpp
S1lv10Fr4gn4n1/physics-simulation-tool-ios
6d32bfcbe0b90a9b0112c56faa971ea4be278e93
[ "MIT" ]
null
null
null
common/CommonStructures.cpp
S1lv10Fr4gn4n1/physics-simulation-tool-ios
6d32bfcbe0b90a9b0112c56faa971ea4be278e93
[ "MIT" ]
null
null
null
common/CommonStructures.cpp
S1lv10Fr4gn4n1/physics-simulation-tool-ios
6d32bfcbe0b90a9b0112c56faa971ea4be278e93
[ "MIT" ]
null
null
null
// // CommonStructures.cpp // Physical.Simulation.Tool // // Created by Silvio Fragnani on 21/08/12. // // #include "CommonStructures.h" /***************************** Vector3 *****************************/ Vector3::Vector3() { this->x = 0.0f; this->y = 0.0f; this->z = 0.0f; this->pad = 0.0f; } Vector3::Vector3(const Vector3 &_vector) { this->x = _vector.x; this->y = _vector.y; this->z = _vector.z; this->pad = 0.0f; } Vector3::Vector3(const real _x, const real _y, const real _z) { this->x = _x; this->y = _y; this->z = _z; this->pad = 0.0f; } Vector3::Vector3(const real _x, const real _y) { this->x = _x; this->y = _y; this->z = 0.0f; this->pad = 0.0f; } Vector3::~Vector3() { // TODO put your code here } void Vector3::clear() { this->x = 0.0f; this->y = 0.0f; this->z = 0.0f; this->pad = 0.0f; } real Vector3::operator[](unsigned _index) const { if (_index == 0) { return this->x; } if (_index == 1) { return this->y; } return this->z; } real& Vector3::operator[](unsigned _index) { if (_index == 0) { return this->x; } else if (_index == 1) { return this->y; } return this->z; } void Vector3::operator+=(const Vector3 &_vector) { this->x += _vector.x; this->y += _vector.y; this->z += _vector.z; } void Vector3::operator=(const Vector3 &_vector) { this->x = _vector.x; this->y = _vector.y; this->z = _vector.z; } Vector3 Vector3::operator+(const Vector3 &_vector) const { return Vector3(this->x+_vector.x, this->y+_vector.y, this->z+_vector.z); } void Vector3::operator-=(const Vector3 &_vector) { this->x -= _vector.x; this->y -= _vector.y; this->z -= _vector.z; } Vector3 Vector3::operator-(const Vector3 &_vector) const { return Vector3(this->x-_vector.x, this->y-_vector.y, this->z-_vector.z); } void Vector3::addScaledVector(const Vector3 &_vector, real _scale) { this->x += _vector.x * _scale; this->y += _vector.y * _scale; this->z += _vector.z * _scale; } Vector3 Vector3::componentProduct(const Vector3 &_vector) const { return Vector3(this->x * _vector.x, this->y * _vector.y, this->z * _vector.z); } void Vector3::componentProductUpdate(const Vector3 &_vector) { this->x *= _vector.x; this->y *= _vector.y; this->z *= _vector.z; } real Vector3::scalarProduct(const Vector3 &_vector) const { return this->x*_vector.x + this->y*_vector.y + this->z*_vector.z; } real Vector3::operator *(const Vector3 &_vector) const { return this->x*_vector.x + this->y*_vector.y + this->z*_vector.z; } void Vector3::operator*=(const real _value) { this->x *= _value; this->y *= _value; this->z *= _value; } Vector3 Vector3::operator*(const real _value) const { return Vector3(this->x*_value, this->y*_value, this->z*_value); } Vector3 Vector3::vectorProduct(const Vector3 &_vector) const { return Vector3(this->y*_vector.z - this->z*_vector.y, this->z*_vector.x - this->x*_vector.z, this->x*_vector.y - this->y*_vector.x); } void Vector3::operator%=(const Vector3 &_vector) { *this = this->vectorProduct(_vector); } Vector3 Vector3::operator%(const Vector3 &_vector) const { return Vector3(this->y*_vector.z - this->z*_vector.y, this->z*_vector.x - this->x*_vector.z, this->x*_vector.y - this->y*_vector.x); } void Vector3::invert() { this->x = -this->x; this->y = -this->y; this->z = -this->z; } real Vector3::magnitude() const { return real_sqrt(this->x*this->x + this->y*this->y + this->z*this->z); } real Vector3::squareMagnitude() const { return this->x*this->x + this->y*this->y + this->z*this->z; } void Vector3::normalize() { real l = this->magnitude(); if (l > 0.0f) { (*this)*=((real)1)/l; } } /***************************** Color *****************************/ Color * Color::MakeRandonColor() { Color * color = new Color(); color->r = static_cast<unsigned char>(rand() % 256); color->g = static_cast<unsigned char>(rand() % 256); color->b = static_cast<unsigned char>(rand() % 256); color->a = 1; return color; } /***************************** BBox *****************************/ BBox::BBox() { this->ptr = NULL; this->color = colorBBox; } BBox::~BBox() { delete [] this->ptr; this->ptr = NULL; } /***************************** Matrix3 *****************************/ Matrix3::Matrix3() { this->data[0] = this->data[1] = this->data[2] = this->data[3] = this->data[4] = this->data[5] = this->data[6] = this->data[7] = this->data[8] = 0; } Matrix3::Matrix3(real _c0, real _c1, real _c2, real _c3, real _c4, real _c5, real _c6, real _c7, real _c8) { this->data[0] = _c0; this->data[1] = _c1; this->data[2] = _c2; this->data[3] = _c3; this->data[4] = _c4; this->data[5] = _c5; this->data[6] = _c6; this->data[7] = _c7; this->data[8] = _c8; } Vector3 Matrix3::operator*(const Vector3 &_vector) const { return Vector3(_vector.x * this->data[0] + _vector.y * this->data[1] + _vector.z * this->data[2], _vector.x * this->data[3] + _vector.y * this->data[4] + _vector.z * this->data[5], _vector.x * this->data[6] + _vector.y * this->data[7] + _vector.z * this->data[8] ); } Matrix3 Matrix3::operator*(const Matrix3 &_matrix) const { return Matrix3(this->data[0]*_matrix.data[0] + this->data[1]*_matrix.data[3] + this->data[2]*_matrix.data[6], this->data[0]*_matrix.data[1] + this->data[1]*_matrix.data[4] + this->data[2]*_matrix.data[7], this->data[0]*_matrix.data[2] + this->data[1]*_matrix.data[5] + this->data[2]*_matrix.data[8], this->data[3]*_matrix.data[0] + this->data[4]*_matrix.data[3] + this->data[5]*_matrix.data[6], this->data[3]*_matrix.data[1] + this->data[4]*_matrix.data[4] + this->data[5]*_matrix.data[7], this->data[3]*_matrix.data[2] + this->data[4]*_matrix.data[5] + this->data[5]*_matrix.data[8], this->data[6]*_matrix.data[0] + this->data[7]*_matrix.data[3] + this->data[8]*_matrix.data[6], this->data[6]*_matrix.data[1] + this->data[7]*_matrix.data[4] + this->data[8]*_matrix.data[7], this->data[6]*_matrix.data[2] + this->data[7]*_matrix.data[5] + this->data[8]*_matrix.data[8] ); } void Matrix3::operator*=(const Matrix3 &_matrix) { real t1; real t2; real t3; t1 = this->data[0]*_matrix.data[0] + this->data[1]*_matrix.data[3] + this->data[2]*_matrix.data[6]; t2 = this->data[0]*_matrix.data[1] + this->data[1]*_matrix.data[4] + this->data[2]*_matrix.data[7]; t3 = this->data[0]*_matrix.data[2] + this->data[1]*_matrix.data[5] + this->data[2]*_matrix.data[8]; this->data[0] = t1; this->data[1] = t2; this->data[2] = t3; t1 = this->data[3]*_matrix.data[0] + this->data[4]*_matrix.data[3] + this->data[5]*_matrix.data[6]; t2 = this->data[3]*_matrix.data[1] + this->data[4]*_matrix.data[4] + this->data[5]*_matrix.data[7]; t3 = this->data[3]*_matrix.data[2] + this->data[4]*_matrix.data[5] + this->data[5]*_matrix.data[8]; data[3] = t1; data[4] = t2; data[5] = t3; t1 = this->data[6]*_matrix.data[0] + this->data[7]*_matrix.data[3] + this->data[8]*_matrix.data[6]; t2 = this->data[6]*_matrix.data[1] + this->data[7]*_matrix.data[4] + this->data[8]*_matrix.data[7]; t3 = this->data[6]*_matrix.data[2] + this->data[7]*_matrix.data[5] + this->data[8]*_matrix.data[8]; this->data[6] = t1; this->data[7] = t2; this->data[8] = t3; } void Matrix3::operator+=(const Matrix3 &_matrix) { this->data[0] += _matrix.data[0]; this->data[1] += _matrix.data[1]; this->data[2] += _matrix.data[2]; this->data[3] += _matrix.data[3]; this->data[4] += _matrix.data[4]; this->data[5] += _matrix.data[5]; this->data[6] += _matrix.data[6]; this->data[7] += _matrix.data[7]; this->data[8] += _matrix.data[8]; } void Matrix3::operator*=(const real _scalar) { this->data[0] *= _scalar; this->data[1] *= _scalar; this->data[2] *= _scalar; this->data[3] *= _scalar; this->data[4] *= _scalar; this->data[5] *= _scalar; this->data[6] *= _scalar; this->data[7] *= _scalar; this->data[8] *= _scalar; } void Matrix3::setInverse(const Matrix3 &_matrix) { real t4 = _matrix.data[0]*_matrix.data[4]; real t6 = _matrix.data[0]*_matrix.data[5]; real t8 = _matrix.data[1]*_matrix.data[3]; real t10 = _matrix.data[2]*_matrix.data[3]; real t12 = _matrix.data[1]*_matrix.data[6]; real t14 = _matrix.data[2]*_matrix.data[6]; // calculate the determinant. real t16 = (t4*_matrix.data[8] - t6*_matrix.data[7] - t8*_matrix.data[8] + t10*_matrix.data[7] + t12*_matrix.data[5] - t14*_matrix.data[4]); // make sure the determinant is non-zer_matrix if (t16 == (real)0.0f) { return; } real t17 = 1/t16; this->data[0] = (_matrix.data[4]*_matrix.data[8]-_matrix.data[5]*_matrix.data[7])*t17; this->data[1] = -(_matrix.data[1]*_matrix.data[8]-_matrix.data[2]*_matrix.data[7])*t17; this->data[2] = (_matrix.data[1]*_matrix.data[5]-_matrix.data[2]*_matrix.data[4])*t17; this->data[3] = -(_matrix.data[3]*_matrix.data[8]-_matrix.data[5]*_matrix.data[6])*t17; this->data[4] = (_matrix.data[0]*_matrix.data[8]-t14)*t17; this->data[5] = -(t6-t10)*t17; this->data[6] = (_matrix.data[3]*_matrix.data[7]-_matrix.data[4]*_matrix.data[6])*t17; this->data[7] = -(_matrix.data[0]*_matrix.data[7]-t12)*t17; this->data[8] = (t4-t8)*t17; } Matrix3 Matrix3::inverse() const { Matrix3 matrix; matrix.setInverse(*this); return matrix; } void Matrix3::invert() { this->setInverse(*this); } void Matrix3::setTranspose(const Matrix3 &_matrix) { this->data[0] = _matrix.data[0]; this->data[1] = _matrix.data[3]; this->data[2] = _matrix.data[6]; this->data[3] = _matrix.data[1]; this->data[4] = _matrix.data[4]; this->data[5] = _matrix.data[7]; this->data[6] = _matrix.data[2]; this->data[7] = _matrix.data[5]; this->data[8] = _matrix.data[8]; } Matrix3 Matrix3::transpose() const { Matrix3 matrix; matrix.setTranspose(*this); return matrix; } void Matrix3::setOrientation(const Quaternion &_quaternion) { this->data[0] = 1 - (2*_quaternion.j*_quaternion.j + 2*_quaternion.k*_quaternion.k); this->data[1] = 2*_quaternion.i*_quaternion.j + 2*_quaternion.k*_quaternion.r; this->data[2] = 2*_quaternion.i*_quaternion.k - 2*_quaternion.j*_quaternion.r; this->data[3] = 2*_quaternion.i*_quaternion.j - 2*_quaternion.k*_quaternion.r; this->data[4] = 1 - (2*_quaternion.i*_quaternion.i + 2*_quaternion.k*_quaternion.k); this->data[5] = 2*_quaternion.j*_quaternion.k + 2*_quaternion.i*_quaternion.r; this->data[6] = 2*_quaternion.i*_quaternion.k + 2*_quaternion.j*_quaternion.r; this->data[7] = 2*_quaternion.j*_quaternion.k - 2*_quaternion.i*_quaternion.r; this->data[8] = 1 - (2*_quaternion.i*_quaternion.i + 2*_quaternion.j*_quaternion.j); } Vector3 Matrix3::transform(const Vector3 &_vector) const { return (*this) * _vector; } void Matrix3::setComponents(const Vector3 &_compOne, const Vector3 &_compTwo, const Vector3 &_compThree) { this->data[0] = _compOne.x; this->data[1] = _compTwo.x; this->data[2] = _compThree.x; this->data[3] = _compOne.y; this->data[4] = _compTwo.y; this->data[5] = _compThree.y; this->data[6] = _compOne.z; this->data[7] = _compTwo.z; this->data[8] = _compThree.z; }; Vector3 Matrix3::transformTranspose(const Vector3 & _vector) const { return Vector3(_vector.x * this->data[0] + _vector.y * this->data[3] + _vector.z * this->data[6], _vector.x * this->data[1] + _vector.y * this->data[4] + _vector.z * this->data[7], _vector.x * this->data[2] + _vector.y * this->data[5] + _vector.z * this->data[8] ); } void Matrix3::setSkewSymmetric(const Vector3 &_vector) { this->data[0] = this->data[4] = this->data[8] = 0; this->data[1] = -_vector.z; this->data[2] = _vector.y; this->data[3] = _vector.z; this->data[5] = -_vector.x; this->data[6] = -_vector.y; this->data[7] = _vector.x; } // Sets the value of the matrix as an inertia tensor of // a rectangular block aligned with the body's coordinate // system with the given axis half-sizes and mass. void Matrix3::setBlockInertiaTensor(const Vector3 &_halfSizes, real _mass) { Vector3 squares = _halfSizes.componentProduct(_halfSizes); this->setInertiaTensorCoeffs(0.3f*_mass*(squares.y + squares.z), 0.3f*_mass*(squares.x + squares.z), 0.3f*_mass*(squares.x + squares.y)); } // sets the value of the matrix from inertia tensor values void Matrix3::setInertiaTensorCoeffs(real _ix, real _iy, real _iz, real _ixy, real _ixz, real _iyz) { this->data[0] = _ix; this->data[1] = this->data[3] = -_ixy; this->data[2] = this->data[6] = -_ixz; this->data[4] = _iy; this->data[5] = this->data[7] = -_iyz; this->data[8] = _iz; } /***************************** Matrix4 *****************************/ Matrix4::Matrix4() { this->data[1] = this->data[2] = this->data[3] = this->data[4] = this->data[6] = this->data[7] = this->data[8] = this->data[9] = this->data[11] = 0; this->data[0] = this->data[5] = this->data[10] = 1; } Matrix4::Matrix4(real _c0, real _c1, real _c2, real _c3, real _c4, real _c5, real _c6, real _c7, real _c8, real _c9, real _c10, real _c11) { this->data[0] = _c0; this->data[1] = _c1; this->data[2] = _c2; this->data[3] = _c3; this->data[4] = _c4; this->data[5] = _c5; this->data[6] = _c6; this->data[7] = _c7; this->data[8] = _c8; this->data[9] = _c9; this->data[10] = _c10; this->data[11] = _c11; } real Matrix4::getDeterminant() const { return this->data[8]*this->data[5]*this->data[2]+ this->data[4]*this->data[9]*this->data[2]+ this->data[8]*this->data[1]*this->data[6]- this->data[0]*this->data[9]*this->data[6]- this->data[4]*this->data[1]*this->data[10]+ this->data[0]*this->data[5]*this->data[10]; } void Matrix4::setOrientationAndPos(const Quaternion &_quaternion, const Vector3 &_pos) { this->data[0] = 1 - (2*_quaternion.j*_quaternion.j + 2*_quaternion.k*_quaternion.k); this->data[1] = 2*_quaternion.i*_quaternion.j + 2*_quaternion.k*_quaternion.r; this->data[2] = 2*_quaternion.i*_quaternion.k - 2*_quaternion.j*_quaternion.r; this->data[3] = _pos.x; this->data[4] = 2*_quaternion.i*_quaternion.j - 2*_quaternion.k*_quaternion.r; this->data[5] = 1 - (2*_quaternion.i*_quaternion.i + 2*_quaternion.k*_quaternion.k); this->data[6] = 2*_quaternion.j*_quaternion.k + 2*_quaternion.i*_quaternion.r; this->data[7] = _pos.y; this->data[8] = 2*_quaternion.i*_quaternion.k + 2*_quaternion.j*_quaternion.r; this->data[9] = 2*_quaternion.j*_quaternion.k - 2*_quaternion.i*_quaternion.r; this->data[10] = 1 - (2*_quaternion.i*_quaternion.i + 2*_quaternion.j*_quaternion.j); this->data[11] = _pos.z; } void Matrix4::setInverse(const Matrix4 &_matrix) { // make sure the determinant is non-zero. real det = this->getDeterminant(); if (det == 0) { return; } det = ((real)1.0)/det; this->data[0] = (-_matrix.data[9]*_matrix.data[6]+_matrix.data[5]*_matrix.data[10])*det; this->data[4] = (_matrix.data[8]*_matrix.data[6]-_matrix.data[4]*_matrix.data[10])*det; this->data[8] = (-_matrix.data[8]*_matrix.data[5]+_matrix.data[4]*_matrix.data[9])*det; this->data[1] = (_matrix.data[9]*_matrix.data[2]-_matrix.data[1]*_matrix.data[10])*det; this->data[5] = (-_matrix.data[8]*_matrix.data[2]+_matrix.data[0]*_matrix.data[10])*det; this->data[9] = (_matrix.data[8]*_matrix.data[1]-_matrix.data[0]*_matrix.data[9])*det; this->data[2] = (-_matrix.data[5]*_matrix.data[2]+_matrix.data[1]*_matrix.data[6])*det; this->data[6] = (+_matrix.data[4]*_matrix.data[2]-_matrix.data[0]*_matrix.data[6])*det; this->data[10] = (-_matrix.data[4]*_matrix.data[1]+_matrix.data[0]*_matrix.data[5])*det; this->data[3] = (_matrix.data[9]*_matrix.data[6]*_matrix.data[3] -_matrix.data[5]*_matrix.data[10]*_matrix.data[3] -_matrix.data[9]*_matrix.data[2]*_matrix.data[7] +_matrix.data[1]*_matrix.data[10]*_matrix.data[7] +_matrix.data[5]*_matrix.data[2]*_matrix.data[11] -_matrix.data[1]*_matrix.data[6]*_matrix.data[11])*det; this->data[7] = (-_matrix.data[8]*_matrix.data[6]*_matrix.data[3] +_matrix.data[4]*_matrix.data[10]*_matrix.data[3] +_matrix.data[8]*_matrix.data[2]*_matrix.data[7] -_matrix.data[0]*_matrix.data[10]*_matrix.data[7] -_matrix.data[4]*_matrix.data[2]*_matrix.data[11] +_matrix.data[0]*_matrix.data[6]*_matrix.data[11])*det; this->data[11] =(_matrix.data[8]*_matrix.data[5]*_matrix.data[3] -_matrix.data[4]*_matrix.data[9]*_matrix.data[3] -_matrix.data[8]*_matrix.data[1]*_matrix.data[7] +_matrix.data[0]*_matrix.data[9]*_matrix.data[7] +_matrix.data[4]*_matrix.data[1]*_matrix.data[11] -_matrix.data[0]*_matrix.data[5]*_matrix.data[11])*det;} Matrix4 Matrix4::inverse() const { Matrix4 matrix; matrix.setInverse(*this); return matrix; } void Matrix4::invert() { this->setInverse(*this); } Matrix4 Matrix4::operator*(const Matrix4 &_matrix) const { Matrix4 matrix; matrix.data[0] = (_matrix.data[0]*this->data[0]) + (_matrix.data[4]*this->data[1]) + (_matrix.data[8]*this->data[2]); matrix.data[4] = (_matrix.data[0]*this->data[4]) + (_matrix.data[4]*this->data[5]) + (_matrix.data[8]*this->data[6]); matrix.data[8] = (_matrix.data[0]*this->data[8]) + (_matrix.data[4]*this->data[9]) + (_matrix.data[8]*this->data[10]); matrix.data[1] = (_matrix.data[1]*this->data[0]) + (_matrix.data[5]*this->data[1]) + (_matrix.data[9]*this->data[2]); matrix.data[5] = (_matrix.data[1]*this->data[4]) + (_matrix.data[5]*this->data[5]) + (_matrix.data[9]*this->data[6]); matrix.data[9] = (_matrix.data[1]*this->data[8]) + (_matrix.data[5]*this->data[9]) + (_matrix.data[9]*this->data[10]); matrix.data[2] = (_matrix.data[2]*this->data[0]) + (_matrix.data[6]*this->data[1]) + (_matrix.data[10]*this->data[2]); matrix.data[6] = (_matrix.data[2]*this->data[4]) + (_matrix.data[6]*this->data[5]) + (_matrix.data[10]*this->data[6]); matrix.data[10] = (_matrix.data[2]*this->data[8]) + (_matrix.data[6]*this->data[9]) + (_matrix.data[10]*this->data[10]); matrix.data[3] = (_matrix.data[3]*this->data[0]) + (_matrix.data[7]*this->data[1]) + (_matrix.data[11]*this->data[2]) + this->data[3]; matrix.data[7] = (_matrix.data[3]*this->data[4]) + (_matrix.data[7]*this->data[5]) + (_matrix.data[11]*this->data[6]) + this->data[7]; matrix.data[11] = (_matrix.data[3]*this->data[8]) + (_matrix.data[7]*this->data[9]) + (_matrix.data[11]*this->data[10]) + this->data[11]; return matrix; } Vector3 Matrix4::operator*(const Vector3 &_vector) const { return Vector3(_vector.x * this->data[0] + _vector.y * this->data[1] + _vector.z * this->data[2] + this->data[3], _vector.x * this->data[4] + _vector.y * this->data[5] + _vector.z * this->data[6] + this->data[7], _vector.x * this->data[8] + _vector.y * this->data[9] + _vector.z * this->data[10] + this->data[11] ); } Vector3 Matrix4::transformInverse(const Vector3 &_vector) const { Vector3 tmp(_vector.x, _vector.y, _vector.z); tmp.x -= this->data[3]; tmp.y -= this->data[7]; tmp.z -= this->data[11]; return Vector3(tmp.x * this->data[0] + tmp.y * this->data[4] + tmp.z * this->data[8], tmp.x * this->data[1] + tmp.y * this->data[5] + tmp.z * this->data[9], tmp.x * this->data[2] + tmp.y * this->data[6] + tmp.z * this->data[10] ); } Vector3 Matrix4::localToWorld(const Vector3 &_local, const Matrix4 &_transform) { return _transform.transform(_local); } Vector3 Matrix4::transform(const Vector3 &_vector) const { return (*this) * _vector; } Vector3 Matrix4::worldToLocal(const Vector3 &_world, const Matrix4 &_transform) { return _transform.transformInverse(_world); } Vector3 Matrix4::transformDirection(const Vector3 &_vector) const { return Vector3(_vector.x * this->data[0] + _vector.y * this->data[1] + _vector.z * this->data[2], _vector.x * this->data[4] + _vector.y * this->data[5] + _vector.z * this->data[6], _vector.x * this->data[8] + _vector.y * this->data[9] + _vector.z * this->data[10] ); } Vector3 Matrix4::transformInverseDirection(const Vector3 &_vector) const { return Vector3(_vector.x * this->data[0] + _vector.y * this->data[4] + _vector.z * this->data[8], _vector.x * this->data[1] + _vector.y * this->data[5] + _vector.z * this->data[9], _vector.x * this->data[2] + _vector.y * this->data[6] + _vector.z * this->data[10] ); } Vector3 Matrix4::localToWorldDirn(const Vector3 &_local, const Matrix4 &_transform) { return _transform.transformDirection(_local); } Vector3 Matrix4::worldToLocalDirn(const Vector3 &_world, const Matrix4 &_transform) { return _transform.transformInverseDirection(_world); } // gets a vector representing one axis, one column, in matrix. // row 3 corresponds to the position of the transform matrix. Vector3 Matrix4::getAxisVector(int _i) const { return Vector3(this->data[_i], this->data[_i+4], this->data[_i+8]); } /***************************** Matrix4x4 *****************************/ Matrix4x4::Matrix4x4() { this->data[1] = this->data[2] = this->data[3] = this->data[4] = this->data[6] = this->data[7] = this->data[8] = this->data[9] = this->data[11] = this->data[12] = this->data[13] = this->data[14] = 0; this->data[0] = this->data[5] = this->data[10] = this->data[15] = 1; } Matrix4x4::Matrix4x4(real _matrix[16]) { for (int i=0; i<16; i++) { this->data[i] = _matrix[i]; } } /***************************** Quaternion *****************************/ Quaternion::Quaternion() { this->r = 0.0f; this->i = 0.0f; this->j = 0.0f; this->k = 0.0f; } Quaternion::Quaternion(real _r, real _i, real _j, real _k) { this->r = _r; this->i = _i; this->j = _j; this->k = _k; } void Quaternion::normalize() { real d = this->r*this->r + this->i*this->i + this->j*this->j + this->k*this->k; // check for zero length quaternion, and use the no-rotation quaternion in that case. if (d == 0) { this->r = 1; return; } d = ((real)1.0)/real_sqrt(d); this->r *= d; this->i *= d; this->j *= d; this->k *= d; } void Quaternion::operator*=(const Quaternion &_quaternion) { this->r = this->r*_quaternion.r - this->i*_quaternion.i - this->j*_quaternion.j - this->k*_quaternion.k; this->i = this->r*_quaternion.i + this->i*_quaternion.r + this->j*_quaternion.k - this->k*_quaternion.j; this->j = this->r*_quaternion.j + this->j*_quaternion.r + this->k*_quaternion.i - this->i*_quaternion.k; this->k = this->r*_quaternion.k + this->k*_quaternion.r + this->i*_quaternion.j - this->j*_quaternion.i; } void Quaternion::rotateByVector(const Vector3 &_vector) { Quaternion quaternion(0, _vector.x, _vector.y, _vector.z); (*this) *= quaternion; } void Quaternion::addScaledVector(const Vector3 &_vector, real _scale) { Quaternion quaternion(0 ,_vector.x * _scale, _vector.y * _scale, _vector.z * _scale); quaternion *= (*this); this->r += quaternion.r * ((real)0.5); this->i += quaternion.i * ((real)0.5); this->j += quaternion.j * ((real)0.5); this->k += quaternion.k * ((real)0.5); } /***************************** Camera *****************************/ Camera::Camera() { this->eyeX = 0.0f; this->eyeY = 1.0f; this->eyeZ = 2.0f; this->centerX = 0.0f; this->centerY = 0.0f; this->centerZ = 0.0f; this->upX = 0.0f; this->upY = 1.0f; this->upZ = 0.0f; this->fovyRadians = DEGREES_TO_RADIANS(60.0f); this->nearZ = 0.1f; this->farZ = 10.0f; } void Camera::resetCamera() { this->eyeX = 0.0f; this->eyeY = 1.0f; this->eyeZ = 2.0f; this->centerX = 0.0f; this->centerY = 0.0f; this->centerZ = 0.0f; this->lookAtMatrix = MatrixMakeLookAt(this->eyeX, this->eyeY, this->eyeZ, this->centerX, this->centerY, this->centerZ, this->upX, this->upY, this->upZ); } void Camera::rotateCamera(real _radians) { static int ang = 0; const static float radius = 3; this->eyeX = (radius * cos(M_PI * ang / 180.0f)); this->centerX = -this->eyeX; this->eyeZ = (radius * sin(M_PI * ang / 180.0f)); this->centerZ = -this->eyeZ; if (_radians < 0) { ang-=1; } else { ang+=1; } this->lookAtMatrix = MatrixMakeLookAt(this->eyeX, this->eyeY, this->eyeZ, this->centerX, this->centerY, this->centerZ, this->upX, this->upY, this->upZ); } void Camera::updatePerspective(real _aspect) { #if defined (_3D_) this->perspectiveMatrix = MatrixMakePerspective(this->fovyRadians, _aspect, this->nearZ, this->farZ); this->lookAtMatrix = MatrixMakeLookAt(this->eyeX, this->eyeY, this->eyeZ, this->centerX, this->centerY, this->centerZ, this->upX, this->upY, this->upZ); #else MatrixOrtho(this->orthoMatrix, -_aspect, _aspect, -1, 1, -1, 1); #endif } void Camera::zoom(real _scale, real _value) { #if defined (_3D_) this->eyeZ = _scale; this->lookAtMatrix = MatrixMakeLookAt(this->eyeX, this->eyeY, this->eyeZ, this->centerX, this->centerY, this->centerZ, this->upX, this->upY, this->upZ); #else MatrixOrtho(this->orthoMatrix, -_value, _value, _scale, _scale, -1, 1); #endif } void Camera::pan(real _scaleX, real _scaleY, real _aspect) { this->eyeX = _scaleX; this->eyeY = _scaleY; #if defined (_3D_) this->lookAtMatrix = MatrixMakeLookAt(this->eyeX, this->eyeY, this->eyeZ, this->centerX, this->centerY, this->centerZ, this->upX, this->upY, this->upZ); #else MatrixOrtho(this->orthoMatrix, (-_aspect - _scaleX), (_aspect - _scaleX), (-1 -_scaleY), (1 - _scaleY), -1, 1); #endif }
32.610723
141
0.5698
[ "vector", "transform" ]
9a2585e2213c9529f0d818bad101942fae490506
4,122
cpp
C++
tutorials/advanced/utils/src/save_image.cpp
adityak2920/pytorch-cpp
1b087742f8aaaad1a3f10880e35aaf7f93425eef
[ "MIT" ]
null
null
null
tutorials/advanced/utils/src/save_image.cpp
adityak2920/pytorch-cpp
1b087742f8aaaad1a3f10880e35aaf7f93425eef
[ "MIT" ]
null
null
null
tutorials/advanced/utils/src/save_image.cpp
adityak2920/pytorch-cpp
1b087742f8aaaad1a3f10880e35aaf7f93425eef
[ "MIT" ]
null
null
null
// Copyright 2020-present pytorch-cpp Authors #include "save_image.h" #include <torch/torch.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" namespace image_utils { namespace { void norm_ip(torch::Tensor img, double min, double max) { img.clamp_(min, max); img.sub_(min).div_(max - min + 1e-5); } void norm_range(torch::Tensor t, const std::vector<double>& range) { if (range.empty()) { norm_ip(t, t.min().item<double>(), t.max().item<double>()); } else if (range.size() == 2) { norm_ip(t, range[0], range[1]); } else { throw std::invalid_argument("Range must either be empty or contain exactly 2 elements."); } } // Makes a grid of images // // Translated from source python code at // https://pytorch.org/docs/stable/_modules/torchvision/utils.html#make_grid torch::Tensor make_grid(torch::Tensor tensor, int64_t nrow, int64_t padding, bool normalize, const std::vector<double>& range, bool scale_each, torch::Scalar pad_value) { if (tensor.dim() == 2) { tensor = tensor.unsqueeze(0); } if (tensor.dim() == 3) { if (tensor.size(0) == 1) { tensor = torch::cat({tensor, tensor, tensor}, 0); } tensor = tensor.unsqueeze(0); } if (tensor.dim() == 4 && tensor.size(1) == 1) { tensor = torch::cat({tensor, tensor, tensor}, 1); } tensor = tensor.to(torch::kFloat32); if (normalize) { if (scale_each) { auto mini_batches = tensor.chunk(tensor.size(1), 1); for_each(mini_batches.begin(), mini_batches.end(), [&range] (auto& t) { norm_range(t, range); }); } else { norm_range(tensor, range); } } if (tensor.size(0) == 1) { return tensor.squeeze(0); } auto nmaps = tensor.size(0); auto xmaps = std::min(nrow, nmaps); auto ymaps = static_cast<int64_t>(std::ceil(static_cast<double>(nmaps) / xmaps)); auto height = tensor.size(2) + padding; auto width = tensor.size(3) + padding; auto num_channels = tensor.size(1); auto grid = torch::full({num_channels, height * ymaps + padding, width * xmaps + padding}, pad_value); int64_t k = 0; for (int64_t y = 0; y != ymaps; ++y) { for (int64_t x = 0; x != xmaps; ++x) { if (k >= nmaps) { break; } grid.narrow(1, y * height + padding, height - padding) .narrow(2, x * width + padding, width - padding) .copy_(tensor[k]); ++k; } } return grid; } } // namespace // Saves a tensor to an image file. // // Translated (and slightly modified) from source python code at // https://pytorch.org/docs/stable/_modules/torchvision/utils.html#save_image void save_image(torch::Tensor tensor, const std::string& file_path, int64_t nrow, int64_t padding, bool normalize, const std::vector<double>& range, bool scale_each, torch::Scalar pad_value, ImageFormat format) { auto grid = make_grid(tensor, nrow, padding, normalize, range, scale_each, pad_value) .mul(255) .add_(0.5) .clamp_(0, 255) .permute({1, 2, 0}) .to(torch::kCPU, torch::kUInt8); switch (format) { case ImageFormat::PNG: stbi_write_png(file_path.c_str(), grid.size(1), grid.size(0), grid.size(2), grid.data_ptr(), grid.stride(0)); break; case ImageFormat::BMP: stbi_write_bmp(file_path.c_str(), grid.size(1), grid.size(0), grid.size(2), grid.data_ptr()); break; case ImageFormat::JPG: stbi_write_jpg(file_path.c_str(), grid.size(1), grid.size(0), grid.size(2), grid.data_ptr(), 100); break; default: throw std::runtime_error("Unknown file format."); } } } // namespace image_utils
34.932203
113
0.556769
[ "vector" ]
9a27a68b266cc83ae331e196dd56a0e524fc42d6
1,354
hpp
C++
modules/slideio/include/opencv2/slideio/svssmallscene.hpp
Booritas/opencv_slideio
86789b833cb5411c71757e7a1d49d481b1b905cd
[ "BSD-3-Clause" ]
null
null
null
modules/slideio/include/opencv2/slideio/svssmallscene.hpp
Booritas/opencv_slideio
86789b833cb5411c71757e7a1d49d481b1b905cd
[ "BSD-3-Clause" ]
null
null
null
modules/slideio/include/opencv2/slideio/svssmallscene.hpp
Booritas/opencv_slideio
86789b833cb5411c71757e7a1d49d481b1b905cd
[ "BSD-3-Clause" ]
null
null
null
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_slideio_svssmallscene_HPP #define OPENCV_slideio_svssmallscene_HPP #include "opencv2/slideio/svsscene.hpp" #include "opencv2/slideio/tifftools.hpp" namespace cv { namespace slideio { class CV_EXPORTS SVSSmallScene : public SVSScene { public: SVSSmallScene( const std::string& filePath, const std::string& name, const slideio::TiffDirectory& dir, TIFF* hfile); cv::Rect getRect() const override; int getNumChannels() const override; slideio::DataType getChannelDataType(int channel) const override; slideio::Resolution getResolution() const override; double getMagnification() const override; void readResampledBlockChannels(const cv::Rect& blockRect, const cv::Size& blockSize, const std::vector<int>& channelIndices, cv::OutputArray output) override; private: slideio::TiffDirectory m_directory; slideio::DataType m_dataType; double m_magnification; TIFF* m_hFile; }; } } #endif
36.594595
137
0.643279
[ "vector" ]
9a317228e97eae9cfe0de412c2d6fefee84ff11c
15,782
cpp
C++
pixelview.cpp
msgmaxim/cp-profiler
6b5327445fb0b62eef607795100d1822af457fab
[ "MIT-feh" ]
null
null
null
pixelview.cpp
msgmaxim/cp-profiler
6b5327445fb0b62eef607795100d1822af457fab
[ "MIT-feh" ]
null
null
null
pixelview.cpp
msgmaxim/cp-profiler
6b5327445fb0b62eef607795100d1822af457fab
[ "MIT-feh" ]
1
2020-04-12T02:44:51.000Z
2020-04-12T02:44:51.000Z
/* 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 "pixelview.hh" #include <chrono> #include <cmath> using namespace std::chrono; /// ******* PIXEL_TREE_DIALOG ******** PixelTreeDialog::PixelTreeDialog(TreeCanvas* tc) : QDialog(tc) { this->resize(600, 400); /// set Title this->setWindowTitle(QString::fromStdString(tc->getTitle())); qDebug() << "title: " << tc->getTitle().c_str(); setLayout(&layout); layout.addWidget(&scrollArea); layout.addLayout(&controlLayout); controlLayout.addWidget(&scaleDown); controlLayout.addWidget(&scaleUp); scaleUp.setText("+"); scaleDown.setText("-"); QLabel* compLabel = new QLabel("compression"); compLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); controlLayout.addWidget(compLabel); controlLayout.addWidget(&compressionSB); compressionSB.setMinimum(1); compressionSB.setMaximum(10000); canvas = new PixelTreeCanvas(&scrollArea, tc); connect(&scaleDown, SIGNAL(clicked()), canvas, SLOT(scaleDown())); connect(&scaleUp, SIGNAL(clicked()), canvas, SLOT(scaleUp())); QObject::connect(&compressionSB, SIGNAL(valueChanged(int)), canvas, SLOT(compressionChanged(int))); setAttribute(Qt::WA_QuitOnClose, true); setAttribute(Qt::WA_DeleteOnClose, true); } PixelTreeDialog::~PixelTreeDialog(void) { delete canvas; } PixelTreeCanvas::~PixelTreeCanvas(void) { freePixelList(pixelList); delete _image; delete [] time_arr; delete [] domain_arr; delete [] domain_red_arr; } /// *********************************** /// ******** PIXEL_TREE_CANVAS ******** PixelTreeCanvas::PixelTreeCanvas(QWidget* parent, TreeCanvas* tc) : QWidget(parent), _tc(tc), _na(tc->na) { _sa = static_cast<QAbstractScrollArea*>(parentWidget()); _vScrollBar = _sa->verticalScrollBar(); _nodeCount = tc->stats.solutions + tc->stats.failures + tc->stats.choices + tc->stats.undetermined; max_depth = tc->stats.maxDepth; // if (_tc->getData()->isRestarts()) { // max_depth++; /// consider the first, dummy node // _nodeCount++; // } _image = nullptr; /// scrolling business _sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); _sa->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); _sa->setAutoFillBackground(true); drawPixelTree(); actuallyDraw(); pixmap.fromImage(*_image); qlabel.setPixmap(pixmap); qlabel.show(); } void PixelTreeCanvas::paintEvent(QPaintEvent*) { QPainter painter(this); actuallyDraw(); painter.drawImage(0, 0, *_image); } void PixelTreeCanvas::constructTree(void) { /// the depth is max_depth /// the width is _nodeCount / approx_size freePixelList(pixelList); vlines = ceil((float)_nodeCount / approx_size); std::cerr << "vlines: " << vlines << "\n"; delete [] time_arr; time_arr = new float[vlines]; // TODO: "Uninitialised value was created by a heap allocation" delete [] domain_arr; domain_arr = new float[vlines]; // TODO: "Uninitialised value was created by a heap allocation" delete [] domain_red_arr; domain_red_arr = new float[vlines]; // TODO: "Uninitialised value was created by a heap allocation" pixelList.resize(vlines); /// get a root VisualNode* root = (*_na)[0]; vline_idx = 0; node_idx = 0; group_size = 0; group_domain = 0; group_domain_red = 0; group_size_nonempty = 0; alpha_factor = 100.0 / approx_size; exploreNext(root, 1); flush(); } void PixelTreeCanvas::freePixelList(std::vector<std::list<PixelData*>>& pixelList) { for (auto& l : pixelList) { for (auto& nodeData : l) { delete nodeData; } l.clear(); } pixelList.clear(); } void PixelTreeCanvas::actuallyDraw() { delete _image; _sa->horizontalScrollBar()->setRange(0, vlines * _step - _sa->width() + 100); _sa->verticalScrollBar()->setRange(0, max_depth * _step + 4 * (HIST_HEIGHT + MARGIN + _step) - _sa->height()); // 4 histograms int xoff = _sa->horizontalScrollBar()->value(); int yoff = _sa->verticalScrollBar()->value(); unsigned int leftmost_x = xoff; unsigned int rightmost_x = xoff + _sa->width(); pt_height = max_depth * _step_y; if (rightmost_x > pixelList.size() * _step) { rightmost_x = pixelList.size() * _step; } int img_height = MARGIN + pt_height + _step + MARGIN + HIST_HEIGHT + _step + /// Time Histogram MARGIN + HIST_HEIGHT + _step + /// Domain Histogram MARGIN + HIST_HEIGHT + _step + /// Domain Reduction Histogram MARGIN + HIST_HEIGHT + _step + /// Node Rate Histogram MARGIN; _image = new QImage(rightmost_x - leftmost_x + _step, img_height, QImage::Format_RGB888); _image->fill(qRgb(255, 255, 255)); this->resize(_image->width(), _image->height()); unsigned leftmost_vline = leftmost_x / _step; unsigned rightmost_vline = rightmost_x / _step; int* intencity_arr = new int[max_depth + 1]; int node_idx = 0; for (unsigned int vline = leftmost_vline; vline < rightmost_vline; vline++) { if (!pixelList[vline].empty()) { memset(intencity_arr, 0, (max_depth + 1)* sizeof(int)); for (auto& pixel : pixelList[vline]) { int xpos = (vline - leftmost_vline) * _step; int ypos = pixel->depth() * _step_y - yoff; intencity_arr[pixel->depth()]++; /// draw pixel itself: if (ypos > 0) { if (!pixel->node()->isSelected()) { int alpha = intencity_arr[pixel->depth()] * alpha_factor; drawPixel(xpos, ypos, QColor::fromHsv(150, 100, 100 - alpha).rgba()); } else { // drawPixel(xpos, ypos, qRgb(255, 0, 0)); drawPixel(xpos, ypos, qRgb(255, 0, 255)); } } /// draw green vertical line if solved: if (pixel->node()->getStatus() == SOLVED) { for (unsigned j = 0; j < pt_height - yoff; j++) if (_image->pixel(xpos, j) == qRgb(255, 255, 255)) for (unsigned i = 0; i < _step; i++) _image->setPixel(xpos + i, j, qRgb(0, 255, 0)); } node_idx++; } } } delete [] intencity_arr; /// All Histograms // drawTimeHistogram(leftmost_vline, rightmost_vline); // drawDomainHistogram(leftmost_vline, rightmost_vline); // drawDomainReduction(leftmost_vline, rightmost_vline); // drawNodeRate(leftmost_vline, rightmost_vline); } void PixelTreeCanvas::drawPixelTree(void) { high_resolution_clock::time_point time_begin = high_resolution_clock::now(); constructTree(); high_resolution_clock::time_point time_end = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(time_end - time_begin); std::cout << "Pixel Tree construction took: " << time_span.count() << " seconds." << std::endl; } void PixelTreeCanvas::flush(void) { if (group_size == 0) return; if (group_size_nonempty == 0) { group_domain = -1; group_domain_red = -1; group_time = -1; } else { group_domain = group_domain / group_size_nonempty; group_domain_red = group_domain_red / group_size_nonempty; } domain_arr[vline_idx] = group_domain; domain_red_arr[vline_idx] = group_domain_red; time_arr[vline_idx] = group_time; } void PixelTreeCanvas::exploreNext(VisualNode* node, unsigned depth) { // Data* data = _tc->getData(); DbEntry* entry = _tc->getEntry(node->getIndex(*_na)); DbEntry* parent = nullptr; assert(depth <= max_depth); if (vline_idx >= pixelList.size()) return; pixelList[vline_idx].push_back(new PixelData(node_idx, node, depth)); if (!entry) { // qDebug() << "entry (idx " << node->getIndex(*_na) << ") does not exist"; } else { group_size_nonempty++; if (entry->parent_sid != ~0u) { parent = _tc->getEntry(node->getParent()); if (parent) /// need this for restarts group_domain_red += parent->domain - entry->domain; } group_time += entry->node_time; group_domain += entry->domain; } group_size++; if (group_size == approx_size) { /// get average domain size for the group if (group_size_nonempty == 0) { group_domain = -1; group_domain_red = -1; group_time = -1; } else { group_domain = group_domain / group_size_nonempty; group_domain_red = group_domain_red / group_size_nonempty; } time_arr[vline_idx] = group_time; domain_arr[vline_idx] = group_domain; domain_red_arr[vline_idx] = group_domain_red; vline_idx++; std::cerr << "increased vline_idx to " << vline_idx << " where vlines is " << vlines << "\n"; group_size = 0; group_time = 0; group_domain = 0; group_domain_red = 0; group_size_nonempty = 0; } node_idx++; uint kids = node->getNumberOfChildren(); for (uint i = 0; i < kids; ++i) { exploreNext(node->getChild(*_na, i), depth + 1); } } /// Draw time histogram underneath the pixel tree void PixelTreeCanvas::drawTimeHistogram(unsigned l_vline, unsigned r_vline) { drawHistogram(0, time_arr, l_vline, r_vline, qRgb(150, 150, 40)); } void PixelTreeCanvas::drawDomainHistogram(unsigned l_vline, unsigned r_vline) { drawHistogram(1, domain_arr, l_vline, r_vline, qRgb(150, 40, 150)); } void PixelTreeCanvas::drawDomainReduction(unsigned l_vline, unsigned r_vline) { drawHistogram(2, domain_red_arr, l_vline, r_vline, qRgb(40, 150, 150)); } void PixelTreeCanvas::drawHistogram(int idx, float* data, unsigned l_vline, unsigned r_vline, int color) { /// coordinates for the top-left corner int init_x = 0; int yoff = _sa->verticalScrollBar()->value(); int y = (pt_height + _step) + MARGIN + idx * (HIST_HEIGHT + MARGIN + _step) - yoff; /// work out maximum value int max_value = 0; for (unsigned i = 0; i < vlines; i++) { if (data[i] > max_value) max_value = data[i]; } if (max_value <= 0) return; /// no data for this histogram float coeff = (float)HIST_HEIGHT / max_value; int zero_level = y + HIST_HEIGHT + _step; for (unsigned i = l_vline; i < r_vline; i++) { int val = data[i] * coeff; /// horizontal line for 0 level for (unsigned j = 0; j < _step; j++) _image->setPixel(init_x + (i - l_vline) * _step + j, zero_level, qRgb(150, 150, 150)); // qDebug() << "data[" << i << "]: " << data[i]; // if (data[i] < 0) continue; for (int v = val; v >= 0; v--) { drawPixel(init_x + (i - l_vline) * _step, y + HIST_HEIGHT - v, color); } } } void PixelTreeCanvas::drawNodeRate(unsigned l_vline, unsigned r_vline) { Data* data = _tc->getExecution()->getData(); std::vector<float>& node_rate = data->node_rate; std::vector<int>& nr_intervals = data->nr_intervals; int start_x = 0; int start_y = (pt_height + _step) + MARGIN + 3 * (HIST_HEIGHT + MARGIN + _step); float max_node_rate = *std::max_element(node_rate.begin(), node_rate.end()); float coeff = (float)HIST_HEIGHT / max_node_rate; int zero_level = start_y + HIST_HEIGHT + _step; // / this is very slow for (unsigned i = l_vline; i < r_vline; i++) { for (unsigned j = 0; j < _step; j++) _image->setPixel(start_x + (i - l_vline) * _step + j, zero_level, qRgb(150, 150, 150)); } for (unsigned i = 1; i < nr_intervals.size(); i++) { float value = node_rate[i - 1] * coeff; unsigned i_begin = ceil((float)nr_intervals[i-1] / approx_size); unsigned i_end = ceil((float)nr_intervals[i] / approx_size); /// draw this interval? if (i_end < l_vline || i_begin > r_vline) continue; if (i_begin < l_vline) i_begin = l_vline; if (i_end > r_vline) i_end = r_vline; /// this is very slow // for (unsigned x = i_begin; x < i_end; x++) { // for (int v = value; v >= 0; v--) { // drawPixel(start_x + (x - l_vline) * _step, // start_y + HIST_HEIGHT - v, // qRgb(40, 40, 150)); // } // } } } void PixelTreeCanvas::scaleUp(void) { _step++; _step_y++; actuallyDraw(); repaint(); } void PixelTreeCanvas::scaleDown(void) { if (_step <= 1) return; _step--; _step_y--; actuallyDraw(); repaint(); } void PixelTreeCanvas::compressionChanged(int value) { qDebug() << "compression is set to: " << value; approx_size = value; drawPixelTree(); repaint(); } void PixelTreeCanvas::drawPixel(int x, int y, int color) { if (y < 0) return; /// TODO: fix later for (unsigned i = 0; i < _step; i++) for (unsigned j = 0; j < _step_y; j++) _image->setPixel(x + i, y + j, color); } void PixelTreeCanvas::mousePressEvent(QMouseEvent* me) { int xoff = _sa->horizontalScrollBar()->value(); int yoff = _sa->verticalScrollBar()->value(); unsigned x = me->x() + xoff; unsigned y = me->y() + yoff; /// check boundaries: if (y > pt_height) return; // which node? unsigned vline = x / _step; selectNodesfromPT(vline); actuallyDraw(); repaint(); } void PixelTreeCanvas::selectNodesfromPT(unsigned vline) { struct Actions { private: NodeAllocator* _na; TreeCanvas* _tc; int node_id; bool _done; public: void selectOne(VisualNode* node) { _tc->setCurrentNode(node); _tc->centerCurrentNode(); } void selectGroup(VisualNode* node) { node->dirtyUp(*_na); VisualNode* next = node; while (!next->isRoot() && next->isHidden()) { next->setHidden(false); next = next->getParent(*_na); } } public: Actions(NodeAllocator* na, TreeCanvas* tc) : _na(na), _tc(tc), _done(false) {} }; qDebug() << "selecting vline: " << vline; if (pixelList.size() <= vline) { qDebug() << "no such vline"; } Actions actions(_na, _tc); void (Actions::*apply)(VisualNode*); /// unset currently selected nodes for (auto& node : nodes_selected) { node->setSelected(false); } nodes_selected.clear(); std::list<PixelData*>& vline_list = pixelList[vline]; if (vline_list.size() == 1) { apply = &Actions::selectOne; } else { apply = &Actions::selectGroup; /// hide everything except root _tc->hideAll(); (*_na)[0]->setHidden(false); } for (auto& pixel : vline_list) { (actions.*apply)(pixel->node()); pixel->node()->setSelected(true); nodes_selected.push_back(pixel->node()); } _tc->update(); } /// ***********************************
24.814465
102
0.625903
[ "vector" ]
9a40e517d0d8f15eff9993880426ad7c221c83d3
655
hxx
C++
include/z5/compression/compressor_base.hxx
davidbrochart/z5
2fc29798a68c66e4c60e3a9f65d4d390336d05d1
[ "MIT" ]
82
2018-02-02T04:03:49.000Z
2022-03-25T07:41:08.000Z
include/z5/compression/compressor_base.hxx
davidbrochart/z5
2fc29798a68c66e4c60e3a9f65d4d390336d05d1
[ "MIT" ]
152
2017-09-18T15:49:05.000Z
2022-03-16T21:07:07.000Z
include/z5/compression/compressor_base.hxx
davidbrochart/z5
2fc29798a68c66e4c60e3a9f65d4d390336d05d1
[ "MIT" ]
27
2017-09-19T14:52:56.000Z
2021-11-25T14:43:47.000Z
#pragma once #include <vector> #include "z5/types/types.hxx" namespace z5 { namespace compression { // abstract basis class for compression template<typename T> class CompressorBase { public: // // API -> must be implemented by child classes // virtual ~CompressorBase() {} virtual void compress(const T *, std::vector<char> &, std::size_t) const = 0; virtual void decompress(const std::vector<char> &, T *, std::size_t) const = 0; virtual types::Compressor type() const = 0; virtual void getOptions(types::CompressionOptions &) const = 0; }; } } // namespace::z5
23.392857
87
0.619847
[ "vector" ]
9a5aaf8b036bbedb845f0cd02709e65ae1b4a146
717
cc
C++
testsuite/test_utils/common_functions.cc
ph4r05/CryptoStreams
0c197842f01994bf22f56121d886a1beebd23e89
[ "MIT" ]
8
2018-03-27T17:02:21.000Z
2021-09-09T07:26:00.000Z
testsuite/test_utils/common_functions.cc
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
47
2018-03-27T17:57:07.000Z
2020-03-06T08:35:52.000Z
testsuite/test_utils/common_functions.cc
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
3
2019-02-09T23:44:07.000Z
2019-09-24T11:06:02.000Z
#include "common_functions.h" namespace testsuite { value_type hex_to_bin(const char input) { if (input >= '0' && input <= '9') return input - '0'; if (input >= 'A' && input <= 'F') return input - 'A' + 10; if (input >= 'a' && input <= 'f') return input - 'a' + 10; throw std::invalid_argument("Invalid input string"); } std::vector<value_type> hex_string_to_binary(const std::string &str) { assert(str.length() % 2 == 0); std::vector<value_type> output(str.length() / 2); for (uint32_t i = 0; i < str.size() / 2; i++) { output[i] = (hex_to_bin(str.at(2 * i)) << 4) + hex_to_bin(str.at(2 * i + 1)); } return output; } } // namespace testsuite
26.555556
85
0.563459
[ "vector" ]
9a6c80e0cf76fb30080b307d64bab936dd2f3270
5,778
cpp
C++
Game/Source/SceneIntro.cpp
Memory-Leakers/Pirates
1f11afe45369a75f924a9682941ffb483e0eae2f
[ "MIT" ]
4
2021-12-21T16:42:10.000Z
2022-01-30T16:16:04.000Z
Game/Source/SceneIntro.cpp
Memory-Leakers/Pirates
1f11afe45369a75f924a9682941ffb483e0eae2f
[ "MIT" ]
null
null
null
Game/Source/SceneIntro.cpp
Memory-Leakers/Pirates
1f11afe45369a75f924a9682941ffb483e0eae2f
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "SceneIntro.h" #include "PhysCore.h" #include "TurnsManager.h" #include "Water.h" #include "GameUI.h" SceneIntro::SceneIntro(Application* app) : Scene(app) {} SceneIntro::~SceneIntro() {} // Load assets bool SceneIntro::Start() { LOG("Loading Intro assets"); bool ret = true; _app->map->Load("PiratesLevel.tmx"); bg[0] = _app->textures->Load("Assets/textures/Background/0.png"); bg[1] = _app->textures->Load("Assets/textures/Background/1.png"); bg[2] = _app->textures->Load("Assets/textures/Background/2.png"); bg[3] = _app->textures->Load("Assets/textures/Background/3.png"); world = new PhysCore({ 0,10 }); rectbgclouds = { 0,50 }; InitScene(); //player Init for (int i = 0; i < 3; i++) { player1Characters[i] = new Player("Player1", "player", _app, 1); player1Characters[i]->rBody = new RigidBody(player1Positions[i], RigidBodyType::DYNAMIC, 11, player1Characters[i]); player1Characters[i]->rBody->SetGravityScale(2.0f); player1Characters[i]->rBody->SetDragCoeficient(0.1f); player1Characters[i]->rBody->SetRestitution(0.2f); player1Characters[i]->rBody->SetHydrodynamicDragCoeficient(0.5f); player1Characters[i]->rBody->SetFriction(6.0f); player2Characters[i] = new Player("Player2", "player", _app, 2); player2Characters[i]->rBody = new RigidBody(player2Positions[i], RigidBodyType::DYNAMIC, 11, player2Characters[i]); player2Characters[i]->rBody->SetGravityScale(2.0f); player2Characters[i]->rBody->SetDragCoeficient(0.1f); player2Characters[i]->rBody->SetRestitution(0.2f); player2Characters[i]->rBody->SetHydrodynamicDragCoeficient(0.5f); player2Characters[i]->rBody->SetFriction(6.0f); } // Init water water = new Water({ 0,450 }, "water", "Water", _app); walls[0] = new RigidBody({ 0,0 }, RigidBodyType::STATIC, 3200, 5); walls[1] = new RigidBody({ 0,0 }, RigidBodyType::STATIC, 5, 1440); walls[2] = new RigidBody({1550,0 }, RigidBodyType::STATIC, 5, 1440); gameUI = new GameUI(_app); turnsManager = new TurnsManager(_app, this, world, gameUI); for (int i = 0; i < 3; i++) { gameObjects.add(player1Characters[i]); gameObjects.add(player2Characters[i]); } gameObjects.add(water); for (int i = 0; i < gameObjects.count(); i++) { gameObjects[i]->Start(); } for (int i = 0; i < 3; i++) { world->AddRigidBody(walls[i]); world->AddRigidBody(player1Characters[i]->rBody); world->AddRigidBody(player2Characters[i]->rBody); } world->AddRigidBody(water->rBody); for (int i = 0; i < 3; i++) { turnsManager->AddGameObjectAsItem(player1Characters[i], PLAYER1); turnsManager->AddGameObjectAsItem(player2Characters[i], PLAYER2); } return ret; } void SceneIntro::InitScene() { // Obstacles for (int i = 0; i < _app->map->mapObjects.count(); i++) { if (_app->map->mapObjects[i].id == 0) { GameObject* g = new GameObject("wall", "Wall", _app); // +8 = offset, porque pivot de b2Body es el centro, y de tectura es izquierda superior. g->rBody = new RigidBody({ _app->map->mapObjects[i].position.x +8, _app->map->mapObjects[i].position.y +8 }, RigidBodyType::STATIC, 16, 16); world->AddRigidBody(g->rBody); gameObjects.add(g); } } } bool SceneIntro::PreUpdate() { for (int i = 0; i < gameObjects.count(); i++) { gameObjects[i]->PreUpdate(); if (gameObjects[i]->pendingToDelete == true) { if (gameObjects[i]->rBody != nullptr) { world->DeleteRigidBody(gameObjects[i]->rBody); if (gameObjects[i]->rBodyTrigger != nullptr) { world->DeleteRigidBody(gameObjects[i]->rBodyTrigger); } } gameObjects[i]->CleanUp(); gameObjects.del(gameObjects.At(gameObjects.find(gameObjects[i]))); } } int player1Lifes = 0; int player2Lifes = 0; for (int i = 0; i < 3; i++) { player1Lifes += player1Characters[i]->health; player2Lifes += player2Characters[i]->health; } if (player1Lifes == 0) { _app->scene->winner = 1; _app->scene->ChangeCurrentScene(2, 0); return true; } if (player2Lifes == 0) { _app->scene->winner = 0; _app->scene->ChangeCurrentScene(2, 0); return true; } return true; } // Load assets bool SceneIntro::CleanUp() { LOG("Unloading Intro scene"); RELEASE(world); if (turnsManager != nullptr) { turnsManager->CleanUp(); delete turnsManager; turnsManager = nullptr; } if (gameUI != nullptr) { delete gameUI; gameUI = nullptr; } _app->map->CleanUp(); Scene::CleanUp(); return true; } // Update: draw background bool SceneIntro::Update() { world->Update((1.0 / _app->fps)); turnsManager->UpdateGameLogic(); gameUI->Update(); for (int i = 0; i < gameObjects.count(); i++) { gameObjects[i]->Update(); } // Camera Follow Logic if (turnsManager->throwedGameObj != nullptr) // Follow throwed Game Object { _app->renderer->camera->SetTarget(turnsManager->throwedGameObj); } else { _app->renderer->camera->SetTarget(nullptr); } if (rectbgclouds.x >= 1200) { rectbgclouds.x -= 2052; } else { rectbgclouds.x++; } _app->renderer->camera->MoveCameraWithMouse(); return true; } bool SceneIntro::PostUpdate() { gameUI->PostUpdate(); _app->renderer->AddTextureRenderQueue(bg[0], { 0,0 }, { 0,0,0,0 },2.0f); _app->renderer->AddTextureRenderQueue(bg[2], { 0,180 }, { 0,0,0,0 }, 2.0f, 0, 0.0f, 0, SDL_FLIP_NONE, 0.4f); _app->renderer->AddTextureRenderQueue(bg[1], { 100,100 }, { 0,0,0,0 }, 2.0f, 0, 0.0f, 0, SDL_FLIP_NONE, 0.5f); _app->renderer->AddTextureRenderQueue(bg[3], { 0,20 }, { 0,0,0,0 }, 1.0f, 0, 0.0f, 0, SDL_FLIP_NONE, 0.6f); for (int i = 0; i < gameObjects.count(); i++) { gameObjects[i]->PostUpdate(); } _app->renderer->AddTextureRenderQueue(bg[3], { rectbgclouds.x,rectbgclouds.y }, { 0,0,0,0 }, 1.0f, 0, 0.0f, 0, SDL_FLIP_NONE, 0.6f); return true; }
24.075
143
0.664763
[ "object" ]
9a6eb7d08a84c45aed014d2920531030fa81db6d
10,338
cpp
C++
artifact/storm/src/storm/solver/SymbolicEliminationLinearEquationSolver.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/solver/SymbolicEliminationLinearEquationSolver.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/solver/SymbolicEliminationLinearEquationSolver.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/solver/SymbolicEliminationLinearEquationSolver.h" #include "storm/storage/dd/DdManager.h" #include "storm/storage/dd/Add.h" #include "storm/utility/dd.h" #include "storm/adapters/RationalFunctionAdapter.h" namespace storm { namespace solver { template<storm::dd::DdType DdType, typename ValueType> SymbolicEliminationLinearEquationSolver<DdType, ValueType>::SymbolicEliminationLinearEquationSolver() : SymbolicLinearEquationSolver<DdType, ValueType>() { // Intentionally left empty. } template<storm::dd::DdType DdType, typename ValueType> SymbolicEliminationLinearEquationSolver<DdType, ValueType>::SymbolicEliminationLinearEquationSolver(storm::dd::Add<DdType, ValueType> const& A, storm::dd::Bdd<DdType> const& allRows, std::set<storm::expressions::Variable> const& rowMetaVariables, std::set<storm::expressions::Variable> const& columnMetaVariables, std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs) : SymbolicEliminationLinearEquationSolver(allRows, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs) { this->setMatrix(A); } template<storm::dd::DdType DdType, typename ValueType> SymbolicEliminationLinearEquationSolver<DdType, ValueType>::SymbolicEliminationLinearEquationSolver(storm::dd::Bdd<DdType> const& allRows, std::set<storm::expressions::Variable> const& rowMetaVariables, std::set<storm::expressions::Variable> const& columnMetaVariables, std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs) : SymbolicLinearEquationSolver<DdType, ValueType>(allRows, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs) { this->createInternalData(allRows, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs); } template<storm::dd::DdType DdType, typename ValueType> storm::dd::Add<DdType, ValueType> SymbolicEliminationLinearEquationSolver<DdType, ValueType>::solveEquations(Environment const& env, storm::dd::Add<DdType, ValueType> const& x, storm::dd::Add<DdType, ValueType> const& b) const { storm::dd::DdManager<DdType>& ddManager = x.getDdManager(); // Build diagonal BDD over new meta variables. storm::dd::Bdd<DdType> diagonal = storm::utility::dd::getRowColumnDiagonal(ddManager, this->rowColumnMetaVariablePairs); diagonal &= this->getAllRows(); diagonal = diagonal.swapVariables(this->oldNewMetaVariablePairs); storm::dd::Add<DdType, ValueType> rowsAdd = this->getAllRows().swapVariables(rowRowMetaVariablePairs).template toAdd<ValueType>(); storm::dd::Add<DdType, ValueType> diagonalAdd = diagonal.template toAdd<ValueType>(); // Move the matrix to the new meta variables. storm::dd::Add<DdType, ValueType> matrix = this->A.swapVariables(oldNewMetaVariablePairs); // Initialize solution over the new meta variables. storm::dd::Add<DdType, ValueType> solution = b.swapVariables(oldNewMetaVariablePairs); // As long as there are transitions, we eliminate them. uint64_t iterations = 0; while (!matrix.isZero()) { // Determine inverse loop probabilies. storm::dd::Add<DdType, ValueType> inverseLoopProbabilities = rowsAdd / (rowsAdd - (diagonalAdd * matrix).sumAbstract(newColumnVariables)); // Scale all transitions with the inverse loop probabilities. matrix *= inverseLoopProbabilities; solution *= inverseLoopProbabilities; // Delete diagonal elements, i.e. remove self-loops. matrix = diagonal.ite(ddManager.template getAddZero<ValueType>(), matrix); // Update the one-step probabilities. solution += (matrix * solution.swapVariables(newRowColumnMetaVariablePairs)).sumAbstract(newColumnVariables); // Shortcut all transitions by eliminating one intermediate step. matrix = matrix.multiplyMatrix(matrix.permuteVariables(shiftMetaVariablePairs), newColumnVariables); matrix = matrix.swapVariables(columnHelperMetaVariablePairs); ++iterations; STORM_LOG_TRACE("Completed iteration " << iterations << " of elimination process."); } STORM_LOG_INFO("Elimination completed in " << iterations << " iterations."); return solution.swapVariables(rowRowMetaVariablePairs); } template<storm::dd::DdType DdType, typename ValueType> LinearEquationSolverProblemFormat SymbolicEliminationLinearEquationSolver<DdType, ValueType>::getEquationProblemFormat(Environment const& env) const { return LinearEquationSolverProblemFormat::FixedPointSystem; } template<storm::dd::DdType DdType, typename ValueType> void SymbolicEliminationLinearEquationSolver<DdType, ValueType>::createInternalData(storm::dd::Bdd<DdType> const& allRows, std::set<storm::expressions::Variable> const& rowMetaVariables, std::set<storm::expressions::Variable> const& columnMetaVariables, std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs) { storm::dd::DdManager<DdType>& ddManager = allRows.getDdManager(); // Create triple-layered meta variables for all original meta variables. We will use them later in the elimination process. for (auto const& metaVariablePair : this->rowColumnMetaVariablePairs) { auto rowVariable = metaVariablePair.first; storm::dd::DdMetaVariable<DdType> const& metaVariable = ddManager.getMetaVariable(rowVariable); std::vector<storm::expressions::Variable> newMetaVariables; // Find a suitable name for the temporary variable. uint64_t counter = 0; std::string newMetaVariableName = "tmp_" + metaVariable.getName(); while (ddManager.hasMetaVariable(newMetaVariableName + std::to_string(counter))) { ++counter; } newMetaVariables = ddManager.cloneVariable(metaVariablePair.first, newMetaVariableName + std::to_string(counter), 3); newRowVariables.insert(newMetaVariables[0]); newColumnVariables.insert(newMetaVariables[1]); helperVariables.insert(newMetaVariables[2]); newRowColumnMetaVariablePairs.emplace_back(newMetaVariables[0], newMetaVariables[1]); columnHelperMetaVariablePairs.emplace_back(newMetaVariables[1], newMetaVariables[2]); rowRowMetaVariablePairs.emplace_back(metaVariablePair.first, newMetaVariables[0]); columnColumnMetaVariablePairs.emplace_back(metaVariablePair.second, newMetaVariables[1]); oldToNewMapping.emplace_back(std::move(newMetaVariables)); } oldNewMetaVariablePairs = rowRowMetaVariablePairs; for (auto const& entry : columnColumnMetaVariablePairs) { oldNewMetaVariablePairs.emplace_back(entry.first, entry.second); } shiftMetaVariablePairs = newRowColumnMetaVariablePairs; for (auto const& entry : columnHelperMetaVariablePairs) { shiftMetaVariablePairs.emplace_back(entry.first, entry.second); } } template<storm::dd::DdType DdType, typename ValueType> void SymbolicEliminationLinearEquationSolver<DdType, ValueType>::setData(storm::dd::Bdd<DdType> const& allRows, std::set<storm::expressions::Variable> const& rowMetaVariables, std::set<storm::expressions::Variable> const& columnMetaVariables, std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs) { // Call superclass function. SymbolicLinearEquationSolver<DdType, ValueType>::setData(allRows, rowMetaVariables, columnMetaVariables, rowColumnMetaVariablePairs); // Now create new variables as needed. this->createInternalData(this->getAllRows(), this->rowMetaVariables, this->columnMetaVariables, this->rowColumnMetaVariablePairs); } template<storm::dd::DdType DdType, typename ValueType> std::unique_ptr<storm::solver::SymbolicLinearEquationSolver<DdType, ValueType>> SymbolicEliminationLinearEquationSolverFactory<DdType, ValueType>::create(Environment const& env) const { return std::make_unique<SymbolicEliminationLinearEquationSolver<DdType, ValueType>>(); } template class SymbolicEliminationLinearEquationSolver<storm::dd::DdType::CUDD, double>; template class SymbolicEliminationLinearEquationSolver<storm::dd::DdType::CUDD, storm::RationalNumber>; template class SymbolicEliminationLinearEquationSolver<storm::dd::DdType::Sylvan, double>; template class SymbolicEliminationLinearEquationSolver<storm::dd::DdType::Sylvan, storm::RationalNumber>; template class SymbolicEliminationLinearEquationSolver<storm::dd::DdType::Sylvan, storm::RationalFunction>; template class SymbolicEliminationLinearEquationSolverFactory<storm::dd::DdType::CUDD, double>; template class SymbolicEliminationLinearEquationSolverFactory<storm::dd::DdType::CUDD, storm::RationalNumber>; template class SymbolicEliminationLinearEquationSolverFactory<storm::dd::DdType::Sylvan, double>; template class SymbolicEliminationLinearEquationSolverFactory<storm::dd::DdType::Sylvan, storm::RationalNumber>; template class SymbolicEliminationLinearEquationSolverFactory<storm::dd::DdType::Sylvan, storm::RationalFunction>; } }
66.696774
559
0.682627
[ "vector" ]
9a6f1617a2e790fd59267bc2041c0dcd43c2d66c
94
cpp
C++
src/ball.cpp
liamst19/pong-study
03da70fc8092a1c20d5e70b2783d583c1418f95d
[ "MIT" ]
null
null
null
src/ball.cpp
liamst19/pong-study
03da70fc8092a1c20d5e70b2783d583c1418f95d
[ "MIT" ]
null
null
null
src/ball.cpp
liamst19/pong-study
03da70fc8092a1c20d5e70b2783d583c1418f95d
[ "MIT" ]
null
null
null
/** ball.cpp * * Ball object. * */ #include "mobilepiece.h" #include "ball.h"
9.4
25
0.510638
[ "object" ]
9a787e2e16cdf8b608cbb723328c33ef7614a21b
10,103
cpp
C++
Source/Workbenches/Sketcher/sketch_line_create_mode.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
Source/Workbenches/Sketcher/sketch_line_create_mode.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
Source/Workbenches/Sketcher/sketch_line_create_mode.cpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2007, 2008, CerroKai Development * 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 CerroKai Development nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CerroKai Development ``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 CerroKai Development 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. ********************************************************************************/ /*** Included Header Files ***/ #include <Sketcher/sketch_line_modes.h> #include <Sketcher/sketch_line.h> #include <Sketcher/sketch_point.h> #include <Sketcher/sketch_workbench.h> #include <Sketcher/sketch.h> #include <Constraint/constraint_length.h> #include <Constraint/constraint_distance.h> #include <Constraint/constraint_coincidence.h> #include <Constraint/constraint_horizontal.h> #include <Constraint/constraint_vertical.h> #include <Kernel/document.h> #include <PartDesign/part_plane.h> /***********************************************~***************************************************/ WCModeSketchLineCreate::WCModeSketchLineCreate(WCSketchWorkbench *wb) : ::WCDrawingMode(wb->Sketch(), SKETCHLINEMODE_CREATE_NAME), _workbench(wb), _isDrawing(false), _begin(), _p0(NULL), _p1(NULL), _line(NULL), _xSuggest(0.0), _ySuggest(0.0), _suggestionType(WCSketchAlignmentSuggestion::None()) { //Add in alignment suggestion rules this->_alignRules.push_back(WCSketchAlignmentSuggestion::CoincidentToPoint()); this->_alignRules.push_back(WCSketchAlignmentSuggestion::CoincidentToLine()); this->_alignRules.push_back(WCSketchAlignmentSuggestion::CoincidentToCurve()); this->_alignRules.push_back(WCSketchAlignmentSuggestion::HorizontalToPoint()); this->_alignRules.push_back(WCSketchAlignmentSuggestion::VerticalToPoint()); } void WCModeSketchLineCreate::OnEntry(void) { CLOGGER_DEBUG(WCLogManager::RootLogger(), "Entering SketchLine Draw Mode."); //Clear any selected items this->_workbench->SelectionManager()->Clear(true); } void WCModeSketchLineCreate::OnExit(void) { CLOGGER_DEBUG(WCLogManager::RootLogger(), "Exiting SketchLine Draw Mode."); //Delete line is present if(this->_isDrawing) { delete this->_p0; delete this->_p1; delete this->_line; } } void WCModeSketchLineCreate::OnMouseDown(const WCMouseButton &button) { //Cancel if right click if (button == WCMouseButton::Right()) { //If not drawing, do nothing if (!this->_isDrawing) return; //Delete the visualization objects delete this->_line; delete this->_p0; delete this->_p1; //Reset drawing state this->_isDrawing = false; return; } //Otherwise, only left button else if (button != WCMouseButton::Left()) return; //If not already drawing if (!this->_isDrawing) { //Get the position this->_begin.Set(this->_xSuggest, this->_ySuggest, 0.0, 1.0); WCVector4 pos = this->_workbench->Sketch()->ReferencePlane()->TransformMatrix() * this->_begin; //Create the visualization points this->_p0 = new WCGeometricPoint(pos); this->_p0->Color(WCSketchFeature::InprocessColor); this->_p0->Size(WCSketchFeature::PointSize); this->_p1 = new WCGeometricPoint(pos); this->_p1->Color(WCSketchFeature::InprocessColor); this->_p1->Size(WCSketchFeature::PointSize); //Create line this->_line = new WCGeometricLine(pos, pos); this->_line->Color(WCSketchFeature::InprocessColor); this->_line->Thickness(WCSketchFeature::LineThickness); //Mark as drawing this->_isDrawing = true; } //If already drawing else { //Get the current coordinates WCVector4 pos(this->_xSuggest, this->_ySuggest, 0.0, 1.0); //Make sure line is long enough if (pos.Distance(this->_begin) < SKETCHLINE_MIN_LENGTH) { CLOGGER_DEBUG(WCLogManager::RootLogger(), "WCModeSketchLineCreate::OnMouseDown - Line length below minimum."); return; } //Create a new SketchLine WCActionSketchLineCreate *action = WCSketchLine::ActionCreate(this->_workbench->Sketch(), "", this->_begin, pos); this->_workbench->Sketch()->Document()->ExecuteAction( action ); WCSketchLine *line = action->Line(); //Create two new SketchPoints // WCActionSketchPointCreate *p0Action = WCSketchPoint::ActionCreate(this->_workbench->Sketch(), "", this->_begin); // this->_workbench->Sketch()->Document()->ExecuteAction( p0Action ); // WCSketchPoint *p0 = p0Action->Point(); // WCActionSketchPointCreate *p1Action = WCSketchPoint::ActionCreate(this->_workbench->Sketch(), "", pos); // this->_workbench->Sketch()->Document()->ExecuteAction( p1Action ); // WCSketchPoint *p1 = p1Action->Point(); //See if auto-dimensional constraints are on if (this->_workbench->IsDimensionalConstraint()) { //Create distance constraints from origin to p0 // WCSketchPoint* origin = dynamic_cast<WCSketchPoint*>( this->_workbench->Sketch()->FeatureFromName("Origin") ); //Create the horizontal distance constraint // WCAction *p0ConstraintAction = WCConstraintDistance::ActionCreate( this->_workbench->Sketch(), "", p0, // origin, WCMeasureType::Horizontal() ); // this->_workbench->Sketch()->Document()->ExecuteAction( p0ConstraintAction ); //Create the vertical distance constraint // p0ConstraintAction = WCConstraintDistance::ActionCreate( this->_workbench->Sketch(), "", p0, // origin, WCMeasureType::Vertical() ); // this->_workbench->Sketch()->Document()->ExecuteAction( p0ConstraintAction ); //Create a length constraint on line WCAction *a2 = WCConstraintLength::ActionCreate(this->_workbench->Sketch(), "", line); this->_workbench->Sketch()->Document()->ExecuteAction( a2 ); } //See if auto-geometric constraints are on if (this->_workbench->IsGeometricConstraint()) { //Create coincidence constraints for p0-line and p1-line // WCAction *p0LineCoincidenceAction = WCConstraintCoincidence::ActionCreate( this->_workbench->Sketch(), "", p0, line); // this->_workbench->Sketch()->Document()->ExecuteAction( p0LineCoincidenceAction ); // WCAction *p1LineCoincidenceAction = WCConstraintCoincidence::ActionCreate( this->_workbench->Sketch(), "", p1, line); // this->_workbench->Sketch()->Document()->ExecuteAction( p1LineCoincidenceAction ); //Determine the slope of the line WPFloat slope = (pos.J() - this->_begin.J()) / (pos.I() - this->_begin.I()); //Check for horizontal or vertical constraints if ((slope < 0.1) && (slope > -0.1)) { WCAction *horizAction = WCConstraintHorizontal::ActionCreate( this->_workbench->Sketch(), "", line); this->_workbench->Sketch()->Document()->ExecuteAction( horizAction ); } else if ((slope > 10) || (slope < -10)) { WCAction *vertAction = WCConstraintVertical::ActionCreate( this->_workbench->Sketch(), "", line); this->_workbench->Sketch()->Document()->ExecuteAction( vertAction ); } //Otherwise, look for angle constraint compared to uAxis else { //... // std::cout << "Making angle constraint\n"; } } //Reset for the next line this->_begin.Set(this->_xSuggest, this->_ySuggest, 0.0, 1.0); pos = this->_workbench->Sketch()->ReferencePlane()->TransformMatrix() * this->_begin; this->_line->Begin(pos); this->_line->End(pos); this->_p0->Set(pos); this->_p1->Set(pos); } } void WCModeSketchLineCreate::OnMouseMove(const WPFloat &x, const WPFloat &y) { //Get suggestion from workbench this->_xSuggest = this->_workbench->SnapMouseX(); this->_ySuggest = this->_workbench->SnapMouseY(); this->_suggestionType = this->_workbench->SuggestAlignment(this->_alignRules, NULL, this->_xSuggest, this->_ySuggest); //Move p1 if we are drawing if (this->_isDrawing) { //Get the new position WCVector4 pos(this->_xSuggest, this->_ySuggest, 0.0, 1.0); pos = this->_workbench->Sketch()->ReferencePlane()->TransformMatrix() * pos; //Set the end point and line appropriately this->_p1->Set(pos); this->_line->End(pos); } } void WCModeSketchLineCreate::Render(void) { //Draw the crosshairs at the current position this->_workbench->RenderCrosshairs(this->_xSuggest, this->_ySuggest); //Draw any suggested references this->_workbench->RenderAlignmentSuggestion(this->_suggestionType, this->_xSuggest, this->_ySuggest); //Check to see if drawing if (!this->_isDrawing) return; //Turn off depth testing glDisable(GL_DEPTH_TEST); glEnable(GL_LINE_STIPPLE); glLineStipple(WCSketchFeature::LineStippleFactor, WCSketchFeature::LineStipplePattern); WPFloat zoom = this->_workbench->Feature()->Document()->Scene()->ActiveCamera()->Zoom(); //Draw visualization points and line this->_p0->Render(0, WCColor::Default(), zoom); this->_p1->Render(0, WCColor::Default(), zoom); this->_line->Render(0, WCColor::Default(), zoom); //Renable depth test glDisable(GL_LINE_STIPPLE); glEnable(GL_DEPTH_TEST); } /***********************************************~***************************************************/
43.547414
133
0.707018
[ "render" ]
9a7bbb8b2229b11825b8d191cc1ec231d3228ccb
4,341
cc
C++
src/pub14_core/simulation/scene.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
1
2015-03-25T16:02:17.000Z
2015-03-25T16:02:17.000Z
src/pub14_core/simulation/scene.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
src/pub14_core/simulation/scene.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "scene.h" #include <algorithm> #include "swganh/object/object.h" #include "swganh/object/object_controller.h" #include "pub14_core/messages/scene_destroy_object.h" using namespace std; using namespace swganh::messages; using namespace swganh::object; using namespace swganh::simulation; using namespace swganh_core::simulation; class Scene::SceneImpl { public: SceneImpl(SceneDescription description) : description_(move(description)) {} const SceneDescription& GetDescription() const { return description_; } bool HasObject(const shared_ptr<Object>& object) { return objects_.find(object) != objects_.end(); } void AddObject(const shared_ptr<Object>& object) { InsertObject(object); for_each(begin(object_map_), end(object_map_), [&object] (const ObjectMap::value_type& object_entry) { auto& stored_object = object_entry.second; stored_object->AddAwareObject(object); object->AddAwareObject(stored_object); }); auto contained_objects = object->GetContainedObjects(); for_each(begin(contained_objects), end(contained_objects), [this] (const ObjectMap::value_type& object_entry) { auto& stored_object = object_entry.second; AddObject(stored_object); }); } void RemoveObject(const shared_ptr<Object>& object) { if (!HasObject(object)) { return; } EraseObject(object); SceneDestroyObject destroy_message; destroy_message.object_id = object->GetObjectId(); for_each(begin(object_map_), end(object_map_), [&object, &destroy_message] (const ObjectMap::value_type& object_entry) { auto& stored_object = object_entry.second; stored_object->RemoveContainedObject(object); stored_object->RemoveAwareObject(object); if (stored_object->HasController()) { stored_object->GetController()->Notify(destroy_message); } }); } void InsertObject(const shared_ptr<Object>& object) { // make sure it's not already there auto find_iter = objects_.find(object); if (find_iter == end(objects_)) objects_.insert(find_iter, object); auto find_map = object_map_.find(object->GetObjectId()); if (find_map == end(object_map_)) object_map_.insert(find_map, ObjectPair(object->GetObjectId(), object)); } void EraseObject(const shared_ptr<Object>& object) { objects_.erase(object); object_map_.erase(object->GetObjectId()); } private: typedef std::map< uint64_t, shared_ptr<Object> > ObjectMap; typedef std::pair< uint64_t, shared_ptr<Object> > ObjectPair; typedef std::set<std::shared_ptr<Object>> ObjectSet; ObjectSet objects_; ObjectMap object_map_; SceneDescription description_; }; Scene::Scene(SceneDescription description) : impl_(new SceneImpl(move(description))) {} Scene::Scene(uint32_t scene_id, string name, string label, string description, string terrain) { SceneDescription scene_description; scene_description.id = scene_id; scene_description.name = move(name); scene_description.label = move(label); scene_description.description = move(description); scene_description.terrain = move(terrain); impl_.reset(new SceneImpl(move(scene_description))); } uint32_t Scene::GetSceneId() const { return impl_->GetDescription().id; } const std::string& Scene::GetName() const { return impl_->GetDescription().name; } const std::string& Scene::GetLabel() const { return impl_->GetDescription().label; } const std::string& Scene::GetDescription() const { return impl_->GetDescription().description; } const std::string& Scene::GetTerrainMap() const { return impl_->GetDescription().terrain; } void Scene::AddObject(const std::shared_ptr<swganh::object::Object>& object) { impl_->AddObject(object); } void Scene::RemoveObject(const std::shared_ptr<swganh::object::Object>& object) { impl_->RemoveObject(object); }
25.092486
95
0.670583
[ "object" ]
893b897e87eb0aa63245af1bae9dced034dc640a
18,124
cpp
C++
inetsrv/iis/svcs/cmp/asp/reg.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/cmp/asp/reg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/cmp/asp/reg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*=================================================================== Microsoft IIS Active Server Pages Microsoft Confidential. Copyright 1997 Microsoft Corporation. All Rights Reserved. Component: Registry stuff File: reg.cpp Owner: AndrewS/LeiJin ===================================================================*/ #include "denpre.h" #pragma hdrstop #include <iadmw.h> #include "comadmin.h" #include "memchk.h" #include "Accctrl.h" #include "aclapi.h" #include "iiscnfg.h" //External functions, defined in glob.cpp extern HRESULT MDRegisterProperties(void); extern HRESULT MDUnRegisterProperties(void); // Globals const REGSAM samDesired = KEY_READ | KEY_WRITE; /* * Info about our intrinsics used by Register & UnRegister */ const char *szClassDesc[] = { "ASP Response Object", "ASP Request Object", "ASP Request Dictionary", "ASP Server Object", "ASP Application Object", "ASP Session Object", "ASP String List Object", "ASP Read Cookie", "ASP Write Cookie", "ASP Scripting Context Object", "ASP Certificate Object", }; const char *szCLSIDEntry[] = { "CLSID\\{D97A6DA0-A864-11cf-83BE-00A0C90C2BD8}", // IResponse "CLSID\\{D97A6DA0-A861-11cf-93AE-00A0C90C2BD8}", // IRequest "CLSID\\{D97A6DA0-A85F-11df-83AE-00A0C90C2BD8}", // IRequestDictionary "CLSID\\{D97A6DA0-A867-11cf-83AE-01A0C90C2BD8}", // IServer "CLSID\\{D97A6DA0-A866-11cf-83AE-10A0C90C2BD8}", // IApplicationObject "CLSID\\{D97A6DA0-A865-11cf-83AF-00A0C90C2BD8}", // ISessionObject "CLSID\\{D97A6DA0-A85D-11cf-83AE-00A0C90C2BD8}", // IStringList "CLSID\\{71EAF260-0CE0-11d0-A53E-00A0C90C2091}", // IReadCookie "CLSID\\{D97A6DA0-A862-11cf-84AE-00A0C90C2BD8}", // IWriteCookie "CLSID\\{D97A6DA0-A868-11cf-83AE-00B0C90C2BD8}", // IScriptingContext "CLSID\\{b3192190-1176-11d0-8ce8-00aa006c400c}", // ICertificate }; const cClassesMax = sizeof(szCLSIDEntry) / sizeof(char *); /*=================================================================== RegisterIntrinsics Register info about our intrinsics in the registry. Returns: HRESULT - S_OK on success Side effects: Registers denali objects in the registry ===================================================================*/ HRESULT RegisterIntrinsics(void) { static const char szDenaliDLL[] = "asp.DLL"; static const char szThreadingModel[] = "ThreadingModel"; static const char szInprocServer32[] = "InprocServer32"; static const char szFreeThreaded[] = "Both"; static const char szProgIdKey[] = "ProgId"; static const char szCLSIDKey[] = "CLSID"; HRESULT hr = S_OK; char szPath[MAX_PATH]; char *pch; HKEY hkeyCLSID = NULL; HKEY hkeyT = NULL; DWORD iClass; // Get the path and name of Denali if (!GetModuleFileNameA(g_hinstDLL, szPath, sizeof(szPath)/sizeof(char))) return E_FAIL; // bug fix 102010 DBCS fixes // //for (pch = szPath + lstrlen(szPath); pch > szPath && *pch != TEXT('\\'); pch--) // ; //if (pch == szPath) pch = (char*) _mbsrchr((const unsigned char*)szPath, '\\'); if (pch == NULL) { Assert(FALSE); goto LErrExit; } strcpy(pch + 1, szDenaliDLL); for (iClass = 0; iClass < cClassesMax; iClass++) { // install the CLSID key // Setting the value of the description creates the key for the clsid if ((RegSetValueA(HKEY_CLASSES_ROOT, szCLSIDEntry[iClass], REG_SZ, szClassDesc[iClass], strlen(szClassDesc[iClass])) != ERROR_SUCCESS)) goto LErrExit; // Open the CLSID key so we can set values on it if (RegOpenKeyExA(HKEY_CLASSES_ROOT, szCLSIDEntry[iClass], 0, samDesired, &hkeyCLSID) != ERROR_SUCCESS) goto LErrExit; // install the InprocServer32 key and open the sub-key to set the named value if ((RegSetValueA(hkeyCLSID, szInprocServer32, REG_SZ, szPath, strlen(szPath)) != ERROR_SUCCESS)) goto LErrExit; if ((RegOpenKeyExA(hkeyCLSID, szInprocServer32, 0, samDesired, &hkeyT) != ERROR_SUCCESS)) goto LErrExit; // install the ThreadingModel named value if (RegSetValueExA(hkeyT, szThreadingModel, 0, REG_SZ, (const BYTE *)szFreeThreaded, (strlen(szFreeThreaded)+1) * sizeof(char)) != ERROR_SUCCESS) goto LErrExit; if (RegCloseKey(hkeyT) != ERROR_SUCCESS) goto LErrExit; hkeyT = NULL; RegCloseKey(hkeyCLSID); hkeyCLSID = NULL; } return hr; LErrExit: if (hkeyT) RegCloseKey(hkeyT); if (hkeyCLSID) RegCloseKey(hkeyCLSID); return E_FAIL; } /*=================================================================== UnRegisterKey Given a string which is the name of a key under HKEY_CLASSES_ROOT, delete everything under that key and the key itself from the registry (why the heck isnt there an API that does this!?!?) Returns: HRESULT - S_OK on success Side effects: Removes a key & all subkeys from the registry ===================================================================*/ HRESULT UnRegisterKey(CHAR *szKey) { HKEY hkey = NULL; CHAR szKeyName[255]; DWORD cbKeyName; LONG errT; // Open the HKEY_CLASSES_ROOT\CLSID\{...} key so we can delete its subkeys if (RegOpenKeyExA(HKEY_CLASSES_ROOT, szKey, 0, samDesired, &hkey) != ERROR_SUCCESS) goto LErrExit; // Enumerate all its subkeys, and delete them while (TRUE) { cbKeyName = sizeof(szKeyName); if ((errT = RegEnumKeyExA(hkey, 0, szKeyName, &cbKeyName, 0, NULL, 0, NULL)) != ERROR_SUCCESS) break; if ((errT = RegDeleteKeyA(hkey, szKeyName)) != ERROR_SUCCESS) goto LErrExit; } // Close the key, and then delete it if ((errT = RegCloseKey(hkey)) != ERROR_SUCCESS) return(E_FAIL); if ((errT = RegDeleteKeyA(HKEY_CLASSES_ROOT, szKey)) != ERROR_SUCCESS) { DBGPRINTF((DBG_CONTEXT, "Deleting key %s returned %d\n", szKey, GetLastError())); return(E_FAIL); } return S_OK; LErrExit: if (hkey) RegCloseKey(hkey); return E_FAIL; } /*=================================================================== UnRegisterIntrinsics UnRegister the info about our intrinsics from the registry. Returns: HRESULT - S_OK on success Side effects: Removes denali objects from the registry ===================================================================*/ HRESULT UnRegisterIntrinsics(void) { HRESULT hr = S_OK, hrT; DWORD iClass; // Now delete the keys for the objects for (iClass = 0; iClass < cClassesMax; iClass++) { // Open the HKEY_CLASSES_ROOT\CLSID\{...} key so we can delete its subkeys if (FAILED(hrT = UnRegisterKey((CHAR *)szCLSIDEntry[iClass]))) hr = hrT; // Hold onto the error, but keep going } return hr; } /*=================================================================== RegisterTypeLib Register denali typelib in the registry. Returns: HRESULT - S_OK on success Side effects: register denali typelib in the registry ===================================================================*/ HRESULT RegisterTypeLib(void) { HRESULT hr; ITypeLib *pITypeLib = NULL; char szFile[MAX_PATH+4]; BSTR bstrFile; // Get the path and name of Denali if (!GetModuleFileNameA(g_hinstDLL, szFile, MAX_PATH)) return E_FAIL; // There are two type libraries: First the standard ASP typelib // then the typelib for the Transacted Script Context object. // Load them both. // First type lib, from default (first ITypeLib entry) location hr = SysAllocStringFromSz(szFile, 0, &bstrFile); if (FAILED(hr)) return hr; hr = LoadTypeLibEx(bstrFile, REGKIND_REGISTER, &pITypeLib); if (pITypeLib) { pITypeLib->Release(); pITypeLib = NULL; } SysFreeString(bstrFile); if (FAILED(hr)) return hr; // now register the Transacted Script Context Object strcat(szFile, "\\2"); hr = SysAllocStringFromSz(szFile, 0, &bstrFile); if (FAILED(hr)) return hr; hr = LoadTypeLibEx(bstrFile, REGKIND_REGISTER, &pITypeLib); if (pITypeLib) { pITypeLib->Release(); pITypeLib = NULL; } SysFreeString(bstrFile); return hr; } /*=================================================================== UnRegisterTypeLib UnRegister denali typelib in the registry. Note: Only the current version used by asp.dll is removed. Returns: HRESULT - S_OK on success Side effects: unregister denali typelib in the registry ===================================================================*/ HRESULT UnRegisterTypeLib(void) { HRESULT hr; ITypeLib *pITypeLib = NULL; TLIBATTR *pTLibAttr = NULL; char szFile[MAX_PATH + 4]; BSTR bstrFile; // Get the path and name of Denali if (!GetModuleFileNameA(g_hinstDLL, szFile, MAX_PATH)) return E_FAIL; hr = SysAllocStringFromSz(szFile, 0, &bstrFile); if (FAILED(hr)) return hr; hr = LoadTypeLibEx(bstrFile, REGKIND_REGISTER, &pITypeLib); if(SUCCEEDED(hr) && pITypeLib) { hr = pITypeLib->GetLibAttr(&pTLibAttr); if(SUCCEEDED(hr) && pTLibAttr) { hr = UnRegisterTypeLib( pTLibAttr->guid, pTLibAttr->wMajorVerNum, pTLibAttr->wMinorVerNum, pTLibAttr->lcid, pTLibAttr->syskind); pITypeLib->ReleaseTLibAttr(pTLibAttr); pTLibAttr = NULL; } pITypeLib->Release(); pITypeLib = NULL; } SysFreeString(bstrFile); // unregister the Txn typelib strcat(szFile, "\\2"); hr = SysAllocStringFromSz(szFile, 0, &bstrFile); if (FAILED(hr)) return hr; hr = LoadTypeLibEx(bstrFile, REGKIND_REGISTER, &pITypeLib); if(SUCCEEDED(hr) && pITypeLib) { hr = pITypeLib->GetLibAttr(&pTLibAttr); if(SUCCEEDED(hr) && pTLibAttr) { hr = UnRegisterTypeLib( pTLibAttr->guid, pTLibAttr->wMajorVerNum, pTLibAttr->wMinorVerNum, pTLibAttr->lcid, pTLibAttr->syskind); pITypeLib->ReleaseTLibAttr(pTLibAttr); pTLibAttr = NULL; } pITypeLib->Release(); pITypeLib = NULL; } SysFreeString(bstrFile); return hr; } HRESULT CreateCompiledTemplatesTempDir() { HRESULT hr = S_OK; BYTE szRegString[MAX_PATH]; BYTE pszExpanded[MAX_PATH]; int result = 0; EXPLICIT_ACCESSA ea[2]; PACL pNewDACL = NULL; SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; // read the temp dir name for the persistant templ // cache. CchLoadStringOfId(IDS_DEFAULTPERSISTDIR, (LPSTR)szRegString, MAX_PATH); result = ExpandEnvironmentStringsA((LPCSTR)szRegString, (LPSTR)pszExpanded, MAX_PATH); if ((result <= MAX_PATH) && (result > 0)) { CreateDirectoryA((LPCSTR)pszExpanded,NULL); } // this next section of code will place the SYSTEM and IWAM_<ComputerName> // ACEs on the directorie's ACL ZeroMemory(ea, sizeof(EXPLICIT_ACCESSA) * 2); ea[0].grfAccessPermissions = SYNCHRONIZE | GENERIC_ALL; ea[0].grfAccessMode = GRANT_ACCESS; ea[0].grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].grfAccessPermissions = SYNCHRONIZE | GENERIC_ALL; ea[1].grfAccessMode = GRANT_ACCESS; ea[1].grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_NAME; ea[1].Trustee.ptstrName = "IIS_WPG"; // Admin privilages. if (!AllocateAndInitializeSid(&NtAuthority, 2, // 2 sub-authorities SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0,0,0,0,0,0, (PSID *)(&ea[0].Trustee.ptstrName))) hr = HRESULT_FROM_WIN32(GetLastError()); else if ((hr = SetEntriesInAclA(2, ea, NULL, &pNewDACL)) != ERROR_SUCCESS); // set the ACL on the directory else hr = SetNamedSecurityInfoA((LPSTR)pszExpanded, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, pNewDACL, NULL); if (pNewDACL) LocalFree(pNewDACL); if (ea[0].Trustee.ptstrName) FreeSid(ea[0].Trustee.ptstrName); return(hr); } /*=================================================================== DllRegisterServer Entry point used by RegSvr32.exe to register the DLL. Returns: HRESULT - S_OK on success Side effects: Registers denali objects in the registry ===================================================================*/ STDAPI DllRegisterServer(void) { HRESULT hr = E_FAIL; HRESULT hrCoInit; hrCoInit = CoInitialize(NULL); if (FAILED(InitializeResourceDll())) goto LErr; // First try to unregister some stuff // This is important when we are registering on top of // an old IIS 3.0 Denali registration // Don't care if fails UnRegisterEventLog(); UnRegisterIntrinsics(); UnRegisterTypeLib(); // Now do the registration if (FAILED(hr = MDRegisterProperties())) goto LErr; // Register NT event log if(FAILED(hr = RegisterEventLog())) goto LErr; if (FAILED(hr = RegisterTypeLib())) goto LErr; // Register our intrinsics if (FAILED(hr = RegisterIntrinsics())) goto LErr; if (FAILED(hr = CreateCompiledTemplatesTempDir())) goto LErr; LErr: UninitializeResourceDll(); if (SUCCEEDED(hrCoInit)) CoUninitialize(); return(hr); } /*=================================================================== DllUnregisterServer Entry point used by RegSvr32.exe to unregister the DLL. Returns: HRESULT - S_OK on success Side effects: Removes denali registrations from the registry ===================================================================*/ STDAPI DllUnregisterServer(void) { HRESULT hr = S_OK, hrT; HRESULT hrCoInit; hrCoInit = CoInitialize(NULL); hrT = InitializeResourceDll(); if (FAILED(hrT)) hr = hrT; hrT = UnRegisterEventLog(); if (FAILED(hrT)) hr = hrT; hrT = MDUnRegisterProperties(); if (FAILED(hrT)) hr = hrT; hrT = UnRegisterIntrinsics(); if (FAILED(hrT)) hr = hrT; hrT = UnRegisterTypeLib(); if (FAILED(hrT)) hr = hrT; // UNDONE BUG 80063: Ignore errors from this call #ifdef UNDONE if (FAILED(hrT)) hr = hrT; #endif UninitializeResourceDll(); if (SUCCEEDED(hrCoInit)) CoUninitialize(); return(hr); }
32.191829
125
0.49062
[ "object" ]
894238130b26324be3107c03f892f48e40b49007
3,882
cpp
C++
tests/util/lock_free_ring_queue_bench.cpp
chisuhua/costream
7478900c35032e849a387a0a3c7b00c597b1e2d8
[ "MIT" ]
2,831
2015-12-24T03:21:07.000Z
2022-03-31T18:37:29.000Z
tests/util/lock_free_ring_queue_bench.cpp
chisuhua/costream
7478900c35032e849a387a0a3c7b00c597b1e2d8
[ "MIT" ]
238
2016-01-26T03:35:35.000Z
2022-03-18T11:17:00.000Z
tests/util/lock_free_ring_queue_bench.cpp
chisuhua/costream
7478900c35032e849a387a0a3c7b00c597b1e2d8
[ "MIT" ]
781
2015-12-24T04:28:34.000Z
2022-03-26T05:23:12.000Z
#include <iostream> #include <iomanip> #include <chrono> #include <thread> #include <vector> #include <assert.h> #include "../../libgo/common/lock_free_ring_queue.h" using namespace std; using namespace std::chrono; #define OUT(x) cout << #x << " = " << x << endl #define O(x) cout << x << endl struct Timer { Timer() : tp(system_clock::now()) {} virtual ~Timer() { auto dur = system_clock::now() - tp; O("Cost " << duration_cast<milliseconds>(dur).count() << " ms"); } system_clock::time_point tp; }; struct Bench : public Timer { Bench() : val(0) {} virtual ~Bench() { auto dur = system_clock::now() - tp; O("Per op: " << duration_cast<nanoseconds>(dur).count() / std::max(val, 1L) << " ns"); auto perf = (double)val / duration_cast<milliseconds>(dur).count() / 10; if (perf < 1) O("Performance: " << std::setprecision(3) << perf << " w/s"); else O("Performance: " << perf << " w/s"); } Bench& operator++() { ++val; return *this; } Bench& operator++(int) { ++val; return *this; } Bench& add(long v) { val += v; } long val; }; #define IS_UNIT_TEST 1 #define IS_DEBUG 0 struct A { static std::atomic<long> sCount; long val_; A() : val_(0) { ++sCount; } A(long val) : val_(val) { ++sCount; } A(A const& a) : val_(a.val_) { ++sCount; } A(A && a) : val_(a.val_) { a.val_ = 0; ++sCount; } ~A() { --sCount; } A& operator=(A const& a) { val_ = a.val_; } A& operator=(A && a) { val_ = a.val_; a.val_ = 0; } operator long() const { return val_; } }; std::atomic<long> A::sCount{0}; void AssertCount(long c, A*) { assert(A::sCount == c); } template <typename T> void AssertCount(long c, T*) { (void)c; } template <typename T = long> void test(int cap, int count, int rThreads, int wThreads) { co::LockFreeRingQueue<T> queue(cap); std::atomic_int lastCount{0}; volatile bool done = false; #if IS_UNIT_TEST AssertCount(0, (T*)nullptr); std::vector<std::atomic<long>*> check(wThreads, nullptr); for (auto & p : check) p = new std::atomic<long>{0}; #endif std::vector<thread*> tg; // read threads for (int i = 0; i < rThreads; ++i) { thread *t = new thread([&]{ T val; while (!done) { co::LockFreeResult result = queue.Pop(val); if (!result.success) continue; long l = val; int threadNumber = l >> 32; int idx = l & 0xffffffff; #if IS_DEBUG printf("pop thread=%d, idx=%d\n", threadNumber, idx); #endif if (idx == count) { if (++lastCount == wThreads) done = true; } #if IS_UNIT_TEST *check[threadNumber] += idx; #endif } }); tg.push_back(t); } // write threads for (int i = 0; i < wThreads; ++i) { thread *t = new thread([&, i]{ for (int j = 1; j <= count; ++j) { T val((long)j | (long)i << 32); while (!queue.Push(std::move(val)).success) ; #if IS_DEBUG printf("push thread=%d, idx=%d\n", i, j); #endif } }); tg.push_back(t); } // join for (auto pt : tg) pt->join(); #if IS_UNIT_TEST AssertCount(0, (T*)nullptr); long checkTotal = (1 + count) * count / 2; for (auto & p : check) { assert(*p == checkTotal); delete p; } #endif } int main() { { Timer t; test<A>(10000, 10000, 10, 10); } { Timer t; test(10000, 10000, 10, 10); } }
26.772414
525
0.484802
[ "vector" ]
895084f9c2093f1ad5a0463b2b90eaa277ae6edc
1,383
hpp
C++
ch02/linear_search.hpp
shbling/CLRS
0ce4ff74b8d2a6376a15306e2441e9a624597d17
[ "MIT" ]
1
2018-11-26T13:54:10.000Z
2018-11-26T13:54:10.000Z
ch02/linear_search.hpp
shbling/CLRS
0ce4ff74b8d2a6376a15306e2441e9a624597d17
[ "MIT" ]
null
null
null
ch02/linear_search.hpp
shbling/CLRS
0ce4ff74b8d2a6376a15306e2441e9a624597d17
[ "MIT" ]
null
null
null
/*************************************************************************** * @file insertion_sort.hpp * @author Alan.W * @date 22 Aug 2014 * @version 2 * @remark CLRS Algorithms implementation in C++ templates. ***************************************************************************/ //! //! ex2.1-3 //! Write pseudocode for linear search, which scans through the sequence, looking //! for . Using a loop invariant, prove that your algorithm is correct. Make sure that //! your loop invariant fulfills the three necessary properties. //! #ifndef LINEAR_SEARCH_HPP #define LINEAR_SEARCH_HPP #include <iterator.hpp> namespace clrs { namespace ch2 { /** * @brief linear_search * @param first * @param last * @param val * * @complexity O(n) * for ex2.1-3 */ template<typename Iter> Iter linear_search(Iter first, Iter last, const IterValue<Iter>& val) { for(auto curr = first; curr != last; ++curr) if(*curr == val) return curr; return last; } }}//namespace #endif // LINEAR_SEARCH_HPP //! @test //! //#include <iostream> //#include <vector> //#include "alan.hpp" //#include "linear_search.hpp" //int main() //{ // std::vector<int> v = {3,2,1,6,99,0}; // std::cout << *clrs::ch2::linear_search(v.begin(),v.end(),99); // alan::end(); // return 0; //} //! @output: //! //99 //exit normally
22.306452
86
0.558207
[ "vector" ]
895bbda5af24d5c5c6a8355b44153a13591fa9dd
6,410
cpp
C++
Classes/CrushableModel.cpp
Mshnik/Pineapple
378917353d22d8497769ed8e45d9a73b40d2717e
[ "MIT" ]
null
null
null
Classes/CrushableModel.cpp
Mshnik/Pineapple
378917353d22d8497769ed8e45d9a73b40d2717e
[ "MIT" ]
null
null
null
Classes/CrushableModel.cpp
Mshnik/Pineapple
378917353d22d8497769ed8e45d9a73b40d2717e
[ "MIT" ]
1
2019-12-25T02:32:13.000Z
2019-12-25T02:32:13.000Z
#include "CrushableModel.h" #include <cornell/CUPolygonNode.h> #include <cornell/CUAssetManager.h> #include <cornell/CUSceneManager.h> #pragma mark - #pragma mark Physics Constants /** The amount to shrink the body fixture (vertically) relative to the image */ #define CRUSHABLE_VSHRINK 0.3f /** The amount to shrink the body fixture (horizontally) relative to the image */ #define CRUSHABLE_HSHRINK 0.3f #pragma mark - #pragma mark Static Constructors /** * Creates a new crushable at the origin. * * The crushable is scaled so that 1 pixel = 1 Box2d unit * * The scene graph is completely decoupled from the physics system. * The node does not have to be the same size as the physics body. We * only guarantee that the scene graph node is positioned correctly * according to the drawing scale. * * @return An retained physics object */ CrushableModel* CrushableModel::create(const char* texture) { CrushableModel* crushable = new (std::nothrow) CrushableModel(); if (crushable && crushable->init(texture)) { crushable->retain(); return crushable; } CC_SAFE_DELETE(crushable); return nullptr; } /** * Creates a new crushable at the given position. * * The crushable is scaled so that 1 pixel = 1 Box2d unit * * The scene graph is completely decoupled from the physics system. * The node does not have to be the same size as the physics body. We * only guarantee that the scene graph node is positioned correctly * according to the drawing scale. * * @param pos Initial position in world coordinates * * @return An retained physics object */ CrushableModel* CrushableModel::create(const char* texture, int x, int y, const Vec2& pos) { CrushableModel* crushable = new (std::nothrow) CrushableModel(); if (crushable && crushable->init(texture, x, y, pos)) { crushable->retain(); return crushable; } CC_SAFE_DELETE(crushable); return nullptr; } /** * Creates a new crushable at the given position. * * The crushable is sized according to the given drawing scale. * * The scene graph is completely decoupled from the physics system. * The node does not have to be the same size as the physics body. We * only guarantee that the scene graph node is positioned correctly * according to the drawing scale. * * @param pos Initial position in world coordinates * @param scale The drawing scale * * @return An retain physics object */ CrushableModel* CrushableModel::create(const char* texture, int x, int y, const Vec2& pos, const Vec2& scale) { CrushableModel* crushable = new (std::nothrow) CrushableModel(); if (crushable && crushable->init(texture, x, y, pos, scale)) { crushable->retain(); return crushable; } CC_SAFE_DELETE(crushable); return nullptr; } #pragma mark - #pragma mark Initializers /** * Initializes a new crushable at the given position. * * The crushable is sized according to the given drawing scale. * * The scene graph is completely decoupled from the physics system. * The node does not have to be the same size as the physics body. We * only guarantee that the scene graph node is positioned correctly * according to the drawing scale. * * @param pos Initial position in world coordinates * @param scale The drawing scale * * @return true if the obstacle is initialized properly, false otherwise. */ bool CrushableModel::init(const char* texture, int x, int y, const Vec2& pos, const Vec2& scale) { if (BoxObstacle::init(pos, Size(scale))) { _movedDown = false; _textureName = texture; _tiledYCoord = y; _tiledXCoord = x; _smashCycleFrame = 0.0f; _smashing = false; _smashed = false; return true; } return false; } #pragma mark - #pragma mark Physics Methods /** * Create new fixtures for this body, defining the shape * * This is the primary method to override for custom physics objects */ void CrushableModel::createFixtures() { if (_body == nullptr) { return; } BoxObstacle::createFixtures(); } /** * Release the fixtures for this body, reseting the shape * * This is the primary method to override for custom physics objects. */ void CrushableModel::releaseFixtures() { if (_body != nullptr) { return; } BoxObstacle::releaseFixtures(); } /** * Updates the object's physics state (NOT GAME LOGIC). * * We use this method to reset cooldowns. * * @param delta Number of seconds since last animation frame */ void CrushableModel::update(float dt) { BoxObstacle::update(dt); } /** * Animate the cup if it's being smashed */ void CrushableModel::animate() { if (_smashing) { _smashCycleFrame += 0.5f; int tmp = (int)rint(_smashCycleFrame); if (tmp < CUP_SMASH_FRAMES) { _smashCycle->setFrame(tmp); } else { _smashed = true; } } } #pragma mark - #pragma mark Scene Graph Methods /** * Performs any necessary additions to the scene graph node. * * This method is necessary for custom physics objects that are composed * of multiple scene graph nodes. In this case, it is because we * manage our own afterburner animations. */ void CrushableModel::resetSceneNode() { AnimationNode* pnode = dynamic_cast<AnimationNode*>(_node); if (pnode != nullptr) { // We need to know the content scale for resolution independence // If the device is higher resolution than 1024x576, Cocos2d will scale it // THIS DOES NOT FIX ASPECT RATIO PROBLEMS // If you are using a device with a 3:2 aspect ratio, you will need to // completely redo the level layout. We can help if this is an issue. float cscale = Director::getInstance()->getContentScaleFactor(); Rect bounds; bounds.size = pnode->getContentSize(); pnode->setPolygon(bounds); pnode->setScale(cscale * CRUSHABLE_SCALE); pnode->setFrame(0); setDimension(pnode->getContentSize().width * CRUSHABLE_HSHRINK / _drawScale.x, pnode->getContentSize().height * CRUSHABLE_VSHRINK / _drawScale.y); pnode->setFrame(0); _smashCycleFrame = 0.0f; _smashCycle = pnode; } } /** * Redraws the outline of the physics fixtures to the debug node * * The debug node is use to outline the fixtures attached to this object. * This is very useful when the fixtures have a very different shape than * the texture (e.g. a circular shape attached to a square texture). */ void CrushableModel::resetDebugNode() { BoxObstacle::resetDebugNode(); }
29.004525
111
0.711856
[ "object", "shape" ]
896903e0098c10b4fb365c83815dacb77b22af85
18,688
cpp
C++
20/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
null
null
null
20/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
null
null
null
20/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
1
2020-12-20T16:35:13.000Z
2020-12-20T16:35:13.000Z
#include <fstream> #include <iostream> #include <regex> #include <sstream> #include <unordered_set> #include <vector> enum Pos { TOP, TOP_R, BOTTOM, BOTTOM_R, LEFT, LEFT_R, RIGHT, RIGHT_R, EMPTY, }; class Tile { public: Tile() { index = -1; } Tile( size_t num ) { index = num; } size_t getIndex() const { return index; } void addLine( const std::string &input ) { std::vector<bool> tmp{}; for ( auto c : input ) { switch ( c ) { case '.': tmp.push_back( false ); break; case '#': tmp.push_back( true ); default: break; } } lines.push_back( tmp ); } void checkTile( size_t index, const std::vector<Tile> &tiles ) { // check if `index` is current tile's neighbour auto top = getTop(); auto res = checkLine( top, index, tiles ); if ( res.first ) top_neighbour = { index, res.second }; auto bottom = getBottom(); res = checkLine( bottom, index, tiles ); if ( res.first ) bottom_neighbour = { index, res.second }; auto left = getLeft(); res = checkLine( left, index, tiles ); if ( res.first ) left_neighbour = { index, res.second }; auto right = getRight(); res = checkLine( right, index, tiles ); if ( res.first ) right_neighbour = { index, res.second }; } std::vector<bool> getTop() const { return lines[0]; } std::vector<bool> getTopReversed() const { auto ret = getTop(); std::reverse( ret.begin(), ret.end() ); return ret; } std::vector<bool> getBottom() const { return lines.back(); } std::vector<bool> getBottomReversed() const { auto ret = getBottom(); std::reverse( ret.begin(), ret.end() ); return ret; } std::vector<bool> getLeft() const { std::vector<bool> ret{}; for ( auto &line : lines ) { ret.push_back( line[0] ); } return ret; } std::vector<bool> getLeftReversed() const { auto ret = getLeft(); std::reverse( ret.begin(), ret.end() ); return ret; } std::vector<bool> getRight() const { std::vector<bool> ret{}; for ( auto &line : lines ) { ret.push_back( line.back() ); } return ret; } std::vector<bool> getRightReversed() const { auto ret = getRight(); std::reverse( ret.begin(), ret.end() ); return ret; } bool isCorner() const { // check if tile is a corner (needs to not have neighbour on 2 // neighbouring edgeds) bool lr = left_neighbour.first == (size_t)-1 || right_neighbour.first == (size_t)-1; bool tb = top_neighbour.first == (size_t)-1 || bottom_neighbour.first == (size_t)-1; return lr && tb; } size_t getRightNeighbour() { return right_neighbour.first; } size_t getBottomNeighbour() { return bottom_neighbour.first; } Pos getRightPos() { return right_neighbour.second; } Pos getBottomPos() { return bottom_neighbour.second; } Pos getLeftPos() { return left_neighbour.second; } Pos getTopPos() { return top_neighbour.second; } void fixSelf( Pos left, Pos top ) { if ( top == EMPTY ) { switch ( left ) { case TOP: rotateLeft(); flipHorizontal(); break; case TOP_R: rotateLeft(); break; case BOTTOM: rotateRight(); break; case BOTTOM_R: rotateRight(); flipHorizontal(); break; case LEFT: break; case LEFT_R: flipHorizontal(); break; case RIGHT: flipVertical(); break; case RIGHT_R: flipVertical(); flipHorizontal(); default: break; } } else { switch ( top ) { case TOP: break; case TOP_R: flipVertical(); break; case BOTTOM: flipHorizontal(); break; case BOTTOM_R: flipHorizontal(); flipVertical(); break; case LEFT: rotateRight(); flipVertical(); break; case LEFT_R: rotateRight(); break; case RIGHT: rotateLeft(); break; case RIGHT_R: rotateLeft(); flipVertical(); default: break; } } } std::vector<std::string> getPicture() { std::vector<std::string> ret{}; for ( size_t i = 1; i < lines.size() - 1; i++ ) { std::string tmp{}; for ( size_t j = 1; j < lines[i].size() - 1; j++ ) { if ( lines[i][j] ) { tmp += '#'; } else { tmp += '.'; } } ret.push_back( tmp ); } return ret; } void rotateLeft() { std::vector<std::vector<bool>> ret{}; for ( size_t i = lines[0].size() - 1; i > 0; i-- ) { std::vector<bool> tmp{}; for ( auto &line : lines ) { tmp.push_back( line[i] ); } ret.push_back( tmp ); } std::vector<bool> tmp{}; for ( auto &line : lines ) { tmp.push_back( line[0] ); } ret.push_back( tmp ); lines = ret; auto tmp_n = left_neighbour; left_neighbour = top_neighbour; top_neighbour = right_neighbour; right_neighbour = bottom_neighbour; bottom_neighbour = tmp_n; right_neighbour.second = reverse( right_neighbour.second ); left_neighbour.second = reverse( left_neighbour.second ); } void rotateRight() { std::vector<std::vector<bool>> ret{}; for ( size_t i = 0; i < lines[0].size(); i++ ) { std::vector<bool> tmp{}; for ( size_t j = lines[0].size() - 1; j > 0; j-- ) { tmp.push_back( lines[j][i] ); } tmp.push_back( lines[0][i] ); ret.push_back( tmp ); } lines = ret; auto tmp_n = left_neighbour; left_neighbour = bottom_neighbour; bottom_neighbour = right_neighbour; right_neighbour = top_neighbour; top_neighbour = tmp_n; top_neighbour.second = reverse( top_neighbour.second ); bottom_neighbour.second = reverse( bottom_neighbour.second ); } void flipVertical() { std::vector<std::vector<bool>> ret{}; for ( size_t i = 0; i < lines.size(); i++ ) { std::vector<bool> tmp{}; for ( size_t j = lines[i].size() - 1; j > 0; j-- ) { tmp.push_back( lines[i][j] ); } tmp.push_back( lines[i][0] ); ret.push_back( tmp ); } lines = ret; auto tmp_n = left_neighbour; left_neighbour = right_neighbour; right_neighbour = tmp_n; top_neighbour.second = reverse( top_neighbour.second ); bottom_neighbour.second = reverse( bottom_neighbour.second ); } void flipHorizontal() { std::vector<std::vector<bool>> ret{}; for ( size_t i = lines.size() - 1; i > 0; i-- ) { ret.push_back( lines[i] ); } ret.push_back( lines[0] ); lines = ret; auto tmp_n = top_neighbour; top_neighbour = bottom_neighbour; bottom_neighbour = tmp_n; right_neighbour.second = reverse( right_neighbour.second ); left_neighbour.second = reverse( left_neighbour.second ); } private: std::pair<bool, Pos> checkLine( const std::vector<bool> &input, size_t index, const std::vector<Tile> &tiles ) { // check if `input` matches any edges of tile with index `index` auto bottom = tiles[index].getBottom(); auto bottom_r = tiles[index].getBottomReversed(); auto top = tiles[index].getTop(); auto top_r = tiles[index].getTopReversed(); if ( input == bottom ) return { true, BOTTOM }; if ( input == bottom_r ) return { true, BOTTOM_R }; if ( input == top ) return { true, TOP }; if ( input == top_r ) return { true, TOP_R }; auto left = tiles[index].getLeft(); auto left_r = tiles[index].getLeftReversed(); auto right = tiles[index].getRight(); auto right_r = tiles[index].getRightReversed(); if ( input == left ) return { true, LEFT }; if ( input == left_r ) return { true, LEFT_R }; if ( input == right ) return { true, RIGHT }; if ( input == right_r ) return { true, RIGHT_R }; return { false, EMPTY }; } Pos reverse( Pos input ) { switch ( input ) { case TOP: return TOP_R; case TOP_R: return TOP; case BOTTOM: return BOTTOM_R; case BOTTOM_R: return BOTTOM; case LEFT: return LEFT_R; case LEFT_R: return LEFT; case RIGHT: return RIGHT_R; case RIGHT_R: return RIGHT; case EMPTY: return EMPTY; } } size_t index; std::vector<std::vector<bool>> lines; std::pair<size_t, Pos> left_neighbour = { -1, EMPTY }; std::pair<size_t, Pos> right_neighbour = { -1, EMPTY }; std::pair<size_t, Pos> top_neighbour = { -1, EMPTY }; std::pair<size_t, Pos> bottom_neighbour = { -1, EMPTY }; }; std::vector<Tile> getTiles( std::ifstream &file ) { std::vector<Tile> ret{}; std::string str{}; int index; Tile tmp{}; bool next_is_index = true; while ( std::getline( file, str ) ) { if ( str == "" ) { ret.push_back( tmp ); next_is_index = true; continue; } if ( next_is_index ) { next_is_index = false; std::stringstream ss( str ); ss >> str; ss >> index; tmp = Tile( index ); } else { tmp.addLine( str ); } } if ( ret.back().getIndex() != tmp.getIndex() ) ret.push_back( tmp ); return ret; } void findNeighbours( std::vector<Tile> &tiles ) { for ( size_t i = 0; i < tiles.size(); i++ ) { for ( size_t j = 0; j < tiles.size(); j++ ) { if ( i != j ) { tiles[i].checkTile( j, tiles ); } } } } std::vector<size_t> findCorners( const std::vector<Tile> &tiles ) { std::vector<size_t> ret{}; for ( size_t i = 0; i < tiles.size(); i++ ) { if ( tiles[i].isCorner() ) { ret.push_back( i ); } } return ret; } void correctTiles( std::vector<Tile> &tiles, size_t anchor_index ) { // rotate tiles so their edges are correctly oriented Tile *start = &tiles[anchor_index]; Tile *prev_start = start; while ( true ) { Tile *cur = start; Tile *prev_cur = cur; while ( true ) { if ( prev_cur == cur ) { if ( prev_start == start ) { cur->fixSelf( EMPTY, EMPTY ); } else { cur->fixSelf( EMPTY, prev_start->getBottomPos() ); } } else { cur->fixSelf( prev_cur->getRightPos(), EMPTY ); } auto next = cur->getRightNeighbour(); if ( next == static_cast<size_t>( -1 ) ) { break; } prev_cur = cur; cur = &tiles[next]; } auto next = start->getBottomNeighbour(); if ( next == static_cast<size_t>( -1 ) ) { break; } prev_start = start; start = &tiles[next]; } } std::vector<std::string> reconstructPicture( std::vector<Tile> &tiles, size_t topleft ) { std::vector<std::string> ret{}; Tile *start = &tiles[topleft]; while ( start != nullptr ) { Tile *cur = start; auto initial = cur->getPicture(); do { cur = &tiles[cur->getRightNeighbour()]; auto pic = cur->getPicture(); for ( size_t i = 0; i < initial.size(); i++ ) { initial[i] += pic[i]; } } while ( cur->getRightNeighbour() != static_cast<size_t>( -1 ) ); for ( auto &line : initial ) { ret.push_back( std::move( line ) ); } auto index = start->getBottomNeighbour(); if ( index == static_cast<size_t>( -1 ) ) start = nullptr; else start = &tiles[index]; } return ret; } void makeTopLeftV1( size_t index, std::vector<Tile> &tiles ) { Tile &worker = tiles[index]; while ( worker.getTopPos() != EMPTY || worker.getLeftPos() != EMPTY ) { worker.rotateLeft(); } } void makeTopLeftV2( size_t index, std::vector<Tile> &tiles ) { Tile &worker = tiles[index]; worker.flipHorizontal(); while ( worker.getTopPos() != EMPTY || worker.getLeftPos() != EMPTY ) { worker.rotateLeft(); } } size_t findMin( std::vector<size_t> &input ) { size_t min = 0; for ( size_t i = 1; i < input.size(); i++ ) { if ( input[i] < input[min] ) min = i; } return min; } bool checkMonster( size_t line, size_t head_pos, const std::vector<std::string> &picture ) { if ( head_pos < 18 ) return false; if ( picture[line][head_pos] != '#' ) return false; line++; if ( picture[line][head_pos - 18] != '#' ) return false; if ( picture[line][head_pos - 13] != '#' ) return false; if ( picture[line][head_pos - 12] != '#' ) return false; if ( picture[line][head_pos - 7] != '#' ) return false; if ( picture[line][head_pos - 6] != '#' ) return false; if ( picture[line][head_pos - 1] != '#' ) return false; if ( picture[line][head_pos] != '#' ) return false; if ( picture[line][head_pos + 1] != '#' ) return false; line++; if ( picture[line][head_pos - 17] != '#' ) return false; if ( picture[line][head_pos - 14] != '#' ) return false; if ( picture[line][head_pos - 11] != '#' ) return false; if ( picture[line][head_pos - 8] != '#' ) return false; if ( picture[line][head_pos - 5] != '#' ) return false; if ( picture[line][head_pos - 2] != '#' ) return false; return true; } void deleteMonster( size_t line, size_t head_pos, std::vector<std::string> &picture ) { picture[line][head_pos] = 'O'; line++; picture[line][head_pos - 18] = 'O'; picture[line][head_pos - 13] = 'O'; picture[line][head_pos - 12] = 'O'; picture[line][head_pos - 7] = 'O'; picture[line][head_pos - 6] = 'O'; picture[line][head_pos - 1] = 'O'; picture[line][head_pos] = 'O'; picture[line][head_pos + 1] = 'O'; line++; picture[line][head_pos - 17] = 'O'; picture[line][head_pos - 14] = 'O'; picture[line][head_pos - 11] = 'O'; picture[line][head_pos - 8] = 'O'; picture[line][head_pos - 5] = 'O'; picture[line][head_pos - 2] = 'O'; } std::string prettify( const std::string &input ) { std::string ret = ""; size_t pos = 0; size_t prev_pos = 0; while ( ( pos = input.find( 'O', pos ) ) != std::string::npos ) { ret += input.substr( prev_pos, pos - prev_pos ); pos++; ret += "\033[93;1mO\033[0m"; prev_pos = pos; } ret += input.substr( prev_pos ); return ret; } int main( int argc, char **argv ) { std::ifstream input_file( "input" ); auto tiles = getTiles( input_file ); findNeighbours( tiles ); auto corners = findCorners( tiles ); std::string corners_str{}; size_t res = 1; for ( size_t i = 0; i < corners.size() - 1; i++ ) { corners_str += std::to_string( tiles[corners[i]].getIndex() ) + ", "; res *= tiles[corners[i]].getIndex(); } corners_str += std::to_string( tiles[corners.back()].getIndex() ); res *= tiles[corners.back()].getIndex(); std::cout << "The multiplication is: \033[93;1m" << res << "\033[0m (\033[91;1m" << corners_str << "\033[0m)" << std::endl; std::vector<std::vector<std::string>> pictures{}; for ( auto corner : corners ) { std::vector<Tile> workTiles = tiles; makeTopLeftV1( corner, workTiles ); correctTiles( workTiles, corner ); pictures.push_back( reconstructPicture( workTiles, corner ) ); workTiles = tiles; makeTopLeftV2( corner, workTiles ); correctTiles( workTiles, corner ); pictures.push_back( reconstructPicture( workTiles, corner ) ); } std::vector<size_t> picture_hashes; for ( auto &picture : pictures ) { std::smatch sm; for ( size_t i = 0; i < picture.size() - 1; i++ ) { for ( size_t j = 18; j < picture[i].length(); j++ ) { if ( checkMonster( i, j, picture ) ) deleteMonster( i, j, picture ); } } size_t hashes = 0; for ( auto &line : picture ) { for ( auto &c : line ) { if ( c == '#' ) hashes++; } } picture_hashes.push_back( hashes ); } auto result_index = findMin( picture_hashes ); std::cout << "There are \033[93;1m" << picture_hashes[result_index] << "\033[0m hashes" << std::endl; if ( argc == 2 && !strcmp( argv[1], "--monsters" ) ) { std::cout << "MONSTER LAKE: " << std::endl; for ( auto &line : pictures[result_index] ) { std::cout << prettify( line ) << std::endl; } } }
29.476341
77
0.488656
[ "vector" ]
897229b483b92249908d64edaecfcf9cccc7d3ff
7,056
cpp
C++
FlexEngine/src/Cameras/VehicleCamera.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
762
2017-11-07T23:40:58.000Z
2022-03-31T16:03:22.000Z
FlexEngine/src/Cameras/VehicleCamera.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
5
2018-03-13T14:41:06.000Z
2020-11-01T12:02:29.000Z
FlexEngine/src/Cameras/VehicleCamera.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
43
2017-11-17T11:22:37.000Z
2022-03-14T01:51:19.000Z
#include "stdafx.hpp" #include "Cameras/VehicleCamera.hpp" IGNORE_WARNINGS_PUSH #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> // for rotateY #include <glm/vec2.hpp> #include <LinearMath/btIDebugDraw.h> IGNORE_WARNINGS_POP #include "Graphics/Renderer.hpp" #include "Helpers.hpp" #include "InputManager.hpp" #include "Physics/RigidBody.hpp" #include "Player.hpp" #include "Scene/BaseScene.hpp" #include "Scene/GameObject.hpp" #include "Scene/SceneManager.hpp" #include "Window/Window.hpp" namespace flex { VehicleCamera::VehicleCamera(real FOV) : BaseCamera("vehicle", CameraType::VEHICLE, true, FOV), m_SpeedFactors(256), m_TargetFollowDist(256), m_LastLookOffset(VEC2_ZERO) { bPossessPlayer = true; m_SpeedFactors.overrideMin = 0.0f; m_SpeedFactors.overrideMax = 1.0f; ResetValues(); } VehicleCamera::~VehicleCamera() { } void VehicleCamera::Initialize() { if (!m_bInitialized) { if (m_TrackedVehicle == nullptr) { FindActiveVehicle(); } m_TargetPosRollingAvg = RollingAverage<glm::vec3>(15, SamplingType::LINEAR); m_TargetForwardRollingAvg = RollingAverage<glm::vec3>(30, SamplingType::LINEAR); m_TargetVelMagnitudeRollingAvg = RollingAverage<real>(30, SamplingType::LINEAR); m_LookOffsetRollingAvg = RollingAverage<glm::vec2>(15, SamplingType::CUBIC); ResetValues(); BaseCamera::Initialize(); } } void VehicleCamera::OnSceneChanged() { BaseCamera::OnSceneChanged(); m_TrackedVehicle = nullptr; FindActiveVehicle(); ResetValues(); } void VehicleCamera::Update() { BaseCamera::Update(); if (m_TrackedVehicle == nullptr) { return; } Transform* targetTransform = m_TrackedVehicle->GetTransform(); btRigidBody* trackedRB = m_TrackedVehicle->GetRigidBody()->GetRigidBodyInternal(); m_TargetForwardRollingAvg.AddValue(targetTransform->GetForward()); m_TargetVelMagnitudeRollingAvg.AddValue(trackedRB->getLinearVelocity().length()); m_TargetPosRollingAvg.AddValue(targetTransform->GetWorldPosition()); m_TargetLookAtPos = m_TargetPosRollingAvg.currentAverage; real newLookOffsetH = -g_InputManager->GetActionAxisValue(Action::VEHICLE_LOOK_LEFT) + g_InputManager->GetActionAxisValue(Action::VEHICLE_LOOK_RIGHT); real newLookOffsetV = -g_InputManager->GetActionAxisValue(Action::VEHICLE_LOOK_UP) + g_InputManager->GetActionAxisValue(Action::VEHICLE_LOOK_DOWN); m_LookOffsetRollingAvg.AddValue(glm::vec2(newLookOffsetH, newLookOffsetV) * m_LookOffsetMagnitude); #if THOROUGH_CHECKS ENSURE(!IsNanOrInf(m_TargetLookAtPos)); #endif SetLookAt(); glm::vec3 desiredPos = GetOffsetPosition(m_TargetLookAtPos); position = desiredPos; CalculateYawAndPitchFromForward(); RecalculateViewProjection(); } void VehicleCamera::DrawImGuiObjects() { if (m_TrackedVehicle != nullptr) { if (ImGui::TreeNode("Vehicle camera")) { Transform* targetTransform = m_TrackedVehicle->GetTransform(); glm::vec3 start = targetTransform->GetWorldPosition(); glm::vec3 end = start + m_TargetForwardRollingAvg.currentAverage * 10.0f; g_Renderer->GetDebugDrawer()->drawLine(ToBtVec3(start), ToBtVec3(end), btVector3(1.0f, 1.0f, 1.0f)); ImGui::Text("Avg target forward: %s", VecToString(m_TargetForwardRollingAvg.currentAverage, 2).c_str()); ImGui::Text("For: %s", VecToString(forward, 2).c_str()); ImGui::TreePop(); ImGui::SliderFloat("Rotation update speed", &m_RotationUpdateSpeed, 0.001f, 50.0f); ImGui::SliderFloat("Dist update speed", &m_DistanceUpdateSpeed, 0.001f, 10.0f); ImGui::SliderFloat("Min target speed zoom threshold", &m_MinSpeed, 1.0f, 50.0f); ImGui::SliderFloat("Max target speed zoom threshold", &m_MaxSpeed, 1.0f, 50.0f); ImGui::SliderFloat("Closest dist", &m_ClosestDist, 1.0f, 60.0f); ImGui::SliderFloat("Furthest dist", &m_FurthestDist, 1.0f, 90.0f); ImGui::SliderFloat("Min downward angle", &m_MinDownwardAngle, 0.0f, 3.0f); ImGui::SliderFloat("Max downward angle", &m_MaxDownwardAngle, 0.0f, 3.0f); ImGui::SliderFloat("Look dist lerp speed", &m_LookDistLerpSpeed, 0.0f, 50.0f); ImGui::SliderFloat("Look offset magnitude", &m_LookOffsetMagnitude, 0.0f, 10.0f); m_SpeedFactors.DrawImGui(); m_TargetFollowDist.DrawImGui(); } } } glm::vec3 VehicleCamera::GetOffsetPosition(const glm::vec3& lookAtPos) { // TODO: Handle camera cut to stationary vehicle? (use vehicle forward rather than vel) glm::vec3 backward = -m_TargetForwardRollingAvg.currentAverage; real minOffsetY = 0.0f; if (backward.y < minOffsetY) { backward.y = minOffsetY; backward = glm::normalize(backward); } // TODO: Check for collisions real speedFactor = glm::clamp((m_TargetVelMagnitudeRollingAvg.currentAverage - m_MinSpeed) / (m_MaxSpeed - m_MinSpeed), 0.0f, 1.0f); glm::vec3 upward = VEC3_UP * Lerp(m_MaxDownwardAngle, m_MinDownwardAngle, speedFactor); real targetFollowDistance = Lerp(m_ClosestDist, m_FurthestDist, speedFactor); real previousFollowDistance = glm::distance(position, lookAtPos); real distUpdateDelta = glm::clamp(1.0f - g_DeltaTime * m_DistanceUpdateSpeed / 1000.0f, 0.0f, 1.0f); real followDistance = Lerp(previousFollowDistance, targetFollowDistance, distUpdateDelta); glm::vec3 offsetVec = glm::normalize(upward + backward) * followDistance; m_SpeedFactors.AddElement(speedFactor); m_TargetFollowDist.AddElement(glm::length(offsetVec)); Transform* targetTransform = m_TrackedVehicle->GetTransform(); glm::vec2 lookOffset = MoveTowards(m_LastLookOffset, m_LookOffsetRollingAvg.currentAverage, g_DeltaTime * m_LookDistLerpSpeed); glm::vec3 lookOffset3 = targetTransform->GetRight() * lookOffset.x + targetTransform->GetUp() * lookOffset.y; m_LastLookOffset = lookOffset; return lookAtPos + offsetVec + lookOffset3; } void VehicleCamera::SetPosAndLookAt() { if (m_TrackedVehicle == nullptr) { return; } Transform* targetTransform = m_TrackedVehicle->GetTransform(); m_TargetLookAtPos = targetTransform->GetWorldPosition(); glm::vec3 desiredPos = GetOffsetPosition(m_TargetLookAtPos); position = desiredPos; SetLookAt(); } void VehicleCamera::SetLookAt() { forward = glm::normalize(m_TargetLookAtPos - position); right = normalize(glm::cross(VEC3_UP, forward)); up = cross(forward, right); } void VehicleCamera::FindActiveVehicle() { Player* player0 = g_SceneManager->CurrentScene()->GetPlayer(0); if (player0 != nullptr) { m_TrackedVehicle = (Vehicle*)player0->ridingVehicleID.Get(); } } void VehicleCamera::ResetValues() { ResetOrientation(); m_Vel = VEC3_ZERO; pitch = -PI_DIV_FOUR; SetPosAndLookAt(); if (m_TrackedVehicle != nullptr) { Transform* targetTransform = m_TrackedVehicle->GetTransform(); m_TargetPosRollingAvg.Reset(targetTransform->GetWorldPosition()); m_TargetForwardRollingAvg.Reset(targetTransform->GetForward()); } else { m_TargetPosRollingAvg.Reset(); m_TargetForwardRollingAvg.Reset(); } RecalculateViewProjection(); } } // namespace flex
30.413793
152
0.743339
[ "transform" ]
897b3b4824ca17677c7703b4c60775aca179f9dc
2,580
hpp
C++
GC/TinyPrep.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
GC/TinyPrep.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
3
2022-02-22T16:14:53.000Z
2022-02-22T16:37:41.000Z
GC/TinyPrep.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
/* * TinyPrep.cpp * */ #include "TinierSharePrep.h" #include "Protocols/MascotPrep.hpp" namespace GC { template<class T> void TinierSharePrep<T>::init_real(Player& P) { assert(real_triple_generator == 0); auto& thread = ShareThread<secret_type>::s(); real_triple_generator = new typename T::whole_type::TripleGenerator( BaseMachine::fresh_ot_setup(P), P.N, -1, OnlineOptions::singleton.batch_size, 1, params, thread.MC->get_alphai(), &P); real_triple_generator->multi_threaded = false; } template<class T> void TinierSharePrep<T>::buffer_secret_triples() { auto& thread = ShareThread<secret_type>::s(); auto& triple_generator = real_triple_generator; assert(triple_generator != 0); params.generateBits = false; vector<array<T, 3>> triples; TripleShuffleSacrifice<T> sacrifice; size_t required; required = sacrifice.minimum_n_inputs_with_combining(); while (triples.size() < required) { triple_generator->generatePlainTriples(); triple_generator->unlock(); assert(triple_generator->plainTriples.size() != 0); for (size_t i = 0; i < triple_generator->plainTriples.size(); i++) triple_generator->valueBits[2].set_portion(i, triple_generator->plainTriples[i][2]); triple_generator->run_multipliers({}); assert(triple_generator->plainTriples.size() != 0); for (size_t i = 0; i < triple_generator->plainTriples.size(); i++) { int dl = secret_type::default_length; for (int j = 0; j < dl; j++) { triples.push_back({}); for (int k = 0; k < 3; k++) { auto& share = triples.back()[k]; share.set_share( triple_generator->plainTriples.at(i).at(k).get_bit( j)); typename T::mac_type mac; mac = thread.MC->get_alphai() * share.get_share(); for (auto& multiplier : triple_generator->ot_multipliers) mac += multiplier->macs.at(k).at(i * dl + j); share.set_mac(mac); } } } } sacrifice.triple_sacrifice(triples, triples, *thread.P, thread.MC->get_part_MC()); sacrifice.triple_combine(triples, triples, *thread.P, thread.MC->get_part_MC()); for (auto& triple : triples) this->triples.push_back(triple); } } /* namespace GC */
33.947368
79
0.574419
[ "vector" ]
897bebd3a32c9dea9fa3c10d320681e8ad465988
2,647
cpp
C++
UVA00670.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
17
2015-12-08T18:50:03.000Z
2022-03-16T01:23:20.000Z
UVA00670.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
null
null
null
UVA00670.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
6
2017-04-04T18:16:23.000Z
2020-06-28T11:07:22.000Z
#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <utility> #include <cmath> using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; int mf, f, s, t, INF = 2000000; int res[204][204]; vi p; inline double dis(int x0, int y0, int x1, int y1) { return sqrt((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1)); } void augment(int v, int minEdge) { if (v == s) { f = minEdge; return; } else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); res[p[v]][v] -= f; res[v][p[v]] += f; } } int main() { int L; cin >> L; while (L--) { int N, M; cin >> N >> M; vector<ii> v(N, ii(0, 0)); vector<ii> P(M, ii(0, 0)); for (int i = 0; i < N; i++) { cin >> v[i].first >> v[i].second; } for (int i = 0; i < M; i++) { cin >> P[i].first >> P[i].second; } for (int i = 0; i < N+M+1; i++) for (int j = 0; j < N+M+1; j++) res[i][j] = 0; for (int i = 0; i < N - 1; i++) { for (int j = 0; j < M; j++) { if (dis(v[i].first, v[i].second, P[j].first, P[j].second) + dis(v[i+1].first, v[i+1].second, P[j].first, P[j].second) <= 2*dis(v[i].first, v[i].second, v[i+1].first, v[i+1].second)) { res[i+1][j+N] = 1; } } } for (int i = 1; i < N; i++) res[0][i] = 1; for (int i = 0; i < M; i++) res[i+N][N+M] = 1; s = 0, t = N+M; mf = 0; while (true) { f = 0; vi dist(N+M+1, INF); dist[s] = 0; queue<int> q; q.push(s); p.assign(N+M+1, -1); while (!q.empty()) { int u = q.front(); q.pop(); if (u == t) break; for (int v = 0; v < N+M+1; v++) { if (res[u][v] > 0 && dist[v] == INF) { dist[v] = dist[u] + 1, q.push(v), p[v] = u; } } } augment(t, INF); if (f == 0) break; mf += f; } printf("%d\n", mf + N); for (int i = 0; i < N - 1; i++) { printf("%d %d ", v[i].first, v[i].second); for (int j = 0; j < M; j++) { if (res[j+N][i+1]) { printf("%d %d ", P[j].first, P[j].second); break; } } } printf("%d %d\n", v[N-1].first, v[N-1].second); if (L) printf("\n"); } return 0; }
27.863158
199
0.365319
[ "vector" ]
8984d0a04a8e0e53945e01c8e1cbde1bbdb24910
3,291
cpp
C++
lib/commands/src/CommandAttack.cpp
maxim-puchkov/TheAdventure2019
049b0318b492f7a360817825f8772d7e28b5f75e
[ "MIT" ]
null
null
null
lib/commands/src/CommandAttack.cpp
maxim-puchkov/TheAdventure2019
049b0318b492f7a360817825f8772d7e28b5f75e
[ "MIT" ]
null
null
null
lib/commands/src/CommandAttack.cpp
maxim-puchkov/TheAdventure2019
049b0318b492f7a360817825f8772d7e28b5f75e
[ "MIT" ]
null
null
null
#include "CommandAttack.h" #include <boost/algorithm/string.hpp> #include <iostream> using internationalization::Internationalization; void CommandAttack::executeInHeartbeat(const std::string& username, const std::vector<std::string>& fullCommand) { auto& currentCombat = combatManager.getCombatWithPlayer(username); if(currentCombat.hasPlayer(username)){ currentCombat.queueCommand(username, fullCommand); //handle npc opponent. does nothing if character is user controlled auto opponentName = currentCombat.getOpponent(username); auto opponentResponse = characterManager.getAttackReply(opponentName); //if response is empty then non-ai opponent if(!opponentResponse.empty()) { onlineUserManager.addMessageToUser(username, opponentName + " prepares a(n) " + opponentResponse + "\n"); std::vector<std::string> opponentCommand; opponentCommand.push_back(opponentResponse); currentCombat.queueCommand(opponentName, opponentCommand); } } else { //player is not in a combat onlineUserManager.addMessageToUser(username, stringManager.getString(Internationalization::STRING_CODE::NOT_IN_COMBAT)); } } void CommandAttack::executeCombatRound(const std::string& username, const std::vector<std::string>& fullCommand) { auto& currentCombat = combatManager.getCombatWithPlayer(username); auto attackValue = characterManager.getCharacterAttack(username); auto opponentName = currentCombat.getOpponent(username); if(characterManager.isDecoy(opponentName)){ onlineUserManager.addMessageToUser(username, "You missed your opponent and hit their decoy.\n"); onlineUserManager.addMessageToUser(opponentName, "Your opponent hit your decoy\n"); } else { characterManager.damageCharacter(opponentName, attackValue); onlineUserManager.addMessageToUser( username, stringManager.getString(Internationalization::STRING_CODE::YOU_ATTACKED) + opponentName + stringManager.getString(Internationalization::STRING_CODE::FOR) + std::to_string(attackValue) + ".\n" ); onlineUserManager.addMessageToUser( opponentName, stringManager.getString(Internationalization::STRING_CODE::YOU_WERE_ATTACKED_FOR) + std::to_string(attackValue) + ".\n" + stringManager.getString(Internationalization::STRING_CODE::CURRENT_HP) + std::to_string(characterManager.getCharacterHealth(opponentName)) + "\n" ); } if(characterManager.getCharacterHealth(opponentName) <= 0){ //end combat & respawn opponent if user } } std::vector<std::string> CommandAttack::reassembleCommand(std::string& fullCommand, bool& commandIsValid) { std::vector<std::string> processedCommand; //Format: attack boost::trim_if(fullCommand, boost::is_any_of(" \t")); //split by " " and compress all long spaces boost::split(processedCommand, fullCommand, boost::is_any_of(" \t"), boost::token_compress_on); commandIsValid = (processedCommand.size() == 1 || processedCommand.size() == 2); return processedCommand; }
43.302632
128
0.694318
[ "vector" ]
898c632f58b7d41ba79c026856e31a5a4a663ba6
654
hpp
C++
helpers_extended/include/GarrysMod/Symbols.hpp
SupinePandora43/garrysmod_common
88dc3e4fc1983bd5ace1ff1ecfd2355347e453f6
[ "BSD-3-Clause" ]
null
null
null
helpers_extended/include/GarrysMod/Symbols.hpp
SupinePandora43/garrysmod_common
88dc3e4fc1983bd5ace1ff1ecfd2355347e453f6
[ "BSD-3-Clause" ]
null
null
null
helpers_extended/include/GarrysMod/Symbols.hpp
SupinePandora43/garrysmod_common
88dc3e4fc1983bd5ace1ff1ecfd2355347e453f6
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vector> #include "Symbol.hpp" namespace Symbols { extern const std::vector<Symbol> CBasePlayer_HandleClientLuaError; extern const std::vector<Symbol> FileSystemFactory; extern const Symbol g_pFullFileSystem; extern const std::vector<Symbol> IServer; extern const std::vector<Symbol> CNetChan_ProcessMessages; extern const std::vector<Symbol> CBaseClient_ConnectionStart; extern const std::vector<Symbol> CBaseClientState_ConnectionStart; extern const std::vector<Symbol> CBaseServer_RecalculateTags; extern const std::vector<Symbol> SteamGameServerAPIContext; extern const std::vector<Symbol> GModDataPack_SendFileToClient; }
29.727273
66
0.830275
[ "vector" ]
898cf77cb32dcd785dbb678b05a4bb0a863df934
47,308
cpp
C++
core/jni/android/graphics/Paint.cpp
Keneral/aframeworksbase
e1212ca12f63686efee5c32582b2878c9ae71ead
[ "Unlicense" ]
null
null
null
core/jni/android/graphics/Paint.cpp
Keneral/aframeworksbase
e1212ca12f63686efee5c32582b2878c9ae71ead
[ "Unlicense" ]
null
null
null
core/jni/android/graphics/Paint.cpp
Keneral/aframeworksbase
e1212ca12f63686efee5c32582b2878c9ae71ead
[ "Unlicense" ]
null
null
null
/* libs/android_runtime/android/graphics/Paint.cpp ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #define LOG_TAG "Paint" #include <utils/Log.h> #include "jni.h" #include "GraphicsJNI.h" #include "core_jni_helpers.h" #include <ScopedStringChars.h> #include <ScopedUtfChars.h> #include "SkBlurDrawLooper.h" #include "SkColorFilter.h" #include "SkMaskFilter.h" #include "SkPath.h" #include "SkRasterizer.h" #include "SkShader.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "unicode/uloc.h" #include "unicode/ushape.h" #include "utils/Blur.h" #include <hwui/MinikinSkia.h> #include <hwui/MinikinUtils.h> #include <hwui/Paint.h> #include <hwui/Typeface.h> #include <minikin/GraphemeBreak.h> #include <minikin/Measurement.h> #include <unicode/utf16.h> #include <cassert> #include <cstring> #include <memory> #include <vector> namespace android { struct JMetricsID { jfieldID top; jfieldID ascent; jfieldID descent; jfieldID bottom; jfieldID leading; }; static jclass gFontMetrics_class; static JMetricsID gFontMetrics_fieldID; static jclass gFontMetricsInt_class; static JMetricsID gFontMetricsInt_fieldID; static void defaultSettingsForAndroid(Paint* paint) { // GlyphID encoding is required because we are using Harfbuzz shaping paint->setTextEncoding(Paint::kGlyphID_TextEncoding); } namespace PaintGlue { enum MoveOpt { AFTER, AT_OR_AFTER, BEFORE, AT_OR_BEFORE, AT }; static void deletePaint(Paint* paint) { delete paint; } static jlong getNativeFinalizer(JNIEnv*, jobject) { return static_cast<jlong>(reinterpret_cast<uintptr_t>(&deletePaint)); } static jlong init(JNIEnv* env, jobject) { static_assert(1 << 0 == SkPaint::kAntiAlias_Flag, "paint_flags_mismatch"); static_assert(1 << 2 == SkPaint::kDither_Flag, "paint_flags_mismatch"); static_assert(1 << 3 == SkPaint::kUnderlineText_Flag, "paint_flags_mismatch"); static_assert(1 << 4 == SkPaint::kStrikeThruText_Flag, "paint_flags_mismatch"); static_assert(1 << 5 == SkPaint::kFakeBoldText_Flag, "paint_flags_mismatch"); static_assert(1 << 6 == SkPaint::kLinearText_Flag, "paint_flags_mismatch"); static_assert(1 << 7 == SkPaint::kSubpixelText_Flag, "paint_flags_mismatch"); static_assert(1 << 8 == SkPaint::kDevKernText_Flag, "paint_flags_mismatch"); static_assert(1 << 10 == SkPaint::kEmbeddedBitmapText_Flag, "paint_flags_mismatch"); Paint* obj = new Paint(); defaultSettingsForAndroid(obj); return reinterpret_cast<jlong>(obj); } static jlong initWithPaint(JNIEnv* env, jobject clazz, jlong paintHandle) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); Paint* obj = new Paint(*paint); return reinterpret_cast<jlong>(obj); } static void reset(JNIEnv* env, jobject clazz, jlong objHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); obj->reset(); defaultSettingsForAndroid(obj); } static void assign(JNIEnv* env, jobject clazz, jlong dstPaintHandle, jlong srcPaintHandle) { Paint* dst = reinterpret_cast<Paint*>(dstPaintHandle); const Paint* src = reinterpret_cast<Paint*>(srcPaintHandle); *dst = *src; } // Equivalent to the Java Paint's FILTER_BITMAP_FLAG. static const uint32_t sFilterBitmapFlag = 0x02; static jint getFlags(JNIEnv* env, jobject, jlong paintHandle) { Paint* nativePaint = reinterpret_cast<Paint*>(paintHandle); uint32_t result = nativePaint->getFlags(); result &= ~sFilterBitmapFlag; // Filtering no longer stored in this bit. Mask away. if (nativePaint->getFilterQuality() != kNone_SkFilterQuality) { result |= sFilterBitmapFlag; } return static_cast<jint>(result); } static void setFlags(JNIEnv* env, jobject, jlong paintHandle, jint flags) { Paint* nativePaint = reinterpret_cast<Paint*>(paintHandle); // Instead of modifying 0x02, change the filter level. nativePaint->setFilterQuality(flags & sFilterBitmapFlag ? kLow_SkFilterQuality : kNone_SkFilterQuality); // Don't pass through filter flag, which is no longer stored in paint's flags. flags &= ~sFilterBitmapFlag; // Use the existing value for 0x02. const uint32_t existing0x02Flag = nativePaint->getFlags() & sFilterBitmapFlag; flags |= existing0x02Flag; nativePaint->setFlags(flags); } static jint getHinting(JNIEnv* env, jobject, jlong paintHandle) { return reinterpret_cast<Paint*>(paintHandle)->getHinting() == Paint::kNo_Hinting ? 0 : 1; } static void setHinting(JNIEnv* env, jobject, jlong paintHandle, jint mode) { reinterpret_cast<Paint*>(paintHandle)->setHinting( mode == 0 ? Paint::kNo_Hinting : Paint::kNormal_Hinting); } static void setAntiAlias(JNIEnv* env, jobject, jlong paintHandle, jboolean aa) { reinterpret_cast<Paint*>(paintHandle)->setAntiAlias(aa); } static void setLinearText(JNIEnv* env, jobject, jlong paintHandle, jboolean linearText) { reinterpret_cast<Paint*>(paintHandle)->setLinearText(linearText); } static void setSubpixelText(JNIEnv* env, jobject, jlong paintHandle, jboolean subpixelText) { reinterpret_cast<Paint*>(paintHandle)->setSubpixelText(subpixelText); } static void setUnderlineText(JNIEnv* env, jobject, jlong paintHandle, jboolean underlineText) { reinterpret_cast<Paint*>(paintHandle)->setUnderlineText(underlineText); } static void setStrikeThruText(JNIEnv* env, jobject, jlong paintHandle, jboolean strikeThruText) { reinterpret_cast<Paint*>(paintHandle)->setStrikeThruText(strikeThruText); } static void setFakeBoldText(JNIEnv* env, jobject, jlong paintHandle, jboolean fakeBoldText) { reinterpret_cast<Paint*>(paintHandle)->setFakeBoldText(fakeBoldText); } static void setFilterBitmap(JNIEnv* env, jobject, jlong paintHandle, jboolean filterBitmap) { reinterpret_cast<Paint*>(paintHandle)->setFilterQuality( filterBitmap ? kLow_SkFilterQuality : kNone_SkFilterQuality); } static void setDither(JNIEnv* env, jobject, jlong paintHandle, jboolean dither) { reinterpret_cast<Paint*>(paintHandle)->setDither(dither); } static jint getStyle(JNIEnv* env, jobject clazz,jlong objHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); return static_cast<jint>(obj->getStyle()); } static void setStyle(JNIEnv* env, jobject clazz, jlong objHandle, jint styleHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); Paint::Style style = static_cast<Paint::Style>(styleHandle); obj->setStyle(style); } static jint getColor(JNIEnv* env, jobject, jlong paintHandle) { int color; color = reinterpret_cast<Paint*>(paintHandle)->getColor(); return static_cast<jint>(color); } static jint getAlpha(JNIEnv* env, jobject, jlong paintHandle) { int alpha; alpha = reinterpret_cast<Paint*>(paintHandle)->getAlpha(); return static_cast<jint>(alpha); } static void setColor(JNIEnv* env, jobject, jlong paintHandle, jint color) { reinterpret_cast<Paint*>(paintHandle)->setColor(color); } static void setAlpha(JNIEnv* env, jobject, jlong paintHandle, jint a) { reinterpret_cast<Paint*>(paintHandle)->setAlpha(a); } static jfloat getStrokeWidth(JNIEnv* env, jobject, jlong paintHandle) { return SkScalarToFloat(reinterpret_cast<Paint*>(paintHandle)->getStrokeWidth()); } static void setStrokeWidth(JNIEnv* env, jobject, jlong paintHandle, jfloat width) { reinterpret_cast<Paint*>(paintHandle)->setStrokeWidth(width); } static jfloat getStrokeMiter(JNIEnv* env, jobject, jlong paintHandle) { return SkScalarToFloat(reinterpret_cast<Paint*>(paintHandle)->getStrokeMiter()); } static void setStrokeMiter(JNIEnv* env, jobject, jlong paintHandle, jfloat miter) { reinterpret_cast<Paint*>(paintHandle)->setStrokeMiter(miter); } static jint getStrokeCap(JNIEnv* env, jobject clazz, jlong objHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); return static_cast<jint>(obj->getStrokeCap()); } static void setStrokeCap(JNIEnv* env, jobject clazz, jlong objHandle, jint capHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); Paint::Cap cap = static_cast<Paint::Cap>(capHandle); obj->setStrokeCap(cap); } static jint getStrokeJoin(JNIEnv* env, jobject clazz, jlong objHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); return static_cast<jint>(obj->getStrokeJoin()); } static void setStrokeJoin(JNIEnv* env, jobject clazz, jlong objHandle, jint joinHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); Paint::Join join = (Paint::Join) joinHandle; obj->setStrokeJoin(join); } static jboolean getFillPath(JNIEnv* env, jobject clazz, jlong objHandle, jlong srcHandle, jlong dstHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkPath* src = reinterpret_cast<SkPath*>(srcHandle); SkPath* dst = reinterpret_cast<SkPath*>(dstHandle); return obj->getFillPath(*src, dst) ? JNI_TRUE : JNI_FALSE; } static jlong setShader(JNIEnv* env, jobject clazz, jlong objHandle, jlong shaderHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkShader* shader = reinterpret_cast<SkShader*>(shaderHandle); return reinterpret_cast<jlong>(obj->setShader(shader)); } static jlong setColorFilter(JNIEnv* env, jobject clazz, jlong objHandle, jlong filterHandle) { Paint* obj = reinterpret_cast<Paint *>(objHandle); SkColorFilter* filter = reinterpret_cast<SkColorFilter *>(filterHandle); return reinterpret_cast<jlong>(obj->setColorFilter(filter)); } static jlong setXfermode(JNIEnv* env, jobject clazz, jlong objHandle, jlong xfermodeHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkXfermode* xfermode = reinterpret_cast<SkXfermode*>(xfermodeHandle); return reinterpret_cast<jlong>(obj->setXfermode(xfermode)); } static jlong setPathEffect(JNIEnv* env, jobject clazz, jlong objHandle, jlong effectHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkPathEffect* effect = reinterpret_cast<SkPathEffect*>(effectHandle); return reinterpret_cast<jlong>(obj->setPathEffect(effect)); } static jlong setMaskFilter(JNIEnv* env, jobject clazz, jlong objHandle, jlong maskfilterHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkMaskFilter* maskfilter = reinterpret_cast<SkMaskFilter*>(maskfilterHandle); return reinterpret_cast<jlong>(obj->setMaskFilter(maskfilter)); } static jlong setTypeface(JNIEnv* env, jobject clazz, jlong objHandle, jlong typefaceHandle) { // TODO: in Paint refactoring, set typeface on android Paint, not Paint return NULL; } static jlong setRasterizer(JNIEnv* env, jobject clazz, jlong objHandle, jlong rasterizerHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); SkAutoTUnref<SkRasterizer> rasterizer(GraphicsJNI::refNativeRasterizer(rasterizerHandle)); return reinterpret_cast<jlong>(obj->setRasterizer(rasterizer)); } static jint getTextAlign(JNIEnv* env, jobject clazz, jlong objHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); return static_cast<jint>(obj->getTextAlign()); } static void setTextAlign(JNIEnv* env, jobject clazz, jlong objHandle, jint alignHandle) { Paint* obj = reinterpret_cast<Paint*>(objHandle); Paint::Align align = static_cast<Paint::Align>(alignHandle); obj->setTextAlign(align); } static jint setTextLocales(JNIEnv* env, jobject clazz, jlong objHandle, jstring locales) { Paint* obj = reinterpret_cast<Paint*>(objHandle); ScopedUtfChars localesChars(env, locales); jint minikinLangListId = FontStyle::registerLanguageList(localesChars.c_str()); obj->setMinikinLangListId(minikinLangListId); return minikinLangListId; } static void setTextLocalesByMinikinLangListId(JNIEnv* env, jobject clazz, jlong objHandle, jint minikinLangListId) { Paint* obj = reinterpret_cast<Paint*>(objHandle); obj->setMinikinLangListId(minikinLangListId); } static jboolean isElegantTextHeight(JNIEnv* env, jobject, jlong paintHandle) { Paint* obj = reinterpret_cast<Paint*>(paintHandle); return obj->getFontVariant() == VARIANT_ELEGANT; } static void setElegantTextHeight(JNIEnv* env, jobject, jlong paintHandle, jboolean aa) { Paint* obj = reinterpret_cast<Paint*>(paintHandle); obj->setFontVariant(aa ? VARIANT_ELEGANT : VARIANT_DEFAULT); } static jfloat getTextSize(JNIEnv* env, jobject, jlong paintHandle) { return SkScalarToFloat(reinterpret_cast<Paint*>(paintHandle)->getTextSize()); } static void setTextSize(JNIEnv* env, jobject, jlong paintHandle, jfloat textSize) { reinterpret_cast<Paint*>(paintHandle)->setTextSize(textSize); } static jfloat getTextScaleX(JNIEnv* env, jobject, jlong paintHandle) { return SkScalarToFloat(reinterpret_cast<Paint*>(paintHandle)->getTextScaleX()); } static void setTextScaleX(JNIEnv* env, jobject, jlong paintHandle, jfloat scaleX) { reinterpret_cast<Paint*>(paintHandle)->setTextScaleX(scaleX); } static jfloat getTextSkewX(JNIEnv* env, jobject, jlong paintHandle) { return SkScalarToFloat(reinterpret_cast<Paint*>(paintHandle)->getTextSkewX()); } static void setTextSkewX(JNIEnv* env, jobject, jlong paintHandle, jfloat skewX) { reinterpret_cast<Paint*>(paintHandle)->setTextSkewX(skewX); } static jfloat getLetterSpacing(JNIEnv* env, jobject clazz, jlong paintHandle) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); return paint->getLetterSpacing(); } static void setLetterSpacing(JNIEnv* env, jobject clazz, jlong paintHandle, jfloat letterSpacing) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); paint->setLetterSpacing(letterSpacing); } static void setFontFeatureSettings(JNIEnv* env, jobject clazz, jlong paintHandle, jstring settings) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); if (!settings) { paint->setFontFeatureSettings(std::string()); } else { ScopedUtfChars settingsChars(env, settings); paint->setFontFeatureSettings(std::string(settingsChars.c_str(), settingsChars.size())); } } static jint getHyphenEdit(JNIEnv* env, jobject clazz, jlong paintHandle, jint hyphen) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); return paint->getHyphenEdit(); } static void setHyphenEdit(JNIEnv* env, jobject clazz, jlong paintHandle, jint hyphen) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); paint->setHyphenEdit((uint32_t)hyphen); } static SkScalar getMetricsInternal(jlong paintHandle, jlong typefaceHandle, Paint::FontMetrics *metrics) { const int kElegantTop = 2500; const int kElegantBottom = -1000; const int kElegantAscent = 1900; const int kElegantDescent = -500; const int kElegantLeading = 0; Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); typeface = Typeface::resolveDefault(typeface); FakedFont baseFont = typeface->fFontCollection->baseFontFaked(typeface->fStyle); float saveSkewX = paint->getTextSkewX(); bool savefakeBold = paint->isFakeBoldText(); MinikinFontSkia::populateSkPaint(paint, baseFont.font, baseFont.fakery); SkScalar spacing = paint->getFontMetrics(metrics); // The populateSkPaint call may have changed fake bold / text skew // because we want to measure with those effects applied, so now // restore the original settings. paint->setTextSkewX(saveSkewX); paint->setFakeBoldText(savefakeBold); if (paint->getFontVariant() == VARIANT_ELEGANT) { SkScalar size = paint->getTextSize(); metrics->fTop = -size * kElegantTop / 2048; metrics->fBottom = -size * kElegantBottom / 2048; metrics->fAscent = -size * kElegantAscent / 2048; metrics->fDescent = -size * kElegantDescent / 2048; metrics->fLeading = size * kElegantLeading / 2048; spacing = metrics->fDescent - metrics->fAscent + metrics->fLeading; } return spacing; } static jfloat ascent(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle) { Paint::FontMetrics metrics; getMetricsInternal(paintHandle, typefaceHandle, &metrics); return SkScalarToFloat(metrics.fAscent); } static jfloat descent(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle) { Paint::FontMetrics metrics; getMetricsInternal(paintHandle, typefaceHandle, &metrics); return SkScalarToFloat(metrics.fDescent); } static jfloat getFontMetrics(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle, jobject metricsObj) { Paint::FontMetrics metrics; SkScalar spacing = getMetricsInternal(paintHandle, typefaceHandle, &metrics); if (metricsObj) { SkASSERT(env->IsInstanceOf(metricsObj, gFontMetrics_class)); env->SetFloatField(metricsObj, gFontMetrics_fieldID.top, SkScalarToFloat(metrics.fTop)); env->SetFloatField(metricsObj, gFontMetrics_fieldID.ascent, SkScalarToFloat(metrics.fAscent)); env->SetFloatField(metricsObj, gFontMetrics_fieldID.descent, SkScalarToFloat(metrics.fDescent)); env->SetFloatField(metricsObj, gFontMetrics_fieldID.bottom, SkScalarToFloat(metrics.fBottom)); env->SetFloatField(metricsObj, gFontMetrics_fieldID.leading, SkScalarToFloat(metrics.fLeading)); } return SkScalarToFloat(spacing); } static jint getFontMetricsInt(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle, jobject metricsObj) { Paint::FontMetrics metrics; getMetricsInternal(paintHandle, typefaceHandle, &metrics); int ascent = SkScalarRoundToInt(metrics.fAscent); int descent = SkScalarRoundToInt(metrics.fDescent); int leading = SkScalarRoundToInt(metrics.fLeading); if (metricsObj) { SkASSERT(env->IsInstanceOf(metricsObj, gFontMetricsInt_class)); env->SetIntField(metricsObj, gFontMetricsInt_fieldID.top, SkScalarFloorToInt(metrics.fTop)); env->SetIntField(metricsObj, gFontMetricsInt_fieldID.ascent, ascent); env->SetIntField(metricsObj, gFontMetricsInt_fieldID.descent, descent); env->SetIntField(metricsObj, gFontMetricsInt_fieldID.bottom, SkScalarCeilToInt(metrics.fBottom)); env->SetIntField(metricsObj, gFontMetricsInt_fieldID.leading, leading); } return descent - ascent + leading; } static jfloat doTextAdvances(JNIEnv *env, Paint *paint, Typeface* typeface, const jchar *text, jint start, jint count, jint contextCount, jint bidiFlags, jfloatArray advances, jint advancesIndex) { NPE_CHECK_RETURN_ZERO(env, text); if ((start | count | contextCount | advancesIndex) < 0 || contextCount < count) { doThrowAIOOBE(env); return 0; } if (count == 0) { return 0; } if (advances) { size_t advancesLength = env->GetArrayLength(advances); if ((size_t)(count + advancesIndex) > advancesLength) { doThrowAIOOBE(env); return 0; } } std::unique_ptr<jfloat[]> advancesArray; if (advances) { advancesArray.reset(new jfloat[count]); } const float advance = MinikinUtils::measureText(paint, bidiFlags, typeface, text, start, count, contextCount, advancesArray.get()); if (advances) { env->SetFloatArrayRegion(advances, advancesIndex, count, advancesArray.get()); } return advance; } static jfloat getTextAdvances___CIIIII_FI(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jcharArray text, jint index, jint count, jint contextIndex, jint contextCount, jint bidiFlags, jfloatArray advances, jint advancesIndex) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); jchar* textArray = env->GetCharArrayElements(text, NULL); jfloat result = doTextAdvances(env, paint, typeface, textArray + contextIndex, index - contextIndex, count, contextCount, bidiFlags, advances, advancesIndex); env->ReleaseCharArrayElements(text, textArray, JNI_ABORT); return result; } static jfloat getTextAdvances__StringIIIII_FI(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jstring text, jint start, jint end, jint contextStart, jint contextEnd, jint bidiFlags, jfloatArray advances, jint advancesIndex) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); const jchar* textArray = env->GetStringChars(text, NULL); jfloat result = doTextAdvances(env, paint, typeface, textArray + contextStart, start - contextStart, end - start, contextEnd - contextStart, bidiFlags, advances, advancesIndex); env->ReleaseStringChars(text, textArray); return result; } static jint doTextRunCursor(JNIEnv *env, Paint* paint, const jchar *text, jint start, jint count, jint flags, jint offset, jint opt) { GraphemeBreak::MoveOpt moveOpt = GraphemeBreak::MoveOpt(opt); size_t result = GraphemeBreak::getTextRunCursor(text, start, count, offset, moveOpt); return static_cast<jint>(result); } static jint getTextRunCursor___C(JNIEnv* env, jobject clazz, jlong paintHandle, jcharArray text, jint contextStart, jint contextCount, jint dir, jint offset, jint cursorOpt) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); jchar* textArray = env->GetCharArrayElements(text, NULL); jint result = doTextRunCursor(env, paint, textArray, contextStart, contextCount, dir, offset, cursorOpt); env->ReleaseCharArrayElements(text, textArray, JNI_ABORT); return result; } static jint getTextRunCursor__String(JNIEnv* env, jobject clazz, jlong paintHandle, jstring text, jint contextStart, jint contextEnd, jint dir, jint offset, jint cursorOpt) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); const jchar* textArray = env->GetStringChars(text, NULL); jint result = doTextRunCursor(env, paint, textArray, contextStart, contextEnd - contextStart, dir, offset, cursorOpt); env->ReleaseStringChars(text, textArray); return result; } class GetTextFunctor { public: GetTextFunctor(const Layout& layout, SkPath* path, jfloat x, jfloat y, Paint* paint, uint16_t* glyphs, SkPoint* pos) : layout(layout), path(path), x(x), y(y), paint(paint), glyphs(glyphs), pos(pos) { } void operator()(size_t start, size_t end) { for (size_t i = start; i < end; i++) { glyphs[i] = layout.getGlyphId(i); pos[i].fX = x + layout.getX(i); pos[i].fY = y + layout.getY(i); } if (start == 0) { paint->getPosTextPath(glyphs + start, (end - start) << 1, pos + start, path); } else { paint->getPosTextPath(glyphs + start, (end - start) << 1, pos + start, &tmpPath); path->addPath(tmpPath); } } private: const Layout& layout; SkPath* path; jfloat x; jfloat y; Paint* paint; uint16_t* glyphs; SkPoint* pos; SkPath tmpPath; }; static void getTextPath(JNIEnv* env, Paint* paint, Typeface* typeface, const jchar* text, jint count, jint bidiFlags, jfloat x, jfloat y, SkPath* path) { Layout layout; MinikinUtils::doLayout(&layout, paint, bidiFlags, typeface, text, 0, count, count); size_t nGlyphs = layout.nGlyphs(); uint16_t* glyphs = new uint16_t[nGlyphs]; SkPoint* pos = new SkPoint[nGlyphs]; x += MinikinUtils::xOffsetForTextAlign(paint, layout); Paint::Align align = paint->getTextAlign(); paint->setTextAlign(Paint::kLeft_Align); paint->setTextEncoding(Paint::kGlyphID_TextEncoding); GetTextFunctor f(layout, path, x, y, paint, glyphs, pos); MinikinUtils::forFontRun(layout, paint, f); paint->setTextAlign(align); delete[] glyphs; delete[] pos; } static void getTextPath___C(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jint bidiFlags, jcharArray text, jint index, jint count, jfloat x, jfloat y, jlong pathHandle) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); SkPath* path = reinterpret_cast<SkPath*>(pathHandle); const jchar* textArray = env->GetCharArrayElements(text, NULL); getTextPath(env, paint, typeface, textArray + index, count, bidiFlags, x, y, path); env->ReleaseCharArrayElements(text, const_cast<jchar*>(textArray), JNI_ABORT); } static void getTextPath__String(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jint bidiFlags, jstring text, jint start, jint end, jfloat x, jfloat y, jlong pathHandle) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); SkPath* path = reinterpret_cast<SkPath*>(pathHandle); const jchar* textArray = env->GetStringChars(text, NULL); getTextPath(env, paint, typeface, textArray + start, end - start, bidiFlags, x, y, path); env->ReleaseStringChars(text, textArray); } static void setShadowLayer(JNIEnv* env, jobject clazz, jlong paintHandle, jfloat radius, jfloat dx, jfloat dy, jint color) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); if (radius <= 0) { paint->setLooper(NULL); } else { SkScalar sigma = android::uirenderer::Blur::convertRadiusToSigma(radius); paint->setLooper(SkBlurDrawLooper::Create((SkColor)color, sigma, dx, dy))->unref(); } } static jboolean hasShadowLayer(JNIEnv* env, jobject clazz, jlong paintHandle) { Paint* paint = reinterpret_cast<Paint*>(paintHandle); return paint->getLooper() && paint->getLooper()->asABlurShadow(NULL); } static int breakText(JNIEnv* env, const Paint& paint, Typeface* typeface, const jchar text[], int count, float maxWidth, jint bidiFlags, jfloatArray jmeasured, const bool forwardScan) { size_t measuredCount = 0; float measured = 0; std::unique_ptr<float[]> advancesArray(new float[count]); MinikinUtils::measureText(&paint, bidiFlags, typeface, text, 0, count, count, advancesArray.get()); for (int i = 0; i < count; i++) { // traverse in the given direction int index = forwardScan ? i : (count - i - 1); float width = advancesArray[index]; if (measured + width > maxWidth) { break; } // properly handle clusters when scanning backwards if (forwardScan || width != 0.0f) { measuredCount = i + 1; } measured += width; } if (jmeasured && env->GetArrayLength(jmeasured) > 0) { AutoJavaFloatArray autoMeasured(env, jmeasured, 1); jfloat* array = autoMeasured.ptr(); array[0] = measured; } return measuredCount; } static jint breakTextC(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jcharArray jtext, jint index, jint count, jfloat maxWidth, jint bidiFlags, jfloatArray jmeasuredWidth) { NPE_CHECK_RETURN_ZERO(env, jtext); Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); bool forwardTextDirection; if (count < 0) { forwardTextDirection = false; count = -count; } else { forwardTextDirection = true; } if ((index < 0) || (index + count > env->GetArrayLength(jtext))) { doThrowAIOOBE(env); return 0; } const jchar* text = env->GetCharArrayElements(jtext, NULL); count = breakText(env, *paint, typeface, text + index, count, maxWidth, bidiFlags, jmeasuredWidth, forwardTextDirection); env->ReleaseCharArrayElements(jtext, const_cast<jchar*>(text), JNI_ABORT); return count; } static jint breakTextS(JNIEnv* env, jobject clazz, jlong paintHandle, jlong typefaceHandle, jstring jtext, jboolean forwards, jfloat maxWidth, jint bidiFlags, jfloatArray jmeasuredWidth) { NPE_CHECK_RETURN_ZERO(env, jtext); Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); int count = env->GetStringLength(jtext); const jchar* text = env->GetStringChars(jtext, NULL); count = breakText(env, *paint, typeface, text, count, maxWidth, bidiFlags, jmeasuredWidth, forwards); env->ReleaseStringChars(jtext, text); return count; } static void doTextBounds(JNIEnv* env, const jchar* text, int count, jobject bounds, const Paint& paint, Typeface* typeface, jint bidiFlags) { SkRect r; SkIRect ir; Layout layout; MinikinUtils::doLayout(&layout, &paint, bidiFlags, typeface, text, 0, count, count); MinikinRect rect; layout.getBounds(&rect); r.fLeft = rect.mLeft; r.fTop = rect.mTop; r.fRight = rect.mRight; r.fBottom = rect.mBottom; r.roundOut(&ir); GraphicsJNI::irect_to_jrect(ir, env, bounds); } static void getStringBounds(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle, jstring text, jint start, jint end, jint bidiFlags, jobject bounds) { const Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); const jchar* textArray = env->GetStringChars(text, NULL); doTextBounds(env, textArray + start, end - start, bounds, *paint, typeface, bidiFlags); env->ReleaseStringChars(text, textArray); } static void getCharArrayBounds(JNIEnv* env, jobject, jlong paintHandle, jlong typefaceHandle, jcharArray text, jint index, jint count, jint bidiFlags, jobject bounds) { const Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); const jchar* textArray = env->GetCharArrayElements(text, NULL); doTextBounds(env, textArray + index, count, bounds, *paint, typeface, bidiFlags); env->ReleaseCharArrayElements(text, const_cast<jchar*>(textArray), JNI_ABORT); } static jboolean layoutContainsNotdef(const Layout& layout) { for (size_t i = 0; i < layout.nGlyphs(); i++) { if (layout.getGlyphId(i) == 0) { return true; } } return false; } // Returns true if the given string is exact one pair of regional indicators. static bool isFlag(const jchar* str, size_t length) { const jchar RI_LEAD_SURROGATE = 0xD83C; const jchar RI_TRAIL_SURROGATE_MIN = 0xDDE6; const jchar RI_TRAIL_SURROGATE_MAX = 0xDDFF; if (length != 4) { return false; } if (str[0] != RI_LEAD_SURROGATE || str[2] != RI_LEAD_SURROGATE) { return false; } return RI_TRAIL_SURROGATE_MIN <= str[1] && str[1] <= RI_TRAIL_SURROGATE_MAX && RI_TRAIL_SURROGATE_MIN <= str[3] && str[3] <= RI_TRAIL_SURROGATE_MAX; } static jboolean hasGlyph(JNIEnv *env, jclass, jlong paintHandle, jlong typefaceHandle, jint bidiFlags, jstring string) { const Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); ScopedStringChars str(env, string); /* Start by rejecting unsupported base code point and variation selector pairs. */ size_t nChars = 0; const uint32_t kStartOfString = 0xFFFFFFFF; uint32_t prevCp = kStartOfString; for (size_t i = 0; i < str.size(); i++) { jchar cu = str[i]; uint32_t cp = cu; if (U16_IS_TRAIL(cu)) { // invalid UTF-16, unpaired trailing surrogate return false; } else if (U16_IS_LEAD(cu)) { if (i + 1 == str.size()) { // invalid UTF-16, unpaired leading surrogate at end of string return false; } i++; jchar cu2 = str[i]; if (!U16_IS_TRAIL(cu2)) { // invalid UTF-16, unpaired leading surrogate return false; } cp = U16_GET_SUPPLEMENTARY(cu, cu2); } if (prevCp != kStartOfString && ((0xFE00 <= cp && cp <= 0xFE0F) || (0xE0100 <= cp && cp <= 0xE01EF))) { bool hasVS = MinikinUtils::hasVariationSelector(typeface, prevCp, cp); if (!hasVS) { // No font has a glyph for the code point and variation selector pair. return false; } else if (nChars == 1 && i + 1 == str.size()) { // The string is just a codepoint and a VS, we have an authoritative answer return true; } } nChars++; prevCp = cp; } Layout layout; MinikinUtils::doLayout(&layout, paint, bidiFlags, typeface, str.get(), 0, str.size(), str.size()); size_t nGlyphs = layout.nGlyphs(); if (nGlyphs != 1 && nChars > 1) { // multiple-character input, and was not a ligature // TODO: handle ZWJ/ZWNJ characters specially so we can detect certain ligatures // in joining scripts, such as Arabic and Mongolian. return false; } if (nGlyphs == 0 || layoutContainsNotdef(layout)) { return false; // The collection doesn't have a glyph. } if (nChars == 2 && isFlag(str.get(), str.size())) { // Some font may have a special glyph for unsupported regional indicator pairs. // To return false for this case, need to compare the glyph id with the one of ZZ // since ZZ is reserved for unknown or invalid territory. // U+1F1FF (REGIONAL INDICATOR SYMBOL LETTER Z) is \uD83C\uDDFF in UTF16. static const jchar ZZ_FLAG_STR[] = { 0xD83C, 0xDDFF, 0xD83C, 0xDDFF }; Layout zzLayout; MinikinUtils::doLayout(&zzLayout, paint, bidiFlags, typeface, ZZ_FLAG_STR, 0, 4, 4); if (zzLayout.nGlyphs() != 1 || layoutContainsNotdef(zzLayout)) { // The font collection doesn't have a glyph for unknown flag. Just return true. return true; } return zzLayout.getGlyphId(0) != layout.getGlyphId(0); } return true; } static jfloat doRunAdvance(const Paint* paint, Typeface* typeface, const jchar buf[], jint start, jint count, jint bufSize, jboolean isRtl, jint offset) { int bidiFlags = isRtl ? kBidi_Force_RTL : kBidi_Force_LTR; if (offset == start + count) { return MinikinUtils::measureText(paint, bidiFlags, typeface, buf, start, count, bufSize, nullptr); } std::unique_ptr<float[]> advancesArray(new float[count]); MinikinUtils::measureText(paint, bidiFlags, typeface, buf, start, count, bufSize, advancesArray.get()); return getRunAdvance(advancesArray.get(), buf, start, count, offset); } static jfloat getRunAdvance___CIIIIZI_F(JNIEnv *env, jclass, jlong paintHandle, jlong typefaceHandle, jcharArray text, jint start, jint end, jint contextStart, jint contextEnd, jboolean isRtl, jint offset) { const Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); jchar* textArray = (jchar*) env->GetPrimitiveArrayCritical(text, NULL); jfloat result = doRunAdvance(paint, typeface, textArray + contextStart, start - contextStart, end - start, contextEnd - contextStart, isRtl, offset - contextStart); env->ReleasePrimitiveArrayCritical(text, textArray, JNI_ABORT); return result; } static jint doOffsetForAdvance(const Paint* paint, Typeface* typeface, const jchar buf[], jint start, jint count, jint bufSize, jboolean isRtl, jfloat advance) { int bidiFlags = isRtl ? kBidi_Force_RTL : kBidi_Force_LTR; std::unique_ptr<float[]> advancesArray(new float[count]); MinikinUtils::measureText(paint, bidiFlags, typeface, buf, start, count, bufSize, advancesArray.get()); return getOffsetForAdvance(advancesArray.get(), buf, start, count, advance); } static jint getOffsetForAdvance___CIIIIZF_I(JNIEnv *env, jclass, jlong paintHandle, jlong typefaceHandle, jcharArray text, jint start, jint end, jint contextStart, jint contextEnd, jboolean isRtl, jfloat advance) { const Paint* paint = reinterpret_cast<Paint*>(paintHandle); Typeface* typeface = reinterpret_cast<Typeface*>(typefaceHandle); jchar* textArray = (jchar*) env->GetPrimitiveArrayCritical(text, NULL); jint result = doOffsetForAdvance(paint, typeface, textArray + contextStart, start - contextStart, end - start, contextEnd - contextStart, isRtl, advance); result += contextStart; env->ReleasePrimitiveArrayCritical(text, textArray, JNI_ABORT); return result; } }; // namespace PaintGlue static const JNINativeMethod methods[] = { {"nGetNativeFinalizer", "()J", (void*) PaintGlue::getNativeFinalizer}, {"nInit","()J", (void*) PaintGlue::init}, {"nInitWithPaint","(J)J", (void*) PaintGlue::initWithPaint}, {"nReset","!(J)V", (void*) PaintGlue::reset}, {"nSet","!(JJ)V", (void*) PaintGlue::assign}, {"nGetFlags","!(J)I", (void*) PaintGlue::getFlags}, {"nSetFlags","!(JI)V", (void*) PaintGlue::setFlags}, {"nGetHinting","!(J)I", (void*) PaintGlue::getHinting}, {"nSetHinting","!(JI)V", (void*) PaintGlue::setHinting}, {"nSetAntiAlias","!(JZ)V", (void*) PaintGlue::setAntiAlias}, {"nSetSubpixelText","!(JZ)V", (void*) PaintGlue::setSubpixelText}, {"nSetLinearText","!(JZ)V", (void*) PaintGlue::setLinearText}, {"nSetUnderlineText","!(JZ)V", (void*) PaintGlue::setUnderlineText}, {"nSetStrikeThruText","!(JZ)V", (void*) PaintGlue::setStrikeThruText}, {"nSetFakeBoldText","!(JZ)V", (void*) PaintGlue::setFakeBoldText}, {"nSetFilterBitmap","!(JZ)V", (void*) PaintGlue::setFilterBitmap}, {"nSetDither","!(JZ)V", (void*) PaintGlue::setDither}, {"nGetStyle","!(J)I", (void*) PaintGlue::getStyle}, {"nSetStyle","!(JI)V", (void*) PaintGlue::setStyle}, {"nGetColor","!(J)I", (void*) PaintGlue::getColor}, {"nSetColor","!(JI)V", (void*) PaintGlue::setColor}, {"nGetAlpha","!(J)I", (void*) PaintGlue::getAlpha}, {"nSetAlpha","!(JI)V", (void*) PaintGlue::setAlpha}, {"nGetStrokeWidth","!(J)F", (void*) PaintGlue::getStrokeWidth}, {"nSetStrokeWidth","!(JF)V", (void*) PaintGlue::setStrokeWidth}, {"nGetStrokeMiter","!(J)F", (void*) PaintGlue::getStrokeMiter}, {"nSetStrokeMiter","!(JF)V", (void*) PaintGlue::setStrokeMiter}, {"nGetStrokeCap","!(J)I", (void*) PaintGlue::getStrokeCap}, {"nSetStrokeCap","!(JI)V", (void*) PaintGlue::setStrokeCap}, {"nGetStrokeJoin","!(J)I", (void*) PaintGlue::getStrokeJoin}, {"nSetStrokeJoin","!(JI)V", (void*) PaintGlue::setStrokeJoin}, {"nGetFillPath","!(JJJ)Z", (void*) PaintGlue::getFillPath}, {"nSetShader","!(JJ)J", (void*) PaintGlue::setShader}, {"nSetColorFilter","!(JJ)J", (void*) PaintGlue::setColorFilter}, {"nSetXfermode","!(JJ)J", (void*) PaintGlue::setXfermode}, {"nSetPathEffect","!(JJ)J", (void*) PaintGlue::setPathEffect}, {"nSetMaskFilter","!(JJ)J", (void*) PaintGlue::setMaskFilter}, {"nSetTypeface","!(JJ)J", (void*) PaintGlue::setTypeface}, {"nSetRasterizer","!(JJ)J", (void*) PaintGlue::setRasterizer}, {"nGetTextAlign","!(J)I", (void*) PaintGlue::getTextAlign}, {"nSetTextAlign","!(JI)V", (void*) PaintGlue::setTextAlign}, {"nSetTextLocales","!(JLjava/lang/String;)I", (void*) PaintGlue::setTextLocales}, {"nSetTextLocalesByMinikinLangListId","!(JI)V", (void*) PaintGlue::setTextLocalesByMinikinLangListId}, {"nIsElegantTextHeight","!(J)Z", (void*) PaintGlue::isElegantTextHeight}, {"nSetElegantTextHeight","!(JZ)V", (void*) PaintGlue::setElegantTextHeight}, {"nGetTextSize","!(J)F", (void*) PaintGlue::getTextSize}, {"nSetTextSize","!(JF)V", (void*) PaintGlue::setTextSize}, {"nGetTextScaleX","!(J)F", (void*) PaintGlue::getTextScaleX}, {"nSetTextScaleX","!(JF)V", (void*) PaintGlue::setTextScaleX}, {"nGetTextSkewX","!(J)F", (void*) PaintGlue::getTextSkewX}, {"nSetTextSkewX","!(JF)V", (void*) PaintGlue::setTextSkewX}, {"nGetLetterSpacing","!(J)F", (void*) PaintGlue::getLetterSpacing}, {"nSetLetterSpacing","!(JF)V", (void*) PaintGlue::setLetterSpacing}, {"nSetFontFeatureSettings","(JLjava/lang/String;)V", (void*) PaintGlue::setFontFeatureSettings}, {"nGetHyphenEdit", "!(J)I", (void*) PaintGlue::getHyphenEdit}, {"nSetHyphenEdit", "!(JI)V", (void*) PaintGlue::setHyphenEdit}, {"nAscent","!(JJ)F", (void*) PaintGlue::ascent}, {"nDescent","!(JJ)F", (void*) PaintGlue::descent}, {"nGetFontMetrics", "!(JJLandroid/graphics/Paint$FontMetrics;)F", (void*)PaintGlue::getFontMetrics}, {"nGetFontMetricsInt", "!(JJLandroid/graphics/Paint$FontMetricsInt;)I", (void*)PaintGlue::getFontMetricsInt}, {"nBreakText","(JJ[CIIFI[F)I", (void*) PaintGlue::breakTextC}, {"nBreakText","(JJLjava/lang/String;ZFI[F)I", (void*) PaintGlue::breakTextS}, {"nGetTextAdvances","(JJ[CIIIII[FI)F", (void*) PaintGlue::getTextAdvances___CIIIII_FI}, {"nGetTextAdvances","(JJLjava/lang/String;IIIII[FI)F", (void*) PaintGlue::getTextAdvances__StringIIIII_FI}, {"nGetTextRunCursor", "(J[CIIIII)I", (void*) PaintGlue::getTextRunCursor___C}, {"nGetTextRunCursor", "(JLjava/lang/String;IIIII)I", (void*) PaintGlue::getTextRunCursor__String}, {"nGetTextPath", "(JJI[CIIFFJ)V", (void*) PaintGlue::getTextPath___C}, {"nGetTextPath", "(JJILjava/lang/String;IIFFJ)V", (void*) PaintGlue::getTextPath__String}, {"nGetStringBounds", "(JJLjava/lang/String;IIILandroid/graphics/Rect;)V", (void*) PaintGlue::getStringBounds }, {"nGetCharArrayBounds", "(JJ[CIIILandroid/graphics/Rect;)V", (void*) PaintGlue::getCharArrayBounds }, {"nHasGlyph", "(JJILjava/lang/String;)Z", (void*) PaintGlue::hasGlyph }, {"nGetRunAdvance", "(JJ[CIIIIZI)F", (void*) PaintGlue::getRunAdvance___CIIIIZI_F}, {"nGetOffsetForAdvance", "(JJ[CIIIIZF)I", (void*) PaintGlue::getOffsetForAdvance___CIIIIZF_I}, {"nSetShadowLayer", "!(JFFFI)V", (void*)PaintGlue::setShadowLayer}, {"nHasShadowLayer", "!(J)Z", (void*)PaintGlue::hasShadowLayer} }; int register_android_graphics_Paint(JNIEnv* env) { gFontMetrics_class = FindClassOrDie(env, "android/graphics/Paint$FontMetrics"); gFontMetrics_class = MakeGlobalRefOrDie(env, gFontMetrics_class); gFontMetrics_fieldID.top = GetFieldIDOrDie(env, gFontMetrics_class, "top", "F"); gFontMetrics_fieldID.ascent = GetFieldIDOrDie(env, gFontMetrics_class, "ascent", "F"); gFontMetrics_fieldID.descent = GetFieldIDOrDie(env, gFontMetrics_class, "descent", "F"); gFontMetrics_fieldID.bottom = GetFieldIDOrDie(env, gFontMetrics_class, "bottom", "F"); gFontMetrics_fieldID.leading = GetFieldIDOrDie(env, gFontMetrics_class, "leading", "F"); gFontMetricsInt_class = FindClassOrDie(env, "android/graphics/Paint$FontMetricsInt"); gFontMetricsInt_class = MakeGlobalRefOrDie(env, gFontMetricsInt_class); gFontMetricsInt_fieldID.top = GetFieldIDOrDie(env, gFontMetricsInt_class, "top", "I"); gFontMetricsInt_fieldID.ascent = GetFieldIDOrDie(env, gFontMetricsInt_class, "ascent", "I"); gFontMetricsInt_fieldID.descent = GetFieldIDOrDie(env, gFontMetricsInt_class, "descent", "I"); gFontMetricsInt_fieldID.bottom = GetFieldIDOrDie(env, gFontMetricsInt_class, "bottom", "I"); gFontMetricsInt_fieldID.leading = GetFieldIDOrDie(env, gFontMetricsInt_class, "leading", "I"); return RegisterMethodsOrDie(env, "android/graphics/Paint", methods, NELEM(methods)); } }
45.974733
113
0.653674
[ "vector" ]
898d58fd3e74c87ef6bdcb0303dc38a43265bbef
272
cpp
C++
AtCoder/abc085/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc085/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc085/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <set> #include <vector> using namespace std; int main() { int N; cin >> N; set<int> S; for (int i = 0; i < N; ++i) { int a; cin >> a; S.insert(a); } printf("%d\n", S.size()); }
18.133333
37
0.533088
[ "vector" ]
898e62599d882725236a92aa9272ad3a7f668c6f
654
cpp
C++
294/B/main.cpp
tamimcsedu19/codeforces
8e61025b99bc0a5b32cb03f736123b39dcc23f61
[ "Apache-2.0" ]
null
null
null
294/B/main.cpp
tamimcsedu19/codeforces
8e61025b99bc0a5b32cb03f736123b39dcc23f61
[ "Apache-2.0" ]
null
null
null
294/B/main.cpp
tamimcsedu19/codeforces
8e61025b99bc0a5b32cb03f736123b39dcc23f61
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; vector<int> A,B,C; int main() { int n; cin>>n; for(int i=0;i<n;++i) { int x; cin>>x; A.push_back(x); } for(int i=0;i<n-1;++i) { int x; cin>>x; B.push_back(x); } for(int i=0;i<n-2;++i) { int x; cin>>x; C.push_back(x); } sort(A.begin(),A.end()); sort(B.begin(),B.end()); sort(C.begin(),C.end()); vector<int> v(1); std::set_difference (A.begin(), A.end(), B.begin(), B.end(), v.begin()); cout<<v[0]<<"\n"; std::set_difference (B.begin(), B.end(), C.begin(), C.end(), v.begin()); cout<<v[0]; }
21.096774
76
0.487768
[ "vector" ]