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
5c5e66d4dcac37988a372b928a7f1dc37642223e
5,838
cpp
C++
ITKLiver/fastmarching.cpp
jon-young/medicalimage
ef8dd3b7c65ab501d1d44ba9ee8f2ad442d42820
[ "MIT" ]
6
2017-04-05T13:39:55.000Z
2021-12-27T21:47:14.000Z
ITKLiver/fastmarching.cpp
jon-young/medicalimage
ef8dd3b7c65ab501d1d44ba9ee8f2ad442d42820
[ "MIT" ]
1
2017-04-06T06:06:05.000Z
2017-04-06T06:06:05.000Z
ITKLiver/fastmarching.cpp
jon-young/medicalimage
ef8dd3b7c65ab501d1d44ba9ee8f2ad442d42820
[ "MIT" ]
6
2016-03-17T03:04:28.000Z
2019-10-21T08:28:43.000Z
// // Execute fast marching method on 3D image // // INPUT: // - read/write directory with trailing slash // - region-of-interest as single image file // - output file name // - (x,y,z) seed coordinates // - sigma, sigmoid K1, K2 for gradient and sigmoid mapping // - stopping time, binary threshold for fast marching // // Code copied from ITK examples // Created on 3 February 2016 // #include <iostream> #include <string> #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.h" #include "itkSigmoidImageFilter.h" #include "itkFastMarchingImageFilter.h" #include "itkBinaryThresholdImageFilter.h" int main(int argc, const char *argv[]) { // Validate input parameters if (argc < 12) { std::cerr << "Usage:" << std::endl; std::cerr << argv[0]; std::cerr << " <Read/WriteDir> <InputImg> <OutputImg> "; std::cerr << "[seedX] [seedY] [seedZ] "; std::cerr << "[sigma] [sigmoid K1] [sigmoid K2] "; std::cerr << "[stopping time] [binary threshold]" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef unsigned short InputPixelType; typedef float InternalPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; //////////////////////////////////////////////// // 1) Read the input image typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); std::string readpath(argv[1]); readpath.append(argv[2]); reader->SetFileName( readpath ); //////////////////////////////////////////////// // 2) Curvature anisotropic diffusion typedef itk::CurvatureAnisotropicDiffusionImageFilter< InputImageType, InternalImageType > SmoothingFilterType; SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New(); smoothing->SetInput( reader->GetOutput() ); smoothing->SetTimeStep(0.04); smoothing->SetNumberOfIterations(5); smoothing->SetConductanceParameter(9.0); //////////////////////////////////////////////// // 3) Gradient magnitude recursive Gaussian const double sigma = atof(argv[7]); typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< InternalImageType, InternalImageType > GradientFilterType; GradientFilterType::Pointer gradMagnitude = GradientFilterType::New(); gradMagnitude->SetInput( smoothing->GetOutput() ); gradMagnitude->SetSigma( sigma ); //////////////////////////////////////////////// // 4) Sigmoid mapping const double K1 = atof(argv[8]); const double K2 = atof(argv[9]); typedef itk::SigmoidImageFilter< InternalImageType, InternalImageType > SigmoidFilterType; SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New(); sigmoid->SetInput( gradMagnitude->GetOutput() ); sigmoid->SetOutputMinimum(0.0); sigmoid->SetOutputMaximum(1.0); sigmoid->SetAlpha( (K2 - K1)/6 ); sigmoid->SetBeta( (K1 + K2)/2 ); //////////////////////////////////////////////// // 5) Fast Marching typedef itk::FastMarchingImageFilter< InternalImageType, InternalImageType > FastMarchingFilterType; typedef FastMarchingFilterType::NodeContainer NodeContainer; typedef FastMarchingFilterType::NodeType NodeType; InternalImageType::IndexType seedPosition; seedPosition[0] = atoi( argv[4] ); seedPosition[1] = atoi( argv[5] ); seedPosition[2] = atoi( argv[6] ); NodeType node; const double seedVal = 0.0; node.SetValue( seedVal ); node.SetIndex( seedPosition ); NodeContainer::Pointer seeds = NodeContainer::New(); seeds->Initialize(); seeds->InsertElement(0, node); const double stoppingTime = atof( argv[10] ); FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New(); fastMarching->SetInput( sigmoid->GetOutput() ); fastMarching->SetTrialPoints( seeds ); fastMarching->SetOutputSize( reader->GetOutput()->GetBufferedRegion().GetSize() ); fastMarching->SetStoppingValue( stoppingTime ); //////////////////////////////////////////////// // 6) Binary Thresholding const InternalPixelType timeThreshold = atof( argv[11] ); typedef itk::BinaryThresholdImageFilter< InternalImageType, OutputImageType > ThresholdingFilterType; ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New(); thresholder->SetInput( fastMarching->GetOutput() ); thresholder->SetLowerThreshold( 0.0 ); thresholder->SetUpperThreshold( timeThreshold ); thresholder->SetOutsideValue( 0 ); thresholder->SetInsideValue( 255 ); //////////////////////////////////////////////// // 7) Write output image typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); std::string writepath(argv[1]); writepath.append(argv[3]); writer->SetFileName( writepath ); writer->SetInput( thresholder->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } // The following writer type is used to save the output of the sigmoid // mapping so that it can be used with a viewer to help determine an // appropriate threshold to be used on the output of the fast marching filter // /* typedef itk::ImageFileWriter< InternalImageType > InternalWriterType; InternalWriterType::Pointer speedWriter = InternalWriterType::New(); speedWriter->SetInput( sigmoid->GetOutput() ); std::string sigmoidpath(argv[1]); speedWriter->SetFileName( sigmoidpath.append("SigmoidOutput.mha") ); speedWriter->Update(); */ return 0; }
35.168675
79
0.691161
[ "3d" ]
5c5f089e10f245461d66ff6c52bbb5bca108d5b5
5,477
cpp
C++
src/suConnectedEntity.cpp
ALIGN-analoglayout/AnalogDetailedRouter
16cf4b4ec6c6b3d5a87277607064a15d7fb4ad3d
[ "BSD-3-Clause" ]
19
2019-07-17T15:41:35.000Z
2021-12-01T23:57:57.000Z
src/suConnectedEntity.cpp
ALIGN-analoglayout/AnalogDetailedRouter
16cf4b4ec6c6b3d5a87277607064a15d7fb4ad3d
[ "BSD-3-Clause" ]
null
null
null
src/suConnectedEntity.cpp
ALIGN-analoglayout/AnalogDetailedRouter
16cf4b4ec6c6b3d5a87277607064a15d7fb4ad3d
[ "BSD-3-Clause" ]
2
2020-07-28T18:50:39.000Z
2022-01-24T03:13:39.000Z
// see LICENSE //! \author Ryzhenko Nikolai, 10984646, nikolai.v.ryzhenko@intel.com //! \date Mon Oct 16 11:20:03 2017 //! \file suConnectedEntity.cpp //! \brief A collection of methods of the class suConnectedEntity. // std includes #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> // application includes #include <suAssert.h> #include <suDefine.h> #include <suJournal.h> #include <suTypedefs.h> // other application includes #include <suGlobalRoute.h> #include <suLayer.h> #include <suLayoutFunc.h> #include <suLayoutLeaf.h> #include <suLayoutNode.h> #include <suNet.h> #include <suSatSolverWrapper.h> #include <suStatic.h> #include <suWire.h> // module include #include <suConnectedEntity.h> namespace amsr { // ------------------------------------------------------------ // - // --- Static variables // - // ------------------------------------------------------------ sutype::id_t suConnectedEntity::_uniqueId = 0; // ------------------------------------------------------------ // - // --- Special methods // - // ------------------------------------------------------------ suConnectedEntity::~suConnectedEntity () { // _openSatindex can be either suSatSolverWrapper::instance()->get_constant(0) or suSatSolverWrapper::instance()->get_next_sat_index() // anyway, I don't create too much connected entities to worry about available satindices // moreover, I don't want to check here what kind of _openSatindex I used here //if (_openSatindex != sutype::UNDEFINED_SAT_INDEX) { // suSatSolverWrapper::instance()->return_sat_index (_openSatindex); //} } // end of suConnectedEntity::~suConnectedEntity // ------------------------------------------------------------ // - // --- Public static methods // - // ------------------------------------------------------------ // ------------------------------------------------------------ // - // --- Public methods // - // ------------------------------------------------------------ // std::string suConnectedEntity::to_str () const { std::ostringstream oss; oss << "{" << "net=" << _net->name() << "; ceid=" << _id; if (_type != sutype::wt_undefined) { oss << "; type=" << suStatic::wire_type_2_str (_type); } if (get_interface_layer()) { oss << "; interface=" << get_interface_layer()->name(); } else { oss << "; interface=<null>"; } if (_trunkGlobalRoute) { oss << "; trunk=" << _trunkGlobalRoute->to_str(); } oss << "; iwires=" << _interfaceWires.size(); oss << "}"; return oss.str(); } // end of suConnectedEntity::to_str // bool suConnectedEntity::layout_function_is_legal () const { suLayoutFunc * layoutfuncCE = layoutFunc(); if (layoutfuncCE == 0) return false; if (layoutfuncCE->func() != sutype::logic_func_or) return false; if (layoutfuncCE->sign() != sutype::unary_sign_just) return false; if (layoutfuncCE->nodes().size() != 2) return false; // expected to be 2-node function to support opens suLayoutNode * node0 = layoutfuncCE->nodes().front(); suLayoutNode * node1 = layoutfuncCE->nodes().back(); if (!((node0->is_leaf() && node1->is_func()) || (node0->is_func() && node1->is_leaf()))) return false; suLayoutLeaf * leaf = node0->is_leaf() ? node0->to_leaf() : node1->to_leaf(); suLayoutFunc * layoutfunc0 = node0->is_func() ? node0->to_func() : node1->to_func(); if (leaf->satindex() != openSatindex()) return false; if (layoutfunc0->func() != sutype::logic_func_and) return false; if (layoutfunc0->sign() != sutype::unary_sign_just) return false; return true; } // end of suConnectedEntity::layout_function_is_legal // suLayoutFunc * suConnectedEntity::get_main_layout_function () const { suLayoutFunc * layoutfuncCE = layoutFunc(); SUASSERT (layoutfuncCE, ""); SUASSERT (layoutfuncCE->func() == sutype::logic_func_or, ""); SUASSERT (layoutfuncCE->sign() == sutype::unary_sign_just, ""); SUASSERT (layoutfuncCE->nodes().size() == 2, ""); suLayoutNode * node0 = layoutfuncCE->nodes().front(); suLayoutNode * node1 = layoutfuncCE->nodes().back(); SUASSERT ((node0->is_leaf() && node1->is_func()) || (node0->is_func() && node1->is_leaf()), ""); suLayoutLeaf * leaf = node0->is_leaf() ? node0->to_leaf() : node1->to_leaf(); suLayoutFunc * layoutfunc0 = node0->is_func() ? node0->to_func() : node1->to_func(); SUASSERT (leaf->satindex() == openSatindex(), ""); SUASSERT (layoutfunc0->func() == sutype::logic_func_and, "Can be only AND to support incrementally added constraints"); SUASSERT (layoutfunc0->sign() == sutype::unary_sign_just, "Can be only AND to support incrementally added constraints"); return layoutfunc0; } // end of suConnectedEntity::get_main_layout_function // ------------------------------------------------------------ // - // --- Private static methods // - // ------------------------------------------------------------ // ------------------------------------------------------------ // - // --- Private methods // - // ------------------------------------------------------------ } // end of namespace amsr // end of suConnectedEntity.cpp
29.28877
138
0.541172
[ "vector" ]
5c7003464898e6a6c0cfbb279f4b81d1b5a7f74b
6,578
cpp
C++
src/db/db_management.cpp
koralkashri/cpp-bank-management
62def8a3295e812f6d5c23b04b4fee2b379a62b0
[ "MIT" ]
null
null
null
src/db/db_management.cpp
koralkashri/cpp-bank-management
62def8a3295e812f6d5c23b04b4fee2b379a62b0
[ "MIT" ]
null
null
null
src/db/db_management.cpp
koralkashri/cpp-bank-management
62def8a3295e812f6d5c23b04b4fee2b379a62b0
[ "MIT" ]
null
null
null
#include "db_management.h" #include <bsoncxx/json.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/uri.hpp> #include <mongocxx/instance.hpp> #include <bsoncxx/builder/stream/helpers.hpp> #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/builder/stream/array.hpp> #include "../extensions/custom_exceptions.h" #include "../extensions/boost_gregorian_extensions.h" #include "../program_flow/structures/transactions.h" using bsoncxx::builder::stream::close_array; using bsoncxx::builder::stream::close_document; using bsoncxx::builder::stream::document; using bsoncxx::builder::stream::finalize; using bsoncxx::builder::stream::open_array; using bsoncxx::builder::stream::open_document; db_management::db_management() : client(mongocxx::uri{}), db(client["bank_management_db"]), plans_management(&db), accounts_management(&db) { } // Accounts Management void db_management::create_account(const std::string &account_name) { accounts_management.create_account(account_name); } void db_management::delete_account(const std::string &account_name) { plans_management.delete_all_account_plans(account_name); accounts_management.delete_account(account_name); } void db_management::modify_account_free_cash(const std::string &account_name, double cash) { accounts_management.modify_free_cash(account_name, cash); } double db_management::get_account_free_cash(const std::string &account_name) const { return accounts_management.get_account_free_cash(account_name); } // Account Transactions Management void db_management::update_account_monthly_income(const std::string &account_name, const std::string &source_name, double income) { accounts_management.get_transactions_management().update_account_monthly_income(account_name, source_name, income); } void db_management::set_account_single_time_income(const std::string &account_name, const std::string &source_name, double income) { double previous_income = 0; try { auto current_t = transactions(get_account_income_details(account_name, boost::gregorian::current_local_date())) .at({ .transaction_name = source_name, .is_income = true }); previous_income = current_t.cash; } catch (...) {} accounts_management.get_transactions_management().set_account_single_time_income(account_name, source_name, income); modify_account_free_cash(account_name, income - previous_income); } void db_management::pause_account_monthly_income(const std::string &account_name, const std::string &source_name) { accounts_management.get_transactions_management().pause_account_monthly_income(account_name, source_name); } void db_management::restart_account_monthly_income(const std::string &account_name, const std::string &source_name) { accounts_management.get_transactions_management().restart_account_monthly_income(account_name, source_name); } void db_management::update_account_monthly_outcome(const std::string &account_name, const std::string &target_name, double outcome) { accounts_management.get_transactions_management().update_account_monthly_outcome(account_name, target_name, outcome); } void db_management::set_account_single_time_outcome(const std::string &account_name, const std::string &target_name, double outcome) { double previous_outcome = 0; try { auto current_t = transactions(get_account_outcome_details(account_name, boost::gregorian::current_local_date())) .at({ .transaction_name = target_name, .is_income = false }); previous_outcome = current_t.cash; } catch (...) {} accounts_management.get_transactions_management().set_account_single_time_outcome(account_name, target_name, outcome); modify_account_free_cash(account_name, previous_outcome - outcome); } void db_management::pause_account_monthly_outcome(const std::string &account_name, const std::string &target_name) { accounts_management.get_transactions_management().pause_account_monthly_outcome(account_name, target_name); } void db_management::restart_account_monthly_outcome(const std::string &account_name, const std::string &target_name) { accounts_management.get_transactions_management().restart_account_monthly_outcome(account_name, target_name); } // Plans Management void db_management::create_plan(const std::string &account_name, const std::string &plan_name) { if (!is_account_exists(account_name)) throw account_not_found_exception(); plans_management.create_plan(account_name, plan_name); } double db_management::delete_plan(const std::string &account_name, const std::string &plan_name) { if (!is_account_exists(account_name)) throw account_not_found_exception(); return plans_management.delete_plan(account_name, plan_name); } void db_management::modify_plan_balance(const std::string &account_name, const std::string &plan_name, double cash) { if (!is_account_exists(account_name)) throw account_not_found_exception(); plans_management.modify_plan_balance(account_name, plan_name, cash); } double db_management::get_plan_balance(const std::string &account_name, const std::string &plan_name) const { if (!is_account_exists(account_name)) throw account_not_found_exception(); return plans_management.get_plan_balance(account_name, plan_name); } std::vector<std::string> db_management::get_all_accounts() const { return accounts_management.get_all_accounts(); } std::vector<std::string> db_management::get_all_account_plans(const std::string &account_name) const { if (!is_account_exists(account_name)) throw account_not_found_exception(); return plans_management.get_all_account_plans(account_name); } bool db_management::is_account_exists(const std::string &account_name) const { return accounts_management.is_account_exists(account_name); } std::vector<transaction> db_management::get_account_outcome_details(const std::string &account_name, const boost::gregorian::date &month) const { return accounts_management.get_transactions_management().get_account_outcome_details(account_name, month); } std::vector<transaction> db_management::get_account_income_details(const std::string &account_name, const boost::gregorian::date &month) const { return accounts_management.get_transactions_management().get_account_income_details(account_name, month); }
45.365517
134
0.767863
[ "vector" ]
5c704edd0633e0b6e73751bbb66ceeceec9045aa
4,504
cpp
C++
src/main/cpp/mtl.cpp
brkyvz/linalg-benchmarks
64b2414bf8cf75089853021ca02ccd2078e938ca
[ "Apache-2.0" ]
null
null
null
src/main/cpp/mtl.cpp
brkyvz/linalg-benchmarks
64b2414bf8cf75089853021ca02ccd2078e938ca
[ "Apache-2.0" ]
null
null
null
src/main/cpp/mtl.cpp
brkyvz/linalg-benchmarks
64b2414bf8cf75089853021ca02ccd2078e938ca
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <ctime> #include <boost/numeric/mtl/mtl.hpp> #include "boost/program_options.hpp" using namespace std; using namespace mtl; using namespace mtl::mat; namespace po = boost::program_options; // m: numRows, n: numCols inline double simpleDenseTest_MTL(int m, int n, int num_trials) { dense2D<double, parameters<tag::col_major> > A(m, n); random(A); dense2D<double, parameters<tag::col_major> > B(m, n); random(B); dense2D<double, parameters<tag::col_major> > C(m, n); random(C); dense2D<double, parameters<tag::col_major> > D(m, n); random(D); dense2D<double, parameters<tag::col_major> > E(m, n); random(E); clock_t start; double duration = 0.0; for (unsigned i = 0; i < num_trials; i++) { start = clock(); (ele_div((A + B), C) - D) * E; duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } return duration / num_trials; } // m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B inline double gemmDenseTest_MTL(int m, int n, int k, int num_trials) { dense2D<double, parameters<tag::col_major> > A(m, n); random(A); dense2D<double, parameters<tag::col_major> > B(m, n); random(B); dense2D<double, parameters<tag::col_major> > C(n, k); random(C); dense2D<double, parameters<tag::col_major> > D(n, k); random(D); dense2D<double, parameters<tag::col_major> > E(m, k); random(E); clock_t start; double duration = 0.0; for (unsigned i = 0; i < num_trials; i++) { start = clock(); E += (A + B) * (C - D); duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } return duration / num_trials; } inline double mulDenseTest_MTL(int a, int b, int c, int d, int num_trials) { dense2D<double, parameters<tag::col_major> > A(a, a); random(A); dense2D<double, parameters<tag::col_major> > B(a, b); random(B); dense2D<double, parameters<tag::col_major> > C(b, c); random(C); dense2D<double, parameters<tag::col_major> > D(c, d); random(D); clock_t start; double duration = 0.0; for (unsigned i = 0; i < num_trials; i++) { start = clock(); A * B * C * D; duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } return duration / num_trials; } void runMTLTests(int num_trials, int m, int n, int k, int a, int b, int c, int d, bool skip_vec, bool skip_simple, bool skip_gemm, bool skip_mult) { cout << "MTL Simple Test:\t" << simpleDenseTest_MTL(m, n, num_trials) << endl; cout << "MTL gemm Test:\t" << gemmDenseTest_MTL(m, n, k, num_trials) << endl; cout << "MTL mulDense Test:\t" << mulDenseTest_MTL(a, b, c, d, num_trials) << endl; } int main(int argc, char *argv[]) { int l, m, n, k, a, b, c, d, trials; bool skip_vec, skip_simple, skip_gemm, skip_mult; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("l", po::value<int>(&l)->default_value(1048576), "length of vectors in vector addition test") ("m", po::value<int>(&m)->default_value(1024), "numRows of matrices in Simple Test, and gemm Test") ("n", po::value<int>(&n)->default_value(1024), "numCols of matrices in Simple Test, and gemm Test") ("k", po::value<int>(&k)->default_value(1024), "numCols of B in gemm Test") ("trials", po::value<int>(&trials)->default_value(10), "number of trials") ("a", po::value<int>(&a)->default_value(1024), "size matrix A in mulDense Test") ("b", po::value<int>(&b)->default_value(512), "size matrix B in mulDense Test") ("c", po::value<int>(&c)->default_value(256), "size matrix C in mulDense Test") ("d", po::value<int>(&d)->default_value(128), "size matrix D in mulDense Test") ("skip-vec", po::value<bool>(&skip_vec)->default_value(false), "skip vectors Test") ("skip-simple", po::value<bool>(&skip_simple)->default_value(false), "skip simple Test") ("skip-gemm", po::value<bool>(&skip_gemm)->default_value(false), "skip gemm Tests") ("skip-mult", po::value<bool>(&skip_mult)->default_value(false), "skip mulDense Test") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); runMTLTests(trials, l, m, n, k, a, b, c, d, skip_vec, skip_simple, skip_gemm, skip_mult); return 0; }
33.864662
93
0.613677
[ "vector" ]
f07a025dcead43700dbaec461aadbbad96efd5de
528
cpp
C++
functional_programming2/main/main.cpp
franz-ms-muc/cxx_Samples
6713198913e3487ec566edf3b31cc5a38e0fb122
[ "Apache-2.0" ]
null
null
null
functional_programming2/main/main.cpp
franz-ms-muc/cxx_Samples
6713198913e3487ec566edf3b31cc5a38e0fb122
[ "Apache-2.0" ]
null
null
null
functional_programming2/main/main.cpp
franz-ms-muc/cxx_Samples
6713198913e3487ec566edf3b31cc5a38e0fb122
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <algorithm> #include <iostream> using namespace std; class MyLess { public: bool operator()(int a, int b) { return a < b; } }; /* Inside .cpp file, app_main function must be declared with C linkage */ extern "C" void app_main(void) { cout << "app_main starting" << endl; vector<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; sort(begin(v), end(v), MyLess()); cout << " Hi "; for (auto a : v) { cout << a << ' '; } cout << "app_main done" << endl; }
12
73
0.545455
[ "vector" ]
f07fda9112a813957abe91efb2fd970f322f2a21
1,060
cpp
C++
langs/c++/sort_bind/sort_bind.cpp
danielgrigg/sandbox
95128ef44ddc2df2a819b14b9930f95d9c9fd423
[ "WTFPL" ]
1
2017-02-23T03:57:39.000Z
2017-02-23T03:57:39.000Z
langs/c++/sort_bind/sort_bind.cpp
danielgrigg/sandbox
95128ef44ddc2df2a819b14b9930f95d9c9fd423
[ "WTFPL" ]
null
null
null
langs/c++/sort_bind/sort_bind.cpp
danielgrigg/sandbox
95128ef44ddc2df2a819b14b9930f95d9c9fd423
[ "WTFPL" ]
null
null
null
#include <iostream> #include <boost/algorithm/string/predicate.hpp> #include <boost/bind.hpp> #include <vector> #include <string> using namespace std; typedef pair<string,string> file_info; bool nocase_compare(const file_info &lhs, const file_info &rhs) { return boost::algorithm::ilexicographical_compare(lhs.second,rhs.second); } int main() { vector<file_info> file_infos; file_infos.push_back(file_info("a1", "c")); file_infos.push_back(file_info("b2", "b")); file_infos.push_back(file_info("c3", "a")); sort(file_infos.begin(), file_infos.end(), boost::bind( boost::algorithm::ilexicographical_compare<string, string>, boost::bind(&file_info::second, _1), boost::bind(&file_info::second, _2))); / sort(file_infos.begin(), file_infos.end(),nocase_compare); for (vector<file_info>::const_iterator i = file_infos.begin(); i != file_infos.end(); i++) { cout << i->first << ", " << i->second << " "; } cout << endl; return 0; }
25.238095
89
0.633019
[ "vector" ]
f081e2e4071c0f9cc0dd9b4a301e34b6ce3024f0
5,718
hpp
C++
stapl_release/stapl/views/metadata/projection/segmented.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/metadata/projection/segmented.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/metadata/projection/segmented.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_VIEWS_METADATA_PROJECTION_SEGMENTED_HPP #define STAPL_VIEWS_METADATA_PROJECTION_SEGMENTED_HPP #include <stapl/runtime.hpp> #include <stapl/views/metadata/metadata_entry.hpp> #include <stapl/domains/partitioned_domain.hpp> #include <stapl/domains/intersect.hpp> #include <stapl/views/metadata/locality_dist_metadata.hpp> #include <stapl/views/metadata/container_fwd.hpp> #include <stapl/containers/type_traits/dimension_traits.hpp> #include <stapl/views/type_traits/is_native_partition.hpp> namespace stapl { namespace metadata { ////////////////////////////////////////////////////////////////////// /// @brief Helper functor used to project the domains in the given /// locality metadata (@c P) to the domain of the given @c /// View. The result is projected metadata locality /// information. /// /// This helper functor is invoked when the given @c View is a /// partitioned view. /// /// @todo operator should return a shared_ptr. ////////////////////////////////////////////////////////////////////// template <typename View, typename P> struct segmented_metadata_projection { typedef typename std::remove_pointer<typename P::second_type>::type lower_md_cont_t; // Adjust 1D domains template <typename V,typename MD,typename Dim> struct adjust_metadata_domains_helper { typedef typename V::domain_type domain_type; typedef typename V::map_func_type map_func_type; typedef typename MD::value_type value_type; typedef typename value_type::component_type component_type; typedef metadata_entry<domain_type,component_type, typename MD::value_type::cid_type > dom_info_type; typedef metadata::growable_container<dom_info_type> return_type; return_type* operator()(View* view, lower_md_cont_t* cpart) const { typedef typename View::view_container_type container_type; typedef std::vector<std::pair<domain_type,bool> > vec_doms_t; // check if the projected metadata is known to have the same number of // elements as the underlying container metadata constexpr bool static_metadata = is_native_partition<typename V::partition_type>::value; // get the partitioner from the partitioner_container auto par = view->container().partition(); auto mfg = view->container().mapfunc_generator(); return_type* res = static_metadata ? new return_type(cpart->size()) : new return_type(); using domain_t = typename lower_md_cont_t::domain_type; domain_t local_domain(cpart->local_dimensions()); const bool has_skipped_seg = !view->domain().is_same_container_domain(); // iterate over the local part of the metadata container domain_map(local_domain, [&](typename domain_t::index_type const& i) { value_type const& entry = (*cpart)[cpart->get_local_vid(i)]; component_type sc = entry.component(); if (!static_metadata) { vec_doms_t doms = par.contained_in(entry.domain(), mfg); for (auto& dj : doms) { if (has_skipped_seg) dj.first = intersect(dj.first, view->domain()); if (dj.second) { res->push_back_here(dom_info_type( typename dom_info_type::cid_type(), dj.first, sc, entry.location_qualifier(), entry.affinity(), entry.handle(), entry.location() )); } else { res->push_back_here(dom_info_type( typename dom_info_type::cid_type(), dj.first, NULL, entry.location_qualifier(), entry.affinity(), entry.handle(), entry.location() )); } } } else { vec_doms_t doms = par.contained_in(entry.domain(), mfg); stapl_assert(doms.size() == 1, "static metadata not balanced"); (*res)[view->get_location_id()] = dom_info_type( typename dom_info_type::cid_type(), doms[0].first, sc, entry.location_qualifier(), entry.affinity(), entry.handle(), entry.location() ); } }); res->update(); delete cpart; return res; } }; typedef typename View::domain_type domain_type; typedef typename dimension_traits< typename lower_md_cont_t::value_type::domain_type::gid_type >::type dimension_t; typedef typename adjust_metadata_domains_helper< View, lower_md_cont_t, dimension_t >::return_type md_cont_type; typedef std::pair<bool, md_cont_type*> return_type; return_type operator()(View* view, lower_md_cont_t* part, bool part_is_fixed = true) const { constexpr bool static_metadata = is_native_partition<typename View::partition_type>::value; return std::make_pair(part_is_fixed && static_metadata, adjust_metadata_domains_helper<View,lower_md_cont_t,dimension_t>()( view, part)); } }; } // namespace metadata } // namespace stapl #endif // STAPL_VIEWS_METADATA_PROJECTION_SEGMENTED_HPP
35.079755
78
0.631165
[ "vector" ]
f0855e83cdecea40fa3f827166f3138dfc2d022c
20,688
cc
C++
bindings/python/py_api.cc
Tparuchuri/reinforcement_learning
a09db076667bbfd9581cac265a0874840881241b
[ "MIT" ]
null
null
null
bindings/python/py_api.cc
Tparuchuri/reinforcement_learning
a09db076667bbfd9581cac265a0874840881241b
[ "MIT" ]
1
2022-02-08T21:18:37.000Z
2022-02-08T21:18:37.000Z
bindings/python/py_api.cc
Tparuchuri/reinforcement_learning
a09db076667bbfd9581cac265a0874840881241b
[ "MIT" ]
null
null
null
#include <pybind11/functional.h> #include <pybind11/pybind11.h> #include "config_utility.h" #include "constants.h" #include "live_model.h" #include "multistep.h" #include <exception> #include <memory> #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) namespace py = pybind11; namespace rl = reinforcement_learning; class rl_exception : public std::exception { public: rl_exception(const char *what_arg, int error_code) : _message(what_arg), _error_code{error_code} {} const char *what() const noexcept override { return _message.c_str(); } int error_code() const { return _error_code; } private: int _error_code; std::string _message; }; // Excellent blog post about how to get custom exception types working with // PyBind11 // https://www.pierov.org/2020/03/01/python-custom-exceptions-c-extensions/ static PyObject *RLException_tp_str(PyObject *self_ptr) { py::str ret; try { py::handle self(self_ptr); py::tuple args = self.attr("args"); ret = py::str(args[0]); } catch (py::error_already_set &e) { ret = ""; } /* ret will go out of scope when returning, therefore increase its reference count, and transfer it to the caller (like PyObject_Str). */ ret.inc_ref(); return ret.ptr(); } static PyObject *RLException_getcode(PyObject *self_ptr, void *closure) { try { py::handle self(self_ptr); py::tuple args = self.attr("args"); py::object code = args[1]; code.inc_ref(); return code.ptr(); } catch (py::error_already_set &e) { /* We could simply backpropagate the exception with e.restore, but exceptions like OSError return None when an attribute is not set. */ py::none ret; ret.inc_ref(); return ret.ptr(); } } static PyGetSetDef RLException_getsetters[] = { {"code", RLException_getcode, NULL, "Get the error code for this exception.", NULL}, {NULL}}; static PyObject *PyRLException; #define THROW_IF_FAIL(x) \ do { \ int retval__LINE__ = (x); \ if (retval__LINE__ != rl::error_code::success) { \ throw rl_exception(status.get_error_msg(), status.get_error_code()); \ } \ } while (0) struct error_callback_context { std::function<void(int, const std::string &)> _callback; }; void dispatch_error_internal(const rl::api_status &status, error_callback_context *context) { py::gil_scoped_acquire acquire; context->_callback(status.get_error_code(), status.get_error_msg()); } class live_model_with_callback : public rl::live_model { private: error_callback_context _context; public: live_model_with_callback( const rl::utility::configuration &config, std::function<void(int, const std::string &)> callback) : rl::live_model(config, &dispatch_error_internal, &_context) { _context._callback = callback; } }; struct constants { constants() = delete; }; PYBIND11_MODULE(rl_client, m) { PyRLException = PyErr_NewException("rl_client.RLException", NULL, NULL); if (PyRLException) { PyTypeObject *as_type = reinterpret_cast<PyTypeObject *>(PyRLException); as_type->tp_str = RLException_tp_str; PyObject *descr = PyDescr_NewGetSet(as_type, RLException_getsetters); auto dict = py::reinterpret_borrow<py::dict>(as_type->tp_dict); dict[py::handle(PyDescr_NAME(descr))] = py::handle(descr); Py_XINCREF(PyRLException); m.add_object("RLException", py::handle(PyRLException)); } py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (rl_exception &e) { py::tuple args(2); args[0] = e.what(); args[1] = e.error_code(); PyErr_SetObject(PyRLException, args.ptr()); } }); py::class_<rl::utility::configuration>(m, "Configuration", R"pbdoc( Container class for all configuration values. Generally is constructed from client.json file read from disk )pbdoc") .def(py::init<>()) .def("get", &rl::utility::configuration::get, py::arg("name"), py::arg("defval"), R"pbdoc( Get a config value or default. :param name: Name of configuration value to get :param defval: Value to return if name does not exist :returns: string value from config )pbdoc") .def("set", &rl::utility::configuration::set); py::class_<rl::live_model>(m, "LiveModel") .def(py::init([](const rl::utility::configuration &config) { auto live_model = std::unique_ptr<rl::live_model>(new rl::live_model(config)); rl::api_status status; THROW_IF_FAIL(live_model->init(&status)); return live_model; }), py::arg("config")) .def(py::init([](const rl::utility::configuration &config, std::function<void(int, const std::string &)> callback) { auto live_model = std::unique_ptr<live_model_with_callback>( new live_model_with_callback(config, callback)); rl::api_status status; THROW_IF_FAIL(live_model->init(&status)); return live_model; }), py::arg("config"), py::arg("callback")) .def( "choose_rank", [](rl::live_model &lm, const char *context, const char *event_id, bool deferred) { rl::ranking_response response; rl::api_status status; unsigned int flags = deferred ? rl::action_flags::DEFERRED : rl::action_flags::DEFAULT; THROW_IF_FAIL( lm.choose_rank(event_id, context, flags, response, &status)); return response; }, py::arg("context"), py::arg("event_id"), py::arg("deferred") = false, R"pbdoc( Request prediction for given context and use the given event_id :rtype: :class:`rl_client.RankingResponse` )pbdoc") .def( "choose_rank", [](rl::live_model &lm, const char *context, bool deferred) { rl::ranking_response response; rl::api_status status; unsigned int flags = deferred ? rl::action_flags::DEFERRED : rl::action_flags::DEFAULT; THROW_IF_FAIL(lm.choose_rank(context, flags, response, &status)); return response; }, py::arg("context"), py::arg("deferred") = false, R"pbdoc( Request prediction for given context and let an event id be generated :rtype: :class:`rl_client.RankingResponse` )pbdoc") .def( "request_episodic_decision", [](rl::live_model &lm, const char* event_id, const char* previous_id, const char* context, rl::episode_state& episode) { rl::ranking_response response; rl::api_status status; THROW_IF_FAIL(lm.request_episodic_decision(event_id, previous_id, context, response, episode, &status)); return response; }, py::arg("event_id"), py::arg("previous_id"), py::arg("context"), py::arg("episode")) .def( "report_action_taken", [](rl::live_model &lm, const char *event_id) { rl::api_status status; THROW_IF_FAIL(lm.report_action_taken(event_id, &status)); }, py::arg("event_id")) .def( "report_outcome", [](rl::live_model &lm, const char *event_id, const char *outcome) { rl::api_status status; THROW_IF_FAIL(lm.report_outcome(event_id, outcome, &status)); }, py::arg("event_id"), py::arg("outcome")) .def( "report_outcome", [](rl::live_model &lm, const char *event_id, float outcome) { rl::api_status status; THROW_IF_FAIL(lm.report_outcome(event_id, outcome, &status)); }, py::arg("event_id"), py::arg("outcome")) .def( "report_outcome", [](rl::live_model &lm, const char *episode_id, const char *event_id, float outcome) { rl::api_status status; THROW_IF_FAIL(lm.report_outcome(episode_id, event_id, outcome, &status)); }, py::arg("episode_id"), py::arg("event_id"), py::arg("outcome")) .def("refresh_model", [](rl::live_model &lm) { rl::api_status status; THROW_IF_FAIL(lm.refresh_model(&status)); }); py::class_<rl::ranking_response>(m, "RankingResponse") .def_property_readonly( "event_id", [](const rl::ranking_response &a) { return a.get_event_id(); }, R"pbdoc( Either the supplied event ID or auto generated if none was given :rtype: str )pbdoc") .def_property_readonly( "chosen_action_id", [](const rl::ranking_response &a) { size_t chosen_action; // todo handle failure a.get_chosen_action_id(chosen_action); return chosen_action; }, R"pbdoc( Action chosen :rtype: int )pbdoc") .def_property_readonly( "model_id", [](const rl::ranking_response &a) { return a.get_model_id(); }, R"pbdoc( ID of model used to make this prediction :rtype: str )pbdoc") .def_property_readonly( "actions_probabilities", [](const rl::ranking_response &a) { py::list return_values; for (const auto &action_prob : a) { return_values.append(py::make_tuple(action_prob.action_id, action_prob.probability)); } return return_values; }, R"pbdoc( The list of action ids and corresponding probabilities :rtype: list[(int,float)] )pbdoc"); // TODO: Expose episode history API. py::class_<rl::episode_state>(m, "EpisodeState") .def(py::init<const char *>()) .def_property_readonly( "episode_id", [](const rl::episode_state &episode) { return episode.get_episode_id(); }); m.def( "create_config_from_json", [](const std::string &config_json) { rl::utility::configuration config; rl::api_status status; THROW_IF_FAIL(rl::utility::config::create_from_json(config_json, config, nullptr, &status)); return config; }, py::arg("config_json"), R"pbdoc( Parse the input as JSON and return an :class:`rl_client.Configuration` object which contains each field. :param config_json: JSON string to parse :returns: :class:`rl_client.Configuration` object containing parsed values )pbdoc"); py::class_<constants>(m, "constants") .def_property_readonly_static("APP_ID", [](py::object /*self*/) { return rl::name::APP_ID; }) .def_property_readonly_static("MODEL_SRC", [](py::object /*self*/) { return rl::name::MODEL_SRC; }) .def_property_readonly_static("MODEL_BLOB_URI", [](py::object /*self*/) { return rl::name::MODEL_BLOB_URI; }) .def_property_readonly_static("MODEL_REFRESH_INTERVAL_MS", [](py::object /*self*/) { return rl::name::MODEL_REFRESH_INTERVAL_MS; }) .def_property_readonly_static("MODEL_IMPLEMENTATION", [](py::object /*self*/) { return rl::name::MODEL_IMPLEMENTATION; }) .def_property_readonly_static("MODEL_BACKGROUND_REFRESH", [](py::object /*self*/) { return rl::name::MODEL_BACKGROUND_REFRESH; }) .def_property_readonly_static("MODEL_VW_INITIAL_COMMAND_LINE", [](py::object /*self*/) { return rl::name::MODEL_VW_INITIAL_COMMAND_LINE; }) .def_property_readonly_static("VW_CMDLINE", [](py::object /*self*/) { return rl::name::VW_CMDLINE; }) .def_property_readonly_static("VW_POOL_INIT_SIZE", [](py::object /*self*/) { return rl::name::VW_POOL_INIT_SIZE; }) .def_property_readonly_static("INITIAL_EPSILON", [](py::object /*self*/) { return rl::name::INITIAL_EPSILON; }) .def_property_readonly_static("LEARNING_MODE", [](py::object /*self*/) { return rl::name::LEARNING_MODE; }) .def_property_readonly_static("PROTOCOL_VERSION", [](py::object /*self*/) { return rl::name::PROTOCOL_VERSION; }) .def_property_readonly_static("INTERACTION_EH_HOST", [](py::object /*self*/) { return rl::name::INTERACTION_EH_HOST; }) .def_property_readonly_static("INTERACTION_EH_NAME", [](py::object /*self*/) { return rl::name::INTERACTION_EH_NAME; }) .def_property_readonly_static("INTERACTION_EH_KEY_NAME", [](py::object /*self*/) { return rl::name::INTERACTION_EH_KEY_NAME; }) .def_property_readonly_static("INTERACTION_EH_KEY", [](py::object /*self*/) { return rl::name::INTERACTION_EH_KEY; }) .def_property_readonly_static("INTERACTION_EH_TASKS_LIMIT", [](py::object /*self*/) { return rl::name::INTERACTION_EH_TASKS_LIMIT; }) .def_property_readonly_static("INTERACTION_EH_MAX_HTTP_RETRIES", [](py::object /*self*/) { return rl::name::INTERACTION_EH_MAX_HTTP_RETRIES; }) .def_property_readonly_static("INTERACTION_SEND_HIGH_WATER_MARK", [](py::object /*self*/) { return rl::name::INTERACTION_SEND_HIGH_WATER_MARK; }) .def_property_readonly_static("INTERACTION_SEND_QUEUE_MAX_CAPACITY_KB", [](py::object /*self*/) { return rl::name::INTERACTION_SEND_QUEUE_MAX_CAPACITY_KB; }) .def_property_readonly_static("INTERACTION_SEND_BATCH_INTERVAL_MS", [](py::object /*self*/) { return rl::name::INTERACTION_SEND_BATCH_INTERVAL_MS; }) .def_property_readonly_static("INTERACTION_SENDER_IMPLEMENTATION", [](py::object /*self*/) { return rl::name::INTERACTION_SENDER_IMPLEMENTATION; }) .def_property_readonly_static("INTERACTION_USE_COMPRESSION", [](py::object /*self*/) { return rl::name::INTERACTION_USE_COMPRESSION; }) .def_property_readonly_static("INTERACTION_USE_DEDUP", [](py::object /*self*/) { return rl::name::INTERACTION_USE_DEDUP; }) .def_property_readonly_static("INTERACTION_QUEUE_MODE", [](py::object /*self*/) { return rl::name::INTERACTION_QUEUE_MODE; }) .def_property_readonly_static("OBSERVATION_EH_HOST", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_HOST; }) .def_property_readonly_static("OBSERVATION_EH_NAME", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_NAME; }) .def_property_readonly_static("OBSERVATION_EH_KEY_NAME", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_KEY_NAME; }) .def_property_readonly_static("OBSERVATION_EH_KEY", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_KEY; }) .def_property_readonly_static("OBSERVATION_EH_TASKS_LIMIT", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_TASKS_LIMIT; }) .def_property_readonly_static("OBSERVATION_EH_MAX_HTTP_RETRIES", [](py::object /*self*/) { return rl::name::OBSERVATION_EH_MAX_HTTP_RETRIES; }) .def_property_readonly_static("OBSERVATION_SEND_HIGH_WATER_MARK", [](py::object /*self*/) { return rl::name::OBSERVATION_SEND_HIGH_WATER_MARK; }) .def_property_readonly_static("OBSERVATION_SEND_QUEUE_MAX_CAPACITY_KB", [](py::object /*self*/) { return rl::name::OBSERVATION_SEND_QUEUE_MAX_CAPACITY_KB; }) .def_property_readonly_static("OBSERVATION_SEND_BATCH_INTERVAL_MS", [](py::object /*self*/) { return rl::name::OBSERVATION_SEND_BATCH_INTERVAL_MS; }) .def_property_readonly_static("OBSERVATION_SENDER_IMPLEMENTATION", [](py::object /*self*/) { return rl::name::OBSERVATION_SENDER_IMPLEMENTATION; }) .def_property_readonly_static("OBSERVATION_USE_COMPRESSION", [](py::object /*self*/) { return rl::name::OBSERVATION_USE_COMPRESSION; }) .def_property_readonly_static("OBSERVATION_QUEUE_MODE", [](py::object /*self*/) { return rl::name::OBSERVATION_QUEUE_MODE; }) .def_property_readonly_static("SEND_HIGH_WATER_MARK", [](py::object /*self*/) { return rl::name::SEND_HIGH_WATER_MARK; }) .def_property_readonly_static("SEND_QUEUE_MAX_CAPACITY_KB", [](py::object /*self*/) { return rl::name::SEND_QUEUE_MAX_CAPACITY_KB; }) .def_property_readonly_static("SEND_BATCH_INTERVAL_MS", [](py::object /*self*/) { return rl::name::SEND_BATCH_INTERVAL_MS; }) .def_property_readonly_static("USE_COMPRESSION", [](py::object /*self*/) { return rl::name::USE_COMPRESSION; }) .def_property_readonly_static("USE_DEDUP", [](py::object /*self*/) { return rl::name::USE_DEDUP; }) .def_property_readonly_static("QUEUE_MODE", [](py::object /*self*/) { return rl::name::QUEUE_MODE; }) .def_property_readonly_static("EH_TEST", [](py::object /*self*/) { return rl::name::EH_TEST; }) .def_property_readonly_static("TRACE_LOG_IMPLEMENTATION", [](py::object /*self*/) { return rl::name::TRACE_LOG_IMPLEMENTATION; }) .def_property_readonly_static("INTERACTION_FILE_NAME", [](py::object /*self*/) { return rl::name::INTERACTION_FILE_NAME; }) .def_property_readonly_static("OBSERVATION_FILE_NAME", [](py::object /*self*/) { return rl::name::OBSERVATION_FILE_NAME; }) .def_property_readonly_static("TIME_PROVIDER_IMPLEMENTATION", [](py::object /*self*/) { return rl::name::TIME_PROVIDER_IMPLEMENTATION; }) .def_property_readonly_static("HTTP_CLIENT_DISABLE_CERT_VALIDATION", [](py::object /*self*/) { return rl::name::HTTP_CLIENT_DISABLE_CERT_VALIDATION; }) .def_property_readonly_static("HTTP_CLIENT_TIMEOUT", [](py::object /*self*/) { return rl::name::HTTP_CLIENT_TIMEOUT; }) .def_property_readonly_static("MODEL_FILE_NAME", [](py::object /*self*/) { return rl::name::MODEL_FILE_NAME; }) .def_property_readonly_static("MODEL_FILE_MUST_EXIST", [](py::object /*self*/) { return rl::name::MODEL_FILE_MUST_EXIST; }) .def_property_readonly_static("ZSTD_COMPRESSION_LEVEL", [](py::object /*self*/) { return rl::name::ZSTD_COMPRESSION_LEVEL; }) .def_property_readonly_static("AZURE_STORAGE_BLOB", [](py::object /*self*/) { return rl::value::AZURE_STORAGE_BLOB; }) .def_property_readonly_static("NO_MODEL_DATA", [](py::object /*self*/) { return rl::value::NO_MODEL_DATA; }) .def_property_readonly_static("FILE_MODEL_DATA", [](py::object /*self*/) { return rl::value::FILE_MODEL_DATA; }) .def_property_readonly_static("VW", [](py::object /*self*/) { return rl::value::VW; }) .def_property_readonly_static("PASSTHROUGH_PDF_MODEL", [](py::object /*self*/) { return rl::value::PASSTHROUGH_PDF_MODEL; }) .def_property_readonly_static("OBSERVATION_EH_SENDER", [](py::object /*self*/) { return rl::value::OBSERVATION_EH_SENDER; }) .def_property_readonly_static("INTERACTION_EH_SENDER", [](py::object /*self*/) { return rl::value::INTERACTION_EH_SENDER; }) .def_property_readonly_static("OBSERVATION_FILE_SENDER", [](py::object /*self*/) { return rl::value::OBSERVATION_FILE_SENDER; }) .def_property_readonly_static("INTERACTION_FILE_SENDER", [](py::object /*self*/) { return rl::value::INTERACTION_FILE_SENDER; }) .def_property_readonly_static("NULL_TRACE_LOGGER", [](py::object /*self*/) { return rl::value::NULL_TRACE_LOGGER; }) .def_property_readonly_static("CONSOLE_TRACE_LOGGER", [](py::object /*self*/) { return rl::value::CONSOLE_TRACE_LOGGER; }) .def_property_readonly_static("NULL_TIME_PROVIDER", [](py::object /*self*/) { return rl::value::NULL_TIME_PROVIDER; }) .def_property_readonly_static("CLOCK_TIME_PROVIDER", [](py::object /*self*/) { return rl::value::CLOCK_TIME_PROVIDER; }) .def_property_readonly_static("LEARNING_MODE_ONLINE", [](py::object /*self*/) { return rl::value::LEARNING_MODE_ONLINE; }) .def_property_readonly_static("LEARNING_MODE_APPRENTICE", [](py::object /*self*/) { return rl::value::LEARNING_MODE_APPRENTICE; }) .def_property_readonly_static("LEARNING_MODE_LOGGINGONLY", [](py::object /*self*/) { return rl::value::LEARNING_MODE_LOGGINGONLY; }) .def_property_readonly_static("CONTENT_ENCODING_IDENTITY", [](py::object /*self*/) { return rl::value::CONTENT_ENCODING_IDENTITY; }) .def_property_readonly_static("CONTENT_ENCODING_DEDUP", [](py::object /*self*/) { return rl::value::CONTENT_ENCODING_DEDUP; }) .def_property_readonly_static("QUEUE_MODE_DROP", [](py::object /*self*/) { return rl::value::QUEUE_MODE_DROP; }) .def_property_readonly_static("QUEUE_MODE_BLOCK", [](py::object /*self*/) { return rl::value::QUEUE_MODE_BLOCK; }); }
51.591022
161
0.652794
[ "object", "model" ]
f0885ecf8b1624e283b40c2728db40062e04886f
556
cpp
C++
examples/cpp_usage_encoding_example.cpp
AmineKhaldi/libbech32
954b14fe81602dde0cf5cb6d45208403160fb76c
[ "BSD-3-Clause" ]
7
2019-11-08T21:36:32.000Z
2021-07-29T07:35:26.000Z
examples/cpp_usage_encoding_example.cpp
AmineKhaldi/libbech32
954b14fe81602dde0cf5cb6d45208403160fb76c
[ "BSD-3-Clause" ]
3
2021-12-26T22:48:04.000Z
2022-01-29T18:03:05.000Z
examples/cpp_usage_encoding_example.cpp
AmineKhaldi/libbech32
954b14fe81602dde0cf5cb6d45208403160fb76c
[ "BSD-3-Clause" ]
6
2019-01-05T22:58:43.000Z
2022-01-22T22:43:24.000Z
#include "libbech32.h" #include <iostream> int main() { // simple human readable part with some data std::string hrp = "hello"; std::vector<unsigned char> data = {14, 15, 3, 31, 13}; // encode std::string bstr = bech32::encode(hrp, data); std::cout << R"(bech32 encoding of human-readable part 'hello' and data part '[14, 15, 3, 31, 13]' is:)" << std::endl; std::cout << bstr << std::endl; // prints "hello1w0rldjn365x" // ... "hello" + Bech32.separator ("1") + encoded data ("w0rld") + 6 char checksum ("jn365x") }
30.888889
122
0.602518
[ "vector" ]
f09027db37a07297dcebab4e3bd5c3b824010565
14,321
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/ArrayAdapter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/ArrayAdapter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/ArrayAdapter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 "Elastos.Droid.Content.h" #include "Elastos.Droid.View.h" #include "elastos/droid/widget/ArrayAdapter.h" #include "elastos/droid/widget/CArrayAdapter.h" #include <elastos/core/StringUtils.h> #include <elastos/core/AutoLock.h> #include <elastos/utility/Arrays.h> #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Content::EIID_IContext; using Elastos::Droid::Content::Res::IResources; using Elastos::Core::AutoLock; using Elastos::Core::CString; using Elastos::Core::StringUtils; using Elastos::Utility::CArrayList; using Elastos::Utility::Arrays; using Elastos::Utility::CCollections; using Elastos::Utility::ICollections; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Widget { ArrayAdapter::ArrayFilter::ArrayFilter( /* [in] */ ArrayAdapter* host) : mHost(host) {} ECode ArrayAdapter::ArrayFilter::PerformFiltering( /* [in] */ ICharSequence* prefix, /* [out] */ IFilterResults** filterResults) { VALIDATE_NOT_NULL(filterResults); AutoPtr<IFilterResults> results = new FilterResults(); if (!mHost->mOriginalValues) { AutoLock lock(mHost->mLock); CArrayList::New(ICollection::Probe(mHost->mObjects), (IArrayList**)&mHost->mOriginalValues); } Int32 length = -1; if (prefix) { prefix->GetLength(&length); } if (prefix == NULL || length == 0) { AutoPtr<IArrayList> list; { AutoLock lock(mHost->mLock); CArrayList::New(ICollection::Probe(mHost->mOriginalValues), (IArrayList**)&list); } Int32 size = 0; mHost->mOriginalValues->GetSize(&size); results->SetValues(list); results->SetCount(size); } else { String prefixString; prefix->ToString(&prefixString); AutoPtr<IArrayList> values; { AutoLock lock(mHost->mLock); CArrayList::New(ICollection::Probe(mHost->mOriginalValues), (IArrayList**)&values); } Int32 count = 0; values->GetSize(&count); AutoPtr<IArrayList> newValues; CArrayList::New((IArrayList**)&newValues); for (Int32 i = 0; i < count; i++) { AutoPtr<IInterface> value; values->Get(i, (IInterface**)&value); String valueText; if (ICharSequence::Probe(value)) { ICharSequence::Probe(value)->ToString(&valueText); } valueText = valueText.ToLowerCase(); // First match against the whole, non-splitted value if (valueText.StartWith(prefixString)) { newValues->Add(value); } else { AutoPtr<ArrayOf<String> > words; StringUtils::Split(valueText, String(" "), (ArrayOf<String>**)&words); const Int32 wordCount = words->GetLength(); // Start at index 0, in case valueText starts with space(s) for (Int32 k = 0; k < wordCount; k++) { if ((*words)[k].StartWith(prefixString)) { newValues->Add(value); break; } } } } results->SetValues(newValues); newValues->GetSize(&count); results->SetCount(count); } *filterResults = results; REFCOUNT_ADD(*filterResults); return NOERROR; } ECode ArrayAdapter::ArrayFilter::PublishResults( /* [in] */ ICharSequence* constraint, /* [in] */ IFilterResults* results) { AutoPtr<IInterface> values; results->GetValues((IInterface**)&values); //noinspection unchecked mHost->mObjects = IList::Probe(values); Int32 count = 0; results->GetCount(&count); if (count > 0) { mHost->NotifyDataSetChanged(); } else { mHost->NotifyDataSetInvalidated(); } return NOERROR; } CAR_INTERFACE_IMPL_2(ArrayAdapter, BaseAdapter, IArrayAdapter, IFilterable); ArrayAdapter::ArrayAdapter() : mResource(0) , mDropDownResource(0) , mFieldId(0) , mNotifyOnChange(TRUE) , mOriginalValues(NULL) {} ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource) { AutoPtr<IList> list; CArrayList::New((IList**)&list); return Init(context, resource, 0, list); } ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ Int32 textViewResourceId) { AutoPtr<IList> list; CArrayList::New((IList**)&list); return Init(context, resource, textViewResourceId, list); } ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ ArrayOf<IInterface*>* objects) { AutoPtr<IList> list; Arrays::AsList(objects, (IList**)&list); return Init(context, resource, 0, list); } ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ Int32 textViewResourceId, /* [in] */ ArrayOf<IInterface*>* objects) { AutoPtr<IList> list; Arrays::AsList(objects, (IList**)&list); return Init(context, resource, textViewResourceId, list); } ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ IList* objects) { return Init(context, resource, 0, objects); } ECode ArrayAdapter::constructor( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ Int32 textViewResourceId, /* [in] */ IList* objects) { return Init(context, resource, textViewResourceId, objects); } ArrayAdapter::~ArrayAdapter() { mOriginalValues = NULL; } ECode ArrayAdapter::Add( /* [in] */ IInterface* object) { { AutoLock syncLock(mLock); if (mOriginalValues != NULL) { mOriginalValues->Add(object); } else { mObjects->Add(object); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::AddAll( /* [in] */ ICollection* collection) { { AutoLock syncLock(mLock); if (mOriginalValues != NULL) { mOriginalValues->AddAll(collection); } else { mObjects->AddAll(collection); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::AddAll( /* [in] */ ArrayOf<IInterface* >* items) { { AutoLock syncLock(mLock); AutoPtr<ICollections> cs; CCollections::AcquireSingleton((ICollections**)&cs); if (mOriginalValues != NULL) { cs->AddAll(ICollection::Probe(mOriginalValues), items); } else { cs->AddAll(ICollection::Probe(mObjects), items); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::Insert( /* [in] */ IInterface* object, /* [in] */ Int32 index) { { AutoLock syncLock(mLock); if (mOriginalValues != NULL) { mOriginalValues->Add(index, object); } else { mObjects->Add(index, object); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::Remove( /* [in] */ IInterface* object) { { AutoLock syncLock(mLock); if (mOriginalValues != NULL) { mOriginalValues->Remove(object); } else { mObjects->Remove(object); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::Clear() { { AutoLock syncLock(mLock); if (mOriginalValues != NULL) { mOriginalValues->Clear(); } else { mObjects->Clear(); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::Sort( /* [in] */ IComparator* comparator) { { AutoLock syncLock(mLock); AutoPtr<ICollections> cs; CCollections::AcquireSingleton((ICollections**)&cs); if (mOriginalValues != NULL) { cs->Sort(IList::Probe(mOriginalValues), comparator); } else { cs->Sort(mObjects, comparator); } } if (mNotifyOnChange) NotifyDataSetChanged(); return NOERROR; } ECode ArrayAdapter::NotifyDataSetChanged() { BaseAdapter::NotifyDataSetChanged(); mNotifyOnChange = TRUE; return NOERROR; } ECode ArrayAdapter::SetNotifyOnChange( /* [in] */ Boolean notifyOnChange) { mNotifyOnChange = notifyOnChange; return NOERROR; } ECode ArrayAdapter::Init( /* [in] */ IContext* context, /* [in] */ Int32 resource, /* [in] */ Int32 textViewResourceId, /* [in] */ IList* objects) { AutoPtr<IInterface> obj; context->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&obj); mInflater = ILayoutInflater::Probe(obj); mResource = mDropDownResource = resource; mObjects = objects; mFieldId = textViewResourceId; IWeakReferenceSource::Probe(context)->GetWeakReference((IWeakReference**)&mWeakContext); return NOERROR; } ECode ArrayAdapter::GetContext( /* [out] */ IContext** context) { VALIDATE_NOT_NULL(context); return mWeakContext->Resolve(EIID_IContext, (IInterface**)context); } ECode ArrayAdapter::GetCount( /* [out] */ Int32* count) { VALIDATE_NOT_NULL(count); return mObjects->GetSize(count); } ECode ArrayAdapter::GetItem( /* [in] */ Int32 position, /* [out] */ IInterface** item) { VALIDATE_NOT_NULL(item); return mObjects->Get(position, item); } ECode ArrayAdapter::GetPosition( /* [in] */ IInterface* item, /* [out] */ Int32* position) { VALIDATE_NOT_NULL(position); return mObjects->IndexOf(item, position); } ECode ArrayAdapter::GetItemId( /* [in] */ Int32 position, /* [out] */ Int64* itemId) { VALIDATE_NOT_NULL(itemId); *itemId = position; return NOERROR; } ECode ArrayAdapter::GetView( /* [in] */ Int32 position, /* [in] */ IView* convertView, /* [in] */ IViewGroup* parent, /* [out] */ IView** view) { VALIDATE_NOT_NULL(view); AutoPtr<IView> v = CreateViewFromResource(position, convertView, parent, mResource); *view = v; REFCOUNT_ADD(*view); return NOERROR; } AutoPtr<IView> ArrayAdapter::CreateViewFromResource( /* [in] */ Int32 position, /* [in] */ IView* convertView, /* [in] */ IViewGroup* parent, /* [in] */ Int32 resource) { AutoPtr<IView> view; AutoPtr<ITextView> text; if (convertView == NULL) { ECode ec = mInflater->Inflate(resource, parent, FALSE, (IView**)&view); if (FAILED(ec) || view == NULL) { Logger::E("ArrayAdapter", "Error: failed to inflate view with : " "position=%d, convertView=%p, parent=%p, resource=%08x, ec=%08x", position, convertView, parent, resource, ec); } } else { view = convertView; } //try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = ITextView::Probe(view); } else { // Otherwise, find the TextView field within the layout AutoPtr<IView> temp; view->FindViewById(mFieldId, (IView**)&temp); text = ITextView::Probe(temp); } if (text == NULL) { Logger::E("ArrayAdapter", "Failed to create view from resource: position=%d, resource=%08x, fieldId=%08x", position, resource, mFieldId); return NULL; } //} catch (ClassCastException e) { // Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); // throw new IllegalStateException( // "ArrayAdapter requires the resource ID to be a TextView", e); //} AutoPtr<IInterface> item; GetItem(position, (IInterface**)&item); if (ICharSequence::Probe(item)) { text->SetText(ICharSequence::Probe(item)); } else { IObject* obj = IObject::Probe(item); if (obj != NULL) { String value; obj->ToString(&value); AutoPtr<ICharSequence> cs; CString::New(value, (ICharSequence**)&cs); text->SetText(cs); } } return view; } ECode ArrayAdapter::SetDropDownViewResource( /* [in] */ Int32 resource) { mDropDownResource = resource; return NOERROR; } ECode ArrayAdapter::GetDropDownView( /* [in] */ Int32 position, /* [in] */ IView* convertView, /* [in] */ IViewGroup* parent, /* [out] */ IView** view) { VALIDATE_NOT_NULL(view); AutoPtr<IView> v = CreateViewFromResource(position, convertView, parent, mDropDownResource); *view = v; REFCOUNT_ADD(*view); return NOERROR; } AutoPtr<IArrayAdapter> ArrayAdapter::CreateFromResource( /* [in] */ IContext* context, /* [in] */ Int32 textArrayResId, /* [in] */ Int32 textViewResId) { AutoPtr<ArrayOf<IInterface*> > strings; AutoPtr<IResources> res; context->GetResources((IResources**)&res); res->GetTextArray(textArrayResId, (ArrayOf<ICharSequence*>**)&strings); AutoPtr<IArrayAdapter> adapter; CArrayAdapter::New(context, textViewResId, (ArrayOf<IInterface*>*)strings, (IArrayAdapter**)&adapter); return adapter; } ECode ArrayAdapter::GetFilter( /* [out] */ IFilter** filter) { VALIDATE_NOT_NULL(filter); if (mFilter == NULL) { mFilter = new ArrayFilter(this); } *filter = mFilter; REFCOUNT_ADD(*filter); return NOERROR; } } // namespace Widget } // namespace Droid } // namespace Elastos
27.330153
114
0.607849
[ "object" ]
f096ef176a91db3dcb2ccfaaf85d378f120d9598
28,079
cpp
C++
amd_tressfx_sample/src/TressFXSample.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
1
2020-07-20T19:07:05.000Z
2020-07-20T19:07:05.000Z
amd_tressfx_sample/src/TressFXSample.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
amd_tressfx_sample/src/TressFXSample.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // Brings together all the TressFX components. // ---------------------------------------------------------------------------- // // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // 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 "TressFXSample.h" #include "PPLLExample.h" #include "ShortCut.h" #include "SuLog.h" #include "SuString.h" #include "SuTypes.h" #include "TressFXAsset.h" #include "SuEffectManager.h" #include "SuEffectTechnique.h" #include "SuGPUResourceManager.h" #include "SuObjectManager.h" #include "AMD_TressFX.h" #include "TressFXLayouts.h" #include "SushiGPUInterface.h" #include "HairStrands.h" #include "SDF.h" #include "Simulation.h" // This could instead be retrieved as a variable from the // script manager, or passed as an argument. static const size_t AVE_FRAGS_PER_PIXEL = 4; static const size_t PPLL_NODE_SIZE = 16; // See TressFXLayouts.h // By default, app allocates space for each of these, and TressFX uses it. // These are globals, because there should really just be one instance. TressFXLayouts* g_TressFXLayouts = 0; extern "C" { void TressFX_DefaultRead(void* ptr, AMD::uint size, EI_Stream* pFile) { FILE* fp = reinterpret_cast<FILE*>(pFile); fread(ptr, size, 1, fp); } void TressFX_DefaultSeek(EI_Stream* pFile, AMD::uint offset) { FILE* fp = reinterpret_cast<FILE*>(pFile); fseek(fp, offset, SEEK_SET); } void SuTressFXError(EI_StringHash message) { SuLogWarning(message); } } TressFXSample::TressFXSample() : m_eOITMethod(OIT_METHOD_SHORTCUT) , m_nScreenWidth(0) , m_nScreenHeight(0) , m_nPPLLNodes(0) { AMD::g_Callbacks.pfMalloc = malloc; AMD::g_Callbacks.pfFree = free; AMD::g_Callbacks.pfError = SuTressFXError; AMD::g_Callbacks.pfRead = TressFX_DefaultRead; AMD::g_Callbacks.pfSeek = TressFX_DefaultSeek; AMD::g_Callbacks.pfCreateLayout = SuCreateLayout; AMD::g_Callbacks.pfDestroyLayout = SuDestroyLayout; AMD::g_Callbacks.pfCreateReadOnlySB = SuCreateReadOnlySB; AMD::g_Callbacks.pfCreateReadWriteSB = SuCreateReadWriteSB; AMD::g_Callbacks.pfCreateCountedSB = SuCreateCountedSB; AMD::g_Callbacks.pfClearCounter = SuClearCounter; AMD::g_Callbacks.pfCopy = SuCopy; AMD::g_Callbacks.pfMap = SuMap; AMD::g_Callbacks.pfUnmap = SuUnmap; AMD::g_Callbacks.pfDestroySB = SuDestroy; AMD::g_Callbacks.pfCreateRT = SuCreateRT; AMD::g_Callbacks.pfCreate2D = SuCreate2D; AMD::g_Callbacks.pfClear2D = SuClear2D; AMD::g_Callbacks.pfSubmitBarriers = SuSubmitBarriers; AMD::g_Callbacks.pfCreateBindSet = SuCreateBindSet; AMD::g_Callbacks.pfDestroyBindSet = SuDestroyBindSet; AMD::g_Callbacks.pfBind = SuBind; AMD::g_Callbacks.pfCreateComputeShaderPSO = SuCreateComputeShaderPSO; AMD::g_Callbacks.pfDestroyPSO = SuDestroyPSO; AMD::g_Callbacks.pfDispatch = SuDispatch; AMD::g_Callbacks.pfCreateIndexBuffer = SuCreateIndexBuffer; AMD::g_Callbacks.pfDestroyIB = SuDestroyIB; AMD::g_Callbacks.pfDraw = SuDrawIndexedInstanced; //m_pFullscreenPass = new FullscreenPass; } TressFXSample::~TressFXSample() { //delete m_pFullscreenPass; EI_Device* pDevice = GetDevice(); for (size_t i = 0; i < m_hairStrands.size(); i++) { //AMD::TressFX_Destroy(&(m_HairObjects[i].first), pDevice); HairStrands::Destroy(m_hairStrands[i], pDevice); } if (m_pPPLL) { m_pPPLL->Shutdown(pDevice); delete m_pPPLL; } if (m_pShortCut) { m_pShortCut->Shutdown(pDevice); delete m_pShortCut; } if (m_pSimulation) { delete m_pSimulation; } #if ENABLE_ROV_TEST if (m_pShortCutROV) { m_pShortCutROV->Destroy(SuGPUResourceManager::GetPtr()); delete m_pShortCutROV; } if (m_pKBufferMutex) { m_pKBufferMutex->Destroy(SuGPUResourceManager::GetPtr()); delete m_pKBufferMutex; } if (m_pKBufferROV) { m_pKBufferROV->Destroy(SuGPUResourceManager::GetPtr()); delete m_pKBufferROV; } #endif for (size_t i = 0; i < m_collisionMeshes.size(); i++) CollisionMesh::Destroy(m_collisionMeshes[i],pDevice); m_collisionMeshes.clear(); m_pShortCutBackBufferView = SuGPURenderableResourceViewPtr(0); m_pShortCutDepthBufferView = SuGPUDepthStencilResourceViewPtr(0); DestroyLayouts(); UnloadEffects(); } void TressFXSample::Simulate(double fTime, bool bUpdateCollMesh, bool bSDFCollisionResponse) { m_pSimulation->StartSimulation(fTime, m_hairStrands, m_collisionMeshes, bUpdateCollMesh, bSDFCollisionResponse); } void TressFXSample::WaitSimulateDone() { m_pSimulation->WaitOnSimulation(); } void TressFXSample::ToggleShortCut() { OITMethod newMethod; if (m_eOITMethod == OIT_METHOD_PPLL) newMethod = OIT_METHOD_SHORTCUT; else newMethod = OIT_METHOD_PPLL; SetOITMethod(newMethod); } void TressFXSample::DrawCollisionMesh() { SuCommandListPtr pCommandList = SuRenderManager::GetRef().GetCurrentCommandList(); for (size_t i = 0; i < m_collisionMeshes.size(); i++) m_collisionMeshes[i]->DrawMesh((EI_CommandContextRef)pCommandList); } void TressFXSample::DrawSDF() { SuCommandListPtr pCommandList = SuRenderManager::GetRef().GetCurrentCommandList(); #if ENABLE_MARCHING_CUBES SuGPUTimerHandle mcTimer = SuRenderManager::GetRef().CreateGPUTimer("Generating Marching Cubes"); GPU_TIMER_START(mcTimer) for (size_t i = 0; i < m_collisionMeshes.size(); i++) m_collisionMeshes[i]->GenerateIsoSurface((EI_CommandContextRef)pCommandList); GPU_TIMER_STOP(mcTimer) UnbindUAVS(); // Engine-required hack to unbind UAVs. for (size_t i = 0; i < m_collisionMeshes.size(); i++) m_collisionMeshes[i]->DrawIsoSurface((EI_CommandContextRef)pCommandList); #endif } void TressFXSample::InitializeLayouts() { // See TressFXLayouts.h // Global storage for layouts. if (g_TressFXLayouts == 0) g_TressFXLayouts = new TressFXLayouts; EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); EI_LayoutManagerRef renderStrandsLayoutManager = GetLayoutManagerRef(m_pHairStrandsEffect);// &(m_pHairStrandsEffect.get()); // Can these be combined? CreateRenderPosTanLayout2(pDevice, renderStrandsLayoutManager); CreateRenderLayout2(pDevice, renderStrandsLayoutManager); CreatePPLLBuildLayout2(pDevice, renderStrandsLayoutManager); CreateShortCutDepthsAlphaLayout2(pDevice, renderStrandsLayoutManager); CreateShortCutFillColorsLayout2(pDevice, renderStrandsLayoutManager); EI_LayoutManagerRef readLayoutManager = GetLayoutManagerRef(m_pHairResolveEffect); CreatePPLLReadLayout2(pDevice, readLayoutManager); CreateShortCutResolveDepthLayout2(pDevice, readLayoutManager); CreateShortCutResolveColorLayout2(pDevice, readLayoutManager); #if ENABLE_ROV_TEST EI_LayoutManager renderStrandsLayoutManagerROVTest = m_pHairStrandsEffectROVTest.get(); CreateShortCutROVBuildLayout(pDevice, renderStrandsLayoutManagerROVTest); CreateKBufferMutexBuildLayout(pDevice, renderStrandsLayoutManagerROVTest); CreateKBufferROVBuildLayout(pDevice, renderStrandsLayoutManagerROVTest); EI_LayoutManager readLayoutManagerROVTest = m_pHairResolveEffectROVTest.get(); CreateShortCutROVReadLayout(pDevice, readLayoutManagerROVTest); CreateKBufferMutexReadLayout(pDevice, readLayoutManagerROVTest); CreateKBufferROVReadLayout(pDevice, readLayoutManagerROVTest); CreateRenderLayoutROVTest(pDevice, renderStrandsLayoutManagerROVTest); CreateRenderPosTanLayoutROVTest(pDevice, renderStrandsLayoutManagerROVTest); #endif } void TressFXSample::DestroyLayouts() { if (g_TressFXLayouts != 0) { EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); DestroyAllLayouts(pDevice); delete g_TressFXLayouts; } } // TODO: Loading asset function should be called from OnAssetReload? void TressFXSample::LoadHairAsset(SuGPUSamplingResourceViewPtr ratColorTextureView) { // TODO Why? DestroyLayouts(); LoadEffects(); InitializeLayouts(); m_pPPLL = new PPLLExample; m_pShortCut = new ShortCut; m_pSimulation = new Simulation; #if ENABLE_ROV_TEST m_pShortCutROV = new TressFXShortCutROV; m_pKBufferMutex = new TressFXKBufferMutex; m_pKBufferROV = new TressFXKBufferROV; #endif EI_Device* pDevice = GetDevice(); // Used for uploading initial data EI_CommandContextRef uploadCommandContext = (EI_CommandContextRef)SuRenderManager::GetRef().GetCurrentCommandList(); // load and create hair objects hairMohawk = HairStrands::Load( "RatBoy_body", "Objects\\HairAsset\\Ratboy\\Ratboy_mohawk.tfx", "Objects\\HairAsset\\Ratboy\\Ratboy_mohawk.tfxbone", "mohawk", 2, // This is number of follow hairs per one guide hair. It could be zero if there is no follow hair at all. 2.0f, ratColorTextureView); hairShort = HairStrands::Load( "RatBoy_body", "Objects\\HairAsset\\Ratboy\\Ratboy_short.tfx", "Objects\\HairAsset\\Ratboy\\Ratboy_short.tfxbone", "hairShort", 0, // no follow hair 0.0f, ratColorTextureView); m_hairStrands.push_back(hairMohawk); m_hairStrands.push_back(hairShort); // load and create collison meshes CollisionMesh* pBody = CollisionMesh::Load( "RatBoy_body", "Objects\\HairAsset\\Ratboy\\Ratboy_body.tfxmesh", 50, 0); CollisionMesh* pLeftHand = CollisionMesh::Load( "RatBoy_left_hand", "Objects\\HairAsset\\Ratboy\\Ratboy_left_hand.tfxmesh", 18, 1.5f); CollisionMesh* pRightHand = CollisionMesh::Load( "RatBoy_right_hand", "Objects\\HairAsset\\Ratboy\\Ratboy_right_hand.tfxmesh", 18, 1.5f); m_collisionMeshes.push_back(pBody); m_collisionMeshes.push_back(pLeftHand); m_collisionMeshes.push_back(pRightHand); } void TressFXSample::LoadEffects() { // if (!m_pHairStrandsEffect) { m_pHairStrandsEffect = SuEffectManager::GetRef().LoadEffect("oHair.sufx"); m_pHairResolveEffect = SuEffectManager::GetRef().LoadEffect("qHair.sufx"); #if ENABLE_ROV_TEST m_pHairStrandsEffectROVTest = SuEffectManager::GetRef().LoadEffect("oHairROVTest.sufx"); m_pHairResolveEffectROVTest = SuEffectManager::GetRef().LoadEffect("qHairROVTest.sufx"); #endif } } void TressFXSample::UnloadEffects() { // if (!m_pHairStrandsEffect) { m_pHairStrandsEffect = SuEffectPtr(0); m_pHairResolveEffect = SuEffectPtr(0); #if ENABLE_ROV_TEST m_pHairStrandsEffectROVTest = SuEffectPtr(0); m_pHairResolveEffectROVTest = SuEffectPtr(0); #endif } } //================================================================================================================================= //================================================================================================================================= void TressFXSample::OnEffectReload(SuEffectPtr pOld, SuEffectPtr pNew) { //m_pSample->OnEffectReload(pOld, pNew); EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); if (m_pHairStrandsEffect == pOld) { //m_pHairStrandsEffect = pNew; SetStrandLayoutManager(pNew); } if (m_pHairResolveEffect == pOld) { SetPPLLResolveLayoutManager(pNew); } } void TressFXSample::SetStrandLayoutManager(SuEffectPtr pNew) { EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); m_pHairStrandsEffect = pNew; EI_LayoutManagerRef renderStrandsLayoutManager = GetLayoutManagerRef(m_pHairStrandsEffect); // Can these be combined? CreateRenderPosTanLayout2(pDevice, renderStrandsLayoutManager); CreateRenderLayout2(pDevice, renderStrandsLayoutManager); CreatePPLLBuildLayout2(pDevice, renderStrandsLayoutManager); CreateShortCutDepthsAlphaLayout2(pDevice, renderStrandsLayoutManager); CreateShortCutFillColorsLayout2(pDevice, renderStrandsLayoutManager); } void TressFXSample::SetPPLLResolveLayoutManager(SuEffectPtr pNew) { EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); m_pHairResolveEffect = pNew; EI_LayoutManagerRef readLayoutManager = GetLayoutManagerRef(m_pHairResolveEffect); CreatePPLLReadLayout2(pDevice, readLayoutManager); } void TressFXSample::UpdateSimulationParameters( const TressFXSimulationSettings& mohawkParameters, const TressFXSimulationSettings& shortHairParameters) { hairMohawk->GetTressFXHandle()->UpdateSimulationParameters(mohawkParameters); hairShort->GetTressFXHandle()->UpdateSimulationParameters(shortHairParameters); } void TressFXSample::OnResize(int width, int height) { // Engine specifics. EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); m_nScreenWidth = width; m_nScreenHeight = height; // TressFX Usage switch (m_eOITMethod) { case OIT_METHOD_PPLL: m_nPPLLNodes = width * height * AVE_FRAGS_PER_PIXEL; m_pPPLL->Shutdown(pDevice); m_pPPLL->Initialize(width, height, m_nPPLLNodes, PPLL_NODE_SIZE, m_pHairStrandsEffect.get(), m_pHairResolveEffect.get()); break; case OIT_METHOD_SHORTCUT: m_pShortCut->Shutdown(pDevice); m_pShortCut->Initialize(width, height, m_pHairStrandsEffect.get(), m_pHairResolveEffect.get()); break; #if ENABLE_ROV_TEST case OIT_METHOD_SHORTCUT_ROV: m_pShortCutROV->Destroy(pDevice); m_pShortCutROV->Create(pDevice, width, height); break; case OIT_METHOD_KBUFFER_MUTEX: m_pKBufferMutex->Destroy(pDevice); m_pKBufferMutex->Create(pDevice, width, height); break; case OIT_METHOD_KBUFFER_ROV: m_pKBufferROV->Destroy(pDevice); m_pKBufferROV->Create(pDevice, width, height); break; #endif }; } void TressFXSample::DrawHairShadows() { SuGPUTimerHandle shadowTimer = SuRenderManager::GetRef().CreateGPUTimer("Shadow"); EI_CommandContextRef pRenderCommandList = (EI_CommandContextRef)SuRenderManager::GetRef().GetCurrentCommandList(); EI_PSO* pso = GetPSOPtr(m_pHairStrandsEffect->GetTechnique("DepthOnly")); SU_ASSERT(pso != nullptr); for (size_t i = 0; i < m_hairStrands.size(); i++) { TressFXHairObject* pHair = m_hairStrands[i]->GetTressFXHandle(); if (pHair) { GPU_TIMER_START(shadowTimer) pHair->DrawStrands(pRenderCommandList, *pso); GPU_TIMER_STOP(shadowTimer) } } } void TressFXSample::DrawHair() { SuGPUTimerHandle drawTimer = SuRenderManager::GetRef().CreateGPUTimer("TRESSFX RENDERING TOTAL"); // Set shader constants for fragment buffer size float4 vFragmentBufferSize; vFragmentBufferSize.x = (float)m_nScreenWidth; vFragmentBufferSize.y = (float)m_nScreenHeight; vFragmentBufferSize.z = (float)m_nScreenWidth * m_nScreenHeight; vFragmentBufferSize.w = 0; m_pHairStrandsEffect->GetParameter("nNodePoolSize")->SetInt(m_nPPLLNodes); m_pHairResolveEffect->GetParameter("nNodePoolSize")->SetInt(m_nPPLLNodes); m_pHairStrandsEffect->GetParameter("vFragmentBufferSize") ->SetFloatVector(&vFragmentBufferSize.x); m_pHairResolveEffect->GetParameter("vFragmentBufferSize") ->SetFloatVector(&vFragmentBufferSize.x); #if ENABLE_ROV_TEST m_pHairStrandsEffectROVTest->GetParameter("nNodePoolSize")->SetInt(m_nPPLLNodes); m_pHairResolveEffectROVTest->GetParameter("nNodePoolSize")->SetInt(m_nPPLLNodes); m_pHairStrandsEffectROVTest->GetParameter("vFragmentBufferSize") ->SetFloatVector(&vFragmentBufferSize.x); m_pHairResolveEffectROVTest->GetParameter("vFragmentBufferSize") ->SetFloatVector(&vFragmentBufferSize.x); #endif GPU_TIMER_START(drawTimer); switch (m_eOITMethod) { case OIT_METHOD_PPLL: DrawHairPPLL(); break; case OIT_METHOD_SHORTCUT: DrawHairShortCut(); break; #if ENABLE_ROV_TEST case OIT_METHOD_SHORTCUT_ROV: DrawHairShortCutROV(); break; case OIT_METHOD_KBUFFER_MUTEX: DrawHairKBufferMutex(); break; case OIT_METHOD_KBUFFER_ROV: DrawHairKBufferROV(); break; #endif }; GPU_TIMER_STOP(drawTimer); } void TressFXSample::SetOITMethod(OITMethod method) { if (method == m_eOITMethod) return; DestroyOITResources(m_eOITMethod); m_eOITMethod = method; OnResize(m_nScreenWidth, m_nScreenHeight); } void TressFXSample::DrawHairPPLL() { m_pPPLL->Draw(m_hairStrands); } void TressFXSample::DrawHairShortCut() { EI_CommandContextRef pRenderCommandList = GetContext(); m_pShortCut->Draw(pRenderCommandList, m_hairStrands); } #if ENABLE_ROV_TEST void SuTressFXPlugin::DrawHairShortCutROV() { SuGPUTimerHandle fillTimer = SuRenderManager::GetRef().CreateGPUTimer("render: SROV Fill"); SuGPUTimerHandle resolveTimer = SuRenderManager::GetRef().CreateGPUTimer("render: SROV Resolve"); EI_CommandContext pRenderCommandList = SuRenderManager::GetRef().GetCurrentCommandList(); EI_PSO buildPSO = const_cast<SuEffectTechnique*>(m_pHairStrandsEffectROVTest->GetTechnique("ShortCutROV")); EI_PSO readPSO = const_cast<SuEffectTechnique*>(m_pHairResolveEffectROVTest->GetTechnique("ShortCutROV")); m_pShortCutROV->Clear(pRenderCommandList); if (m_pShortCutBackBufferView == NULL) { // Initialize back and depth buffer views SuGPUTexture2DArray* tBackBuffer = (SuGPUTexture2DArray*)SuGPUResourceManager::GetRef() .GetNamedResource("tBackBuffer") .get(); SuGPUTexture2DArray* tDepthBuffer = (SuGPUTexture2DArray*)SuGPUResourceManager::GetRef() .GetNamedResource("tDepthBuffer") .get(); SuGPUResourceViewDescription tBackBufferViewDesc( SU_RENDERABLE_VIEW, tBackBuffer->GetFormat(), SuGPUResource::GPU_RESOURCE_TEXTURE_2D_ARRAY, tBackBuffer->GetDefaultResourceDesc()); SuGPUResourceViewDescription tDepthBufferViewDesc( SU_DEPTH_STENCIL_VIEW, SU_FORMAT_D32_FLOAT, SuGPUResource::GPU_RESOURCE_TEXTURE_2D_ARRAY, tDepthBuffer->GetDefaultResourceDesc()); m_pShortCutBackBufferView = tBackBuffer->GetRenderableView(tBackBufferViewDesc); m_pShortCutDepthBufferView = tDepthBuffer->GetDepthStencilView(tDepthBufferViewDesc); } // Bind render targets for DepthsAlpha pass and initialize depths SuRenderManager::GetRef().SetRenderTargets( 1, &m_pShortCutROV->GetInvAlphaTexture().rtv, m_pShortCutDepthBufferView); SuRenderManager::GetRef().SetClearColor(SuVector4(1, 1, 1, 1)); SuRenderManager::GetRef().Clear(true, false, false); m_pShortCutROV->BindForBuild(pRenderCommandList); // put clear in here? for (size_t i = 0; i < m_HairObjects.size(); i++) { TressFXHairObject* pHair = m_HairObjects[i].first; if (pHair) { GPU_TIMER_START(fillTimer); pHair->DrawStrands(pRenderCommandList, GetRenderPosTanLayoutROVTest(), GetRenderLayoutROVTest(), buildPSO); GPU_TIMER_STOP(fillTimer); } } m_pShortCutROV->DoneBuilding(pRenderCommandList); // TODO move this to a clear "after all pos and tan usage by rendering" place. for (size_t i = 0; i < m_HairObjects.size(); i++) m_HairObjects[i].first->GetPosTanCollection().TransitionRenderingToSim(pRenderCommandList); UnbindUAVS(); // Engine-required hack to unbind UAVs. // Bind back buffer for blend SuRenderManager::GetRef().SetRenderTargets( 1, &m_pShortCutBackBufferView, m_pShortCutDepthBufferView); m_pShortCutROV->BindForRead(pRenderCommandList); // Enables lights. Only lights marked to hit TressFX will be applied. if (m_EngineTressFXObjects.size() > 0) { SuObjectManager::GetRef().SetObjectBeingDrawn(m_EngineTressFXObjects[0]); GPU_TIMER_START(resolveTimer); DrawFullscreen(pRenderCommandList, readPSO); GPU_TIMER_STOP(resolveTimer); SuObjectManager::GetRef().SetObjectBeingDrawn(0); } m_pShortCutROV->DoneReading(pRenderCommandList); } void SuTressFXPlugin::DrawHairKBufferMutex() { SuGPUTimerHandle fillTimer = SuRenderManager::GetRef().CreateGPUTimer("render: KMtx Fill"); SuGPUTimerHandle resolveTimer = SuRenderManager::GetRef().CreateGPUTimer("render: KMtx Resolve"); EI_CommandContext pRenderCommandList = SuRenderManager::GetRef().GetCurrentCommandList(); EI_PSO buildPSO = const_cast<SuEffectTechnique*>(m_pHairStrandsEffectROVTest->GetTechnique("MutexDeferred")); EI_PSO readPSO = const_cast<SuEffectTechnique*>(m_pHairResolveEffectROVTest->GetTechnique("MutexDeferred")); m_pKBufferMutex->Clear(pRenderCommandList); m_pKBufferMutex->BindForBuild(pRenderCommandList); // put clear in here? for (size_t i = 0; i < m_HairObjects.size(); i++) { TressFXHairObject* pHair = m_HairObjects[i].first; if (pHair) { GPU_TIMER_START(fillTimer); pHair->DrawStrands(pRenderCommandList, GetRenderPosTanLayoutROVTest(), GetRenderLayoutROVTest(), buildPSO); GPU_TIMER_STOP(fillTimer); } } m_pKBufferMutex->DoneBuilding(pRenderCommandList); // TODO move this to a clear "after all pos and tan usage by rendering" place. for (size_t i = 0; i < m_HairObjects.size(); i++) m_HairObjects[i].first->GetPosTanCollection().TransitionRenderingToSim(pRenderCommandList); UnbindUAVS(); // Engine-required hack to unbind UAVs. m_pKBufferMutex->BindForRead(pRenderCommandList); if (m_EngineTressFXObjects.size() > 0) { // Enables lights. Only lights marked to hit TressFX will be applied. SuObjectManager::GetRef().SetObjectBeingDrawn(m_EngineTressFXObjects[0]); GPU_TIMER_START(resolveTimer); DrawFullscreen(pRenderCommandList, readPSO); GPU_TIMER_STOP(resolveTimer); SuObjectManager::GetRef().SetObjectBeingDrawn(0); } m_pKBufferMutex->DoneReading(pRenderCommandList); } void SuTressFXPlugin::DrawHairKBufferROV() { SuGPUTimerHandle fillTimer = SuRenderManager::GetRef().CreateGPUTimer("render: KROV Fill"); SuGPUTimerHandle resolveTimer = SuRenderManager::GetRef().CreateGPUTimer("render: KROV Resolve"); EI_CommandContext pRenderCommandList = SuRenderManager::GetRef().GetCurrentCommandList(); EI_PSO buildPSO = const_cast<SuEffectTechnique*>( m_pHairStrandsEffectROVTest->GetTechnique("MutexDeferredROV")); EI_PSO readPSO = const_cast<SuEffectTechnique*>( m_pHairResolveEffectROVTest->GetTechnique("MutexDeferredROV")); m_pKBufferROV->Clear(pRenderCommandList); m_pKBufferROV->BindForBuild(pRenderCommandList); // put clear in here? for (size_t i = 0; i < m_HairObjects.size(); i++) { TressFXHairObject* pHair = m_HairObjects[i].first; if (pHair) { GPU_TIMER_START(fillTimer); pHair->DrawStrands(pRenderCommandList, GetRenderPosTanLayoutROVTest(), GetRenderLayoutROVTest(), buildPSO); GPU_TIMER_STOP(fillTimer); } } m_pKBufferROV->DoneBuilding(pRenderCommandList); // TODO move this to a clear "after all pos and tan usage by rendering" place. for (size_t i = 0; i < m_HairObjects.size(); i++) m_HairObjects[i].first->GetPosTanCollection().TransitionRenderingToSim(pRenderCommandList); UnbindUAVS(); // Engine-required hack to unbind UAVs. m_pKBufferROV->BindForRead(pRenderCommandList); if (m_EngineTressFXObjects.size() > 0) { // Enables lights. Only lights marked to hit TressFX will be applied. SuObjectManager::GetRef().SetObjectBeingDrawn(m_EngineTressFXObjects[0]); GPU_TIMER_START(resolveTimer); DrawFullscreen(pRenderCommandList, readPSO); GPU_TIMER_STOP(resolveTimer); SuObjectManager::GetRef().SetObjectBeingDrawn(0); } m_pKBufferROV->DoneReading(pRenderCommandList); } #endif void TressFXSample::DestroyOITResources(OITMethod method) { // Engine specifics. EI_Device* pDevice = (EI_Device*)SuGPUResourceManager::GetPtr(); // TressFX Usage switch (m_eOITMethod) { case OIT_METHOD_PPLL: m_pPPLL->Shutdown(pDevice); break; case OIT_METHOD_SHORTCUT: m_pShortCut->Shutdown(pDevice); break; #if ENABLE_ROV_TEST case OIT_METHOD_SHORTCUT_ROV: m_pShortCutROV->Destroy(pDevice); break; case OIT_METHOD_KBUFFER_MUTEX: m_pKBufferMutex->Destroy(pDevice); break; case OIT_METHOD_KBUFFER_ROV: m_pKBufferROV->Destroy(pDevice); break; #endif }; } SuObject* TressFXSample::GetTressFXObject(int index) { return m_hairStrands[index]->GetAsEngineObject(); } //================================================================================================================================= // // Protected methods block // //================================================================================================================================= //================================================================================================================================= // // Private methods block // //=================================================================================================================================
33.268957
132
0.665052
[ "render" ]
f099229ffe4fccab210c7f4552c9e8d6e5bea74b
8,902
cpp
C++
ROF_Engine/ModuleEditor.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
ROF_Engine/ModuleEditor.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
ROF_Engine/ModuleEditor.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleEditor.h" #include "ModuleWindow.h" #include "ModuleGOManager.h" #include "ModuleFileSystem.h" #include "ModuleSceneImporter.h" #include "ModuleCamera3D.h" #include "GameObject.h" #include "Panel.h" #include "PanelConsole.h" #include "PanelConfiguration.h" #include "PanelHierarchy.h" #include "PanelComponents.h" #include "PanelTimeControl.h" #include <algorithm> #include "ImGui/imgui.h" #include "ImGui/imgui_impl_sdl_gl3.h" using namespace std; ModuleEditor::ModuleEditor(Application* app, bool start_enabled) : Module(app, start_enabled) { name.assign("Editor"); selected_file[0] = '\0'; } // Destructor ModuleEditor::~ModuleEditor() {} // Called before render is available bool ModuleEditor::Init() { ImGui_ImplSdlGL3_Init(App->window->window); panels.push_back(Config = new PanelConfiguration); panels.push_back(Console = new PanelConsole); panels.push_back(Hierarchy = new PanelHierarchy); panels.push_back(Comp = new PanelComponents); panels.push_back(TimeControl = new PanelTimeControl); go_id = 0; return true; } update_status ModuleEditor::PreUpdate(float dt) { ImGui_ImplSdlGL3_NewFrame(App->window->window); return UPDATE_CONTINUE; } update_status ModuleEditor::Update(float dt) { //Creating an ImGui UI if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Quit", "ESC")) { return UPDATE_STOP; } if (ImGui::MenuItem("New Scene")) { App->go_manager->CleanScene(); } if (ImGui::MenuItem("Load Scene...", nullptr, &file_explorer)) { loading_scene = true; frame_name = "Load File"; } if (ImGui::MenuItem("Save Scene...", nullptr, &file_explorer)) { saving_scene = true; frame_name = "Save File"; } if (ImGui::MenuItem("Import FBX", nullptr, &file_explorer)) { importing_scene = true; frame_name = "Import File"; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Edit")) { if (ImGui::MenuItem("Create GameObject")) { char tmp[SHORT_STRING]; sprintf(tmp, "GameObject%d", go_id); go_name = tmp; App->go_manager->CreateGameObject(go_name.c_str(), nullptr); go_id++; } if (ImGui::MenuItem("Create OctTree")) { App->go_manager->DoOctTree(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Window")) { if (ImGui::MenuItem("Configuration", "C", &Config->active)); if (ImGui::MenuItem("Console", "CTR+C", &Console->active)); if (ImGui::MenuItem("Hierarchy", "CTR+O", &Hierarchy->active)); if (ImGui::MenuItem("Time Controller", "CTR+T", &TimeControl->active)); ImGui::EndMenu(); } if (ImGui::BeginMenu("Debug Tools")) { if (ImGui::MenuItem("Show AABB", "B", &aabb_debug)) { App->go_manager->ShowAABB(aabb_debug); } if (ImGui::MenuItem("Show GO OctTree", "T", &octtree_debug)) { App->go_manager->show_tree = octtree_debug; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Help")) { if (ImGui::MenuItem("Download latest")) { App->RequestBrowser("https://github.com/RogerOlasz/ROF_Engine/releases"); } if (ImGui::MenuItem("Report a bug")) { App->RequestBrowser("https://github.com/RogerOlasz/ROF_Engine/issues"); } if (ImGui::MenuItem("Source code")) { App->RequestBrowser("https://github.com/RogerOlasz/ROF_Engine"); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } //ROF Discomment it to edit ImGuiC Colors //ImGui::ShowStyleEditor(); //Draw all active panels Panel* panel; for (vector<Panel*>::iterator tmp = panels.begin(); tmp != panels.end(); ++tmp) { panel = (*tmp); if (panel->IsActive()) { panel->Draw(); } } Comp->Draw(Hierarchy->GetSelectedGO()); if (file_explorer == true && App->editor->FileDialog(nullptr, "Assets/")) { const char* file = App->editor->CloseFileDialog(); if (file != nullptr && loading_scene) { App->go_manager->LoadScene(file); App->go_manager->want_to_load_scene = true; } if (file != nullptr && saving_scene) { std::string tmp = file; tmp.append(".xml"); App->go_manager->SaveScene(tmp.c_str()); App->go_manager->want_to_save_scene = true; } if (file != nullptr && importing_scene) { App->importer->LoadFBX(file); } importing_scene = false; loading_scene = false; saving_scene = false; file_explorer = false; } if (file_dialog == opened) { LoadFile((file_dialog_filter.length() > 0) ? file_dialog_filter.c_str() : nullptr); } else { in_modal = false; } return UPDATE_CONTINUE; } update_status ModuleEditor::PostUpdate(float dt) { ImGui::Render(); return UPDATE_CONTINUE; } bool ModuleEditor::Load(pugi::xml_node &config) { SetMaxFPS(config.child("Framerate").attribute("Cap_FPS").as_uint(60)); return true; } bool ModuleEditor::Save(pugi::xml_node &config) const { pugi::xml_node tmp_node = config.append_child("Framerate"); tmp_node.append_attribute("Cap_FPS") = GetMaxFPS(); return true; } // Called before quitting bool ModuleEditor::CleanUp() { for (vector<Panel*>::iterator tmp = panels.begin(); tmp != panels.end(); ++tmp) { RELEASE(*tmp); } panels.clear(); ImGui_ImplSdlGL3_Shutdown(); return true; } void ModuleEditor::Log(const char* log) { if (Console != NULL) { Console->AddLog(log); } } void ModuleEditor::SetMaxFPS(uint new_fps_cap) { Config->SetMaxFPS(new_fps_cap); } void ModuleEditor::LogFPS(const float* fps, const float ms) { Config->Log(fps, ms); } uint ModuleEditor::GetMaxFPS() const { return Config->GetMaxFPS(); } void ModuleEditor::SetSelectedGO(GameObject* go) { Hierarchy->SetSelectedGO(go); } void ModuleEditor::SetLastGO(GameObject* go) { Comp->last_go = go; } void ModuleEditor::LoadFile(const char* filter_extension, const char* from_dir) { ImGui::OpenPopup(frame_name.c_str()); if (ImGui::BeginPopupModal(frame_name.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { in_modal = true; ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); ImGui::BeginChild("File Browser", ImVec2(0, 300), true); DrawDirectoryRecursive(from_dir, filter_extension); ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PushItemWidth(250.f); if (ImGui::InputText("##file_selector", selected_file, MEDIUM_STRING, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) { file_dialog = ready_to_close; } ImGui::PopItemWidth(); ImGui::SameLine(); if (ImGui::Button("Ok", ImVec2(50, 20))) { file_dialog = ready_to_close; } ImGui::SameLine(); if (ImGui::Button("Cancel", ImVec2(50, 20))) { file_dialog = ready_to_close; selected_file[0] = '\0'; } ImGui::EndPopup(); } else { in_modal = false; } } void ModuleEditor::DrawDirectoryRecursive(const char* directory, const char* filter_extension) { vector<string> files; vector<string> dirs; std::string dir((directory) ? directory : ""); dir += "/"; App->physfs->DiscoverFiles(dir.c_str(), files, dirs); for (vector<string>::const_iterator it = dirs.begin(); it != dirs.end(); ++it) { if (ImGui::TreeNodeEx((dir + (*it)).c_str(), 0, "%s/", (*it).c_str())) { DrawDirectoryRecursive((dir + (*it)).c_str(), filter_extension); ImGui::TreePop(); } } std::sort(files.begin(), files.end()); for (vector<string>::const_iterator it = files.begin(); it != files.end(); ++it) { const string& str = *it; bool ok = true; if (filter_extension && str.substr(str.find_last_of(".") + 1) != filter_extension) { ok = false; } if (ok && ImGui::TreeNodeEx(str.c_str(), ImGuiTreeNodeFlags_Leaf)) { if (ImGui::IsItemClicked()) { sprintf_s(selected_file, MEDIUM_STRING, "%s%s", dir.substr(1).c_str(), str.c_str()); //Changed dir if (ImGui::IsMouseDoubleClicked(0)) { file_dialog = ready_to_close; } } ImGui::TreePop(); } } } bool ModuleEditor::FileDialog(const char * extension, const char* from_folder) { bool ret = true; App->camera->controls_disabled = true; switch (file_dialog) { case closed: selected_file[0] = '\0'; file_dialog_filter = (extension) ? extension : ""; file_dialog_origin = (from_folder) ? from_folder : ""; file_dialog = opened; case opened: ret = false; break; } return ret; } const char * ModuleEditor::CloseFileDialog() { App->camera->controls_disabled = false; if (file_dialog == ready_to_close) { file_dialog = closed; return selected_file[0] ? selected_file : nullptr; } return nullptr; }
21.926108
147
0.639632
[ "render", "vector" ]
f09923c0338ca264eb06a4791cd0601d2a223fa9
6,011
cpp
C++
Builder/Builder/src/rangeencoder.cpp
sglab/OpenIRT
1a1522ed82f6bb26f1d40dc93024487869045ab2
[ "BSD-2-Clause" ]
2
2015-09-28T12:59:25.000Z
2020-03-28T22:28:03.000Z
Builder/Builder/src/rangeencoder.cpp
sglab/OpenIRT
1a1522ed82f6bb26f1d40dc93024487869045ab2
[ "BSD-2-Clause" ]
2
2018-10-26T12:17:53.000Z
2018-11-09T07:04:17.000Z
Builder/Builder/src/rangeencoder.cpp
sglab/OpenIRT
1a1522ed82f6bb26f1d40dc93024487869045ab2
[ "BSD-2-Clause" ]
null
null
null
/* =============================================================================== FILE: rangeencoder.cpp CONTENTS: see header file PROGRAMMERS: martin isenburg@cs.unc.edu COPYRIGHT: copyright (C) 2003 martin isenburg (isenburg@cs.unc.edu) This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: see header file =============================================================================== */ #include "rangeencoder.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include "App.h" bool g_ModelUpdate = true; // flag incicating that we don't update model RangeEncoder::RangeEncoder(FILE* fp, bool store_chars) { if (fp) { this->fp = fp; chars = 0; number_chars = 0; } else { this->fp = 0; if (store_chars) { chars = (unsigned char*)malloc(sizeof(unsigned char)*1000); number_chars = 0; allocated_chars = 1000; } else { chars = 0; number_chars = 0; } } low = 0; /* Full code range */ range = TOP_VALUE; /* this buffer is written as first byte in the datastream (header,...) */ buffer = HEADERBYTE; help = 0; /* No bytes to follow */ bytecount = 0; } void RangeEncoder::encode(RangeModel* rm, unsigned int sym) { unsigned int syfreq; unsigned int ltfreq; unsigned int r, tmp; unsigned int lg_totf = rm->lg_totf; assert(sym >= 0 && sym < (unsigned int)rm->n); rm->getfreq(sym,&syfreq,&ltfreq); normalize(); r = range >> lg_totf; tmp = r * ltfreq; low += tmp; #ifdef EXTRAFAST range = r * syfreq; #else if ((ltfreq+syfreq) >> lg_totf) { range -= tmp; } else { range = r * syfreq; } #endif #ifdef PARTIAL_MODELER_UPDATE if (g_ModelUpdate) rm->update(sym); #else rm->update(sym); #endif } void RangeEncoder::encode(unsigned int range, unsigned int sym) { assert(sym >= 0 && sym < range); if (range < sym) printf ("hello\n"); if (range > 4194303) // 22 bits { encodeShort(sym&65535); sym = sym >> 16; range = range >> 16; range++; } unsigned int r, tmp; normalize(); r = this->range / range; tmp = r * sym; low += tmp; #ifdef EXTRAFAST this->range = r; #else if (sym+1 < range) { this->range = r; } else { this->range -= tmp; } #endif } void RangeEncoder::encodeByte(unsigned char c) { assert(c >= 0 && c < 256); unsigned int r, tmp; normalize(); r = range >> 8; tmp = r * (unsigned int)(c); low += tmp; #ifdef EXTRAFAST range = r; #else if (((unsigned int)(c)+1) >> 8) { range -= tmp; } else { range = r; } #endif } void RangeEncoder::encodeShort(unsigned short s) { assert(s >= 0 && s < 65536); unsigned int r, tmp; normalize(); r = range >> 16; tmp = r * (unsigned int)(s); low += tmp; #ifdef EXTRAFAST range = r; #else if (((unsigned int)(s)+1) >> 16) { range -= tmp; } else { range = r; } #endif } void RangeEncoder::encodeInt(unsigned int i) { encodeShort((unsigned short)(i % 65536)); // lower 16 bits encodeShort((unsigned short)(i / 65536)); // UPPER 16 bits } void RangeEncoder::encodeFloat(float f) { encodeInt(*((unsigned int*)(&f))); } /* I do the normalization before I need a defined state instead of */ /* after messing it up. This simplifies starting and ending. */ inline void RangeEncoder::normalize() { while(range <= BOTTOM_VALUE) /* do we need renormalisation? */ { if (low < (unsigned int)0xff<<SHIFT_BITS) /* no carry possible --> output */ { outbyte(buffer); for(; help; help--) { outbyte(0xff); } buffer = (unsigned char)(low >> SHIFT_BITS); } else if (low & TOP_VALUE) /* carry now, no future carry */ { outbyte(buffer+1); for(; help; help--) { outbyte(0); } buffer = (unsigned char)(low >> SHIFT_BITS); } else /* passes on a potential carry */ { help++; } range <<= 8; low = (low<<8) & (TOP_VALUE-1); bytecount++; } } /* Finish encoding */ /* actually not that many bytes need to be output, but who */ /* cares. I output them because decode will read them :) */ /* the return value is the number of bytes written */ unsigned int RangeEncoder::done() { unsigned int tmp; normalize(); /* now we have a normalized state */ bytecount += 5; if ((low & (BOTTOM_VALUE-1)) < ((bytecount&0xffffffL)>>1)) { tmp = low >> SHIFT_BITS; } else { tmp = (low >> SHIFT_BITS) + 1; } if (tmp > 0xff) /* we have a carry */ { outbyte(buffer+1); for(; help; help--) { outbyte(0); } } else /* no carry */ { outbyte(buffer); for(; help; help--) { outbyte(0xff); } } outbyte(tmp & 0xff); outbyte((bytecount>>16) & 0xff); outbyte((bytecount>>8) & 0xff); outbyte(bytecount & 0xff); return bytecount; } RangeEncoder::~RangeEncoder() { if (chars) { free(chars); } } unsigned char* RangeEncoder::getChars() { return chars; } int RangeEncoder::getNumberChars() { return number_chars; } long RangeEncoder::getNumberBits() { return bytecount*8; } int RangeEncoder::getNumberBytes() { return bytecount; } inline void RangeEncoder::outbyte(unsigned int c) { if (fp) { fputc(c, fp); } else { if (chars) { if (number_chars == allocated_chars) { unsigned char* newchars = (unsigned char*) malloc(sizeof(unsigned char)*allocated_chars*2); memcpy(newchars,chars,sizeof(unsigned char)*allocated_chars); free(chars); chars = newchars; allocated_chars = allocated_chars*2; } chars[number_chars++] = c; } } }
18.784375
99
0.560472
[ "model" ]
f09a3f1804196ada1c445d60fd6738137451304a
4,433
cpp
C++
Game/ConfigurationManager.cpp
roooodcastro/gamedev-coursework
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
[ "MIT" ]
1
2019-10-05T23:31:00.000Z
2019-10-05T23:31:00.000Z
Game/ConfigurationManager.cpp
roooodcastro/gamedev-coursework
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
[ "MIT" ]
null
null
null
Game/ConfigurationManager.cpp
roooodcastro/gamedev-coursework
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
[ "MIT" ]
null
null
null
#include "ConfigurationManager.h" ConfigurationManager *ConfigurationManager::instance = NULL; ConfigurationManager::ConfigurationManager(void) { configFileName = "settings.cfg"; } ConfigurationManager::~ConfigurationManager(void) { } ConfigurationManager *ConfigurationManager::getInstance() { if (instance == NULL) { instance = new ConfigurationManager(); } return instance; } bool ConfigurationManager::readBool(std::string configName, bool defaultValue) { if (configExists(configName)) { std::string value = readString(configName, "true"); return value == "true"; } return defaultValue; } int ConfigurationManager::readInt(std::string configName, int defaultValue) { if (configExists(configName)) { std::string value = readString(configName, "0"); return atoi(value.c_str()); } return defaultValue; } float ConfigurationManager::readFloat(std::string configName, float defaultValue) { if (configExists(configName)) { std::string value = readString(configName, "0"); return atof(value.c_str()); } return defaultValue; } std::string ConfigurationManager::readString(std::string configName, std::string defaultValue) { if (configExists(configName)) { std::ifstream file(configFileName); if (!file.is_open()) { std::cout << "ERROR: Cannot open the configuration file: " << configFileName << std::endl; return false; } std::vector<std::string> lines; char lineBuffer[200]; while(!file.eof()) { file.getline(lineBuffer, 200); lines.emplace_back(lineBuffer); } for (unsigned i = 0; i < lines.size(); i++) { std::string line = lines[i]; line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); std::vector<std::string> splitted = split(line, '='); if (splitted[0].compare(configName) == 0) { return std::string(splitted[1]); } } } return defaultValue; } void ConfigurationManager::writeConfig(std::string configName, int value) { std::ostringstream convert; convert << value; writeConfig(configName, (std::string) convert.str()); } void ConfigurationManager::writeConfig(std::string configName, bool value) { writeConfig(configName, (std::string) (value ? "true" : "false")); } void ConfigurationManager::writeConfig(std::string configName, float value) { std::ostringstream convert; convert << value; writeConfig(configName, (std::string) convert.str()); } void ConfigurationManager::writeConfig(std::string configName, std::string value) { // Read the config file std::fstream file(configFileName); if (!file.is_open()) { std::cout << "ERROR: Cannot open the configuration file: " << configFileName << std::endl; return; } std::vector<std::string> lines; char lineBuffer[200]; while(!file.eof()) { file.getline(lineBuffer, 200); lines.emplace_back(lineBuffer); } int lineNum = -1; // Find the line of the configuration, if it exists for (unsigned i = 0; i < lines.size(); i++) { std::string line = lines[i]; line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); std::vector<std::string> splitted = split(line, '='); if (splitted.size() >= 2) { if (splitted[0].compare(configName) == 0) { lineNum = i; } } } // Change the config value if (lineNum >= 0) { lines[lineNum] = configName + "=" + value; } else { lines.emplace_back(configName + "=" + value); } // Now recreate the file and rewrite its contents file.close(); file.open(configFileName, std::ofstream::out | std::ofstream::trunc); for (unsigned i = 0; i < lines.size(); i++) { if (lines[i].size() > 0) { file << lines[i] << std::endl; } } } bool ConfigurationManager::configExists(std::string configName) { std::ifstream file(configFileName); if (!file.is_open()) { std::cout << "ERROR: Cannot open the configuration file: " << configFileName << std::endl; return false; } std::vector<std::string> lines; char lineBuffer[200]; while(!file.eof()) { file.getline(lineBuffer, 200); lines.emplace_back(lineBuffer); } for (unsigned i = 0; i < lines.size(); i++) { std::string line = lines[i]; line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); std::vector<std::string> splitted = split(line, '='); if (splitted.size() > 0) { if (splitted[0].compare(configName) == 0) { return true; } } } return false; }
29.952703
117
0.681254
[ "vector" ]
f09daddfe6b73011b52412f50ee617562f818491
7,494
cpp
C++
NativeMultiClockDLL/ClockWindowRefresh.cpp
lukasniemeier/multiclock
e8e38775bc4778e2f3772d00f4d52bc218c70075
[ "MIT" ]
4
2015-04-21T15:06:06.000Z
2017-10-20T13:46:23.000Z
NativeMultiClockDLL/ClockWindowRefresh.cpp
lukasniemeier/multiclock
e8e38775bc4778e2f3772d00f4d52bc218c70075
[ "MIT" ]
null
null
null
NativeMultiClockDLL/ClockWindowRefresh.cpp
lukasniemeier/multiclock
e8e38775bc4778e2f3772d00f4d52bc218c70075
[ "MIT" ]
null
null
null
#include "ClockWindow.h" #include <vector> using namespace Gdiplus; #ifdef _DEBUG static void SaveBitmap(Bitmap* bitmap) { CLSID guid; ::CLSIDFromString(L"{557CF406-1A04-11D3-9A73-0000F81EF32E}", &guid); Status saveStatus = bitmap->Save(L"C:\\Users\\Hugo\\bitmap.png", &guid); if (saveStatus != Status::Ok) { Beep(200, 100); Beep(200, 100); } } #endif static std::wstring TextTime(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr) { int textLength = ::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, nullptr, 0); wchar_t* textBuffer = new wchar_t[textLength]; ::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, textBuffer, textLength); std::wstring text(textBuffer); delete textBuffer; return text; } static std::wstring TextDate(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr) { int textLength = ::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, nullptr, 0, nullptr); wchar_t* textBuffer = new wchar_t[textLength]; ::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, textBuffer, textLength, nullptr); std::wstring text(textBuffer); delete textBuffer; return text; } void ClockWindow::RenderClickedState(Gdiplus::Graphics* graphics, int width, int height) const { Rect stateRect(1, 0, width - 1, height); SolidBrush brush(Color(5, 255, 255, 255)); graphics->FillRectangle(&brush, stateRect); } void ClockWindow::RenderHighlight(Gdiplus::Graphics* graphics, int width, int height) const { int otherColorsCount = 1; Color centerBarColor = Color(192, 200, 200, 200); Color otherBarColors[] = { Color(0, 200, 200, 200) }; // Draw left highlight bar... const Rect leftHightlightRect(1, 0, 2, height); GraphicsPath leftHighlightPath; leftHighlightPath.AddRectangle(leftHightlightRect); PathGradientBrush leftHighlightBrush(&leftHighlightPath); leftHighlightBrush.SetCenterColor(centerBarColor); leftHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount); graphics->FillPath(&leftHighlightBrush, &leftHighlightPath); // ... and draw the right one... const Rect rightHightlightRect(width - 3, 0, 2, height); GraphicsPath rightHighlightPath; rightHighlightPath.AddRectangle(rightHightlightRect); PathGradientBrush rightHighlightBrush(&rightHighlightPath); rightHighlightBrush.SetCenterColor(centerBarColor); rightHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount); graphics->FillPath(&rightHighlightBrush, &rightHighlightPath); // ... and the blue highlight dot Color centerDotColor = Color(200, 177, 211, 255); Color otherDotColors[] = { Color(0, 255, 255, 255) }; GraphicsPath dotPath; dotPath.AddEllipse(width / 3.f, height * 0.66f, width / 3.f, (REAL)height); PathGradientBrush dotBursh(&dotPath); dotBursh.SetCenterColor(centerDotColor); dotBursh.SetSurroundColors(otherDotColors, &otherColorsCount); graphics->FillPath(&dotBursh, &dotPath); const Rect dotLineRect(0, height - 1, width, 1); Color colors[] = { otherDotColors[0], centerDotColor, otherDotColors[0] }; REAL positions[] = { 0.0f, 0.5f, 1.0f }; LinearGradientBrush dotLineBrush( Point(dotLineRect.X, dotLineRect.Y), Point(dotLineRect.GetRight(), dotLineRect.GetBottom()), Color(255, 0, 0, 0), Color(255, 255, 255, 255)); dotLineBrush.SetInterpolationColors(colors, positions, 3); graphics->FillRectangle(&dotLineBrush, dotLineRect); } void ClockWindow::RenderTime(HDC context, int maxWidth, int maxHeight) const { // Get the current system font... NONCLIENTMETRICS metrics; metrics.cbSize = sizeof(NONCLIENTMETRICS); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0); HFONT font = ::CreateFontIndirect(&metrics.lfStatusFont); HFONT oldFont = (HFONT)::SelectObject(context, font); int oldBkMode = ::SetBkMode(context, TRANSPARENT); int oldTextColor = ::SetTextColor(context, GetSysColor(COLOR_3DFACE)); std::wstring timeText; { RECT textRect; int textRectWidth; SYSTEMTIME time; GetLocalTime(&time); std::wstring dateText; std::wstring dayText; timeText = TextTime(time, TIME_NOSECONDS); if (maxHeight >= 36) { if (maxHeight >= 53) { dayText = TextDate(time, 0, L"dddd"); textRect = { 0, 0, maxWidth, maxHeight }; std::vector<wchar_t> textBuffer(dayText.begin(), dayText.end()); textBuffer.push_back('\0'); ::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr); textRectWidth = textRect.right - textRect.left; if (textRectWidth <= maxWidth) { timeText += L"\n"; timeText += dayText; } } dateText = TextDate(time, DATE_SHORTDATE); textRect = { 0, 0, maxWidth, maxHeight }; std::vector<wchar_t> textBuffer(dayText.begin(), dayText.end()); textBuffer.push_back('\0'); ::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr); textRectWidth = textRect.right - textRect.left; if (textRectWidth <= maxWidth) { timeText += L"\n"; timeText += dateText; } } } RECT textRect = { 0, 0, maxWidth, maxHeight }; std::vector<wchar_t> textBuffer(timeText.begin(), timeText.end()); textBuffer.push_back('\0'); ::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr); // move text rect to (0,0) ::OffsetRect(&textRect, -textRect.left, -textRect.top); // center text rect ::OffsetRect(&textRect, (int)((maxWidth - textRect.right) / 2.0), (int)((maxHeight - textRect.bottom) / 2.0)); // draw ::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CENTER | DT_NOCLIP, nullptr); ::SetTextColor(context, oldTextColor); ::SetBkMode(context, oldBkMode); ::SelectObject(context, oldFont); ::DeleteObject(font); } void ClockWindow::RenderHighlighting(Graphics* graphics, int width, int height) const { SolidBrush burshClear(Color::Transparent); graphics->FillRectangle(&burshClear, 0, 0, width, height); if (isClicked) { RenderClickedState(graphics, width, height); } if (isHighlighted) { RenderHighlight(graphics, width, height); } } bool ClockWindow::IsVisible(const RECT& clientRect) { return true; } void ClockWindow::Refresh(bool force) { OUTPUT_DEBUG_STRING(L"Clock refresh requested. Force =", force); RECT clientRect; GetClientRect(&clientRect); if (!force && !IsVisible(clientRect)) { return; } int width = clientRect.right - clientRect.left; int height = clientRect.bottom - clientRect.top; Bitmap* bitmap = new Bitmap(width, height, PixelFormat32bppPARGB); Status status = bitmap->GetLastStatus(); if (status != Status::Ok) { delete bitmap; return; } Graphics* g = Graphics::FromImage(bitmap); RenderHighlighting(g, width, height); delete g; HBITMAP hbitmap; bitmap->GetHBITMAP(NULL, &hbitmap); HDC hdcScreen = ::GetDC(nullptr); HDC hDC = ::CreateCompatibleDC(hdcScreen); HBITMAP hbitmapOld = (HBITMAP) ::SelectObject(hDC, hbitmap); RenderTime(hDC, width, height); SIZE sizeWnd = { width, height }; POINT ptSrc = { 0, 0 }; BLENDFUNCTION blend = { 0 }; blend.BlendOp = AC_SRC_OVER; blend.SourceConstantAlpha = 255; blend.AlphaFormat = AC_SRC_ALPHA; ::UpdateLayeredWindow(this->m_hWnd, hdcScreen, nullptr, &sizeWnd, hDC, &ptSrc, 0, &blend, ULW_ALPHA); ::SelectObject(hDC, hbitmapOld); ::DeleteObject(hbitmap); ::DeleteDC(hDC); ::ReleaseDC(NULL, hdcScreen); delete bitmap; OUTPUT_DEBUG_STRING(L"Clock has been refreshed."); }
29.738095
122
0.726181
[ "vector" ]
f09ff89c472b9ee141af996723cf70d6c6b16211
3,868
cpp
C++
NewClockWorkEngine/Hierarchy.cpp
xsiro/NewClockWorkEngine
973627ac98261f1009b5a0fd1f8a4b4d706d330a
[ "MIT" ]
null
null
null
NewClockWorkEngine/Hierarchy.cpp
xsiro/NewClockWorkEngine
973627ac98261f1009b5a0fd1f8a4b4d706d330a
[ "MIT" ]
null
null
null
NewClockWorkEngine/Hierarchy.cpp
xsiro/NewClockWorkEngine
973627ac98261f1009b5a0fd1f8a4b4d706d330a
[ "MIT" ]
null
null
null
#include "Hierarchy.h" #include "imgui/imgui.h" #include "Globals.h" #include "Application.h" #include "ModuleSceneIntro.h" #include "GameObject.h" //value ret tied to SHow Hierarchy bool ShowHierarchyTab() { bool ret = true; if (App->scene->root != nullptr) { SeekMyChildren(App->scene->root); } return ret; } //This is the recursive func that makes the hierarchy void SeekMyChildren(GameObject* myself) { bool droppedItem = false; ImGuiTreeNodeFlags TreeNodeEx_flags = ImGuiTreeNodeFlags_OpenOnArrow; //yeah, we have to set it each iteration. ImGui Badness if (myself->children.size() == 0) TreeNodeEx_flags = ImGuiTreeNodeFlags_Leaf; if (myself == App->scene->root) { for (int i = 0; i < myself->children.size(); i++) { SeekMyChildren(myself->children[i]); } } else { ImGui::PushStyleColor(ImGuiCol_Text, ChooseMyColor(myself)); bool open = ImGui::TreeNodeEx(myself->GetName().c_str(), TreeNodeEx_flags); //========================================================================================== // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { // Set payload to carry the object pointer ImGui::SetDragDropPayload("OBJ_ID", &myself->ID, sizeof(unsigned int)); // Display preview (could be anything, e.g. when dragging an image we could decide to display // the filename and a small preview of the image, etc.) ImGui::Text("%s", myself->GetName().c_str()); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload * payload = ImGui::AcceptDragDropPayload("OBJ_ID")) { IM_ASSERT(payload->DataSize == sizeof(unsigned int)); //int payload_n = *(const int*)payload->Data; GameObject* newObj = nullptr; App->scene->root->GetChildWithID(*(const unsigned int*)payload->Data, newObj); GameObject* newParent = nullptr; App->scene->root->GetChildWithID(myself->ID, newParent); GameObject* isParent = nullptr; newObj->GetChildWithID(newParent->ID, isParent); if (!isParent) newObj->ChangeParent(newParent); /*newParent->children.push_back(newObj); newObj->parent = newParent;*/ /*if (mode == Mode_Move) { names[n] = names[payload_n]; names[payload_n] = ""; }*/ droppedItem = true; } ImGui::EndDragDropTarget(); } //========================================================================================== if (ImGui::IsItemHovered())//we use itemHovered + mouse click check because we want the mouse to perform the action on key up, otherwise it would select an item when dropping a payload { //this if is redundant, check is already done inside setSelectedGameObject() /*if (!App->scene->GetSelectedGameObject().empty()) { App->scene->GetSelectedGameObject().back()->focused = false; }*/ if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP&& !droppedItem) { if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT) { App->scene->SetSelectedGameObject(myself, true); } else if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT) { App->scene->RemoveGameObjFromSelected(myself); } else { App->scene->SetSelectedGameObject(myself); } } } if (open == true) { for (int i = 0; i < myself->children.size(); i++) { SeekMyChildren(myself->children[i]); } ImGui::TreePop(); } ImGui::PopStyleColor(); } } //Quick func that return the color vector based on IsActive ImVec4 ChooseMyColor(GameObject* myself) { ImVec4 activeColor ACTIVE_COLOR; if (!myself->isActive || !myself->IsParentActive()) activeColor = ImVec4 PASIVE_COLOR; if (myself->focused) activeColor = ImVec4 FOCUSED_COLOR; else if (myself->selected) activeColor = ImVec4 SELECTED_COLOR; return activeColor; }
25.615894
186
0.648656
[ "object", "vector" ]
f0a98d429f69d22eb43120e9d115c365a54c91ce
2,266
hpp
C++
CookieEngine/include/UI/Widgets/EditorWs/InspectorWidget.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/UI/Widgets/EditorWs/InspectorWidget.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/UI/Widgets/EditorWs/InspectorWidget.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef __INSPECTOR_W_HPP__ #define __INSPECTOR_W_HPP__ #include "UIwidgetBases.hpp" namespace Cookie::Resources { class ResourcesManager; } namespace Cookie::ECS { class Coordinator; class Entity; } namespace Cookie::Core::Math { union Vec2; } namespace Cookie { struct FocusEntity; } namespace reactphysics3d { class Collider; } namespace Cookie::UIwidget { // The inspector gives an immense multitude of options to edit any selected entity to your liking. class Inspector final : public WItemBase { FocusEntity& selectedEntity; Cookie::ECS::Entity* recordedEntity = nullptr; Cookie::Resources::ResourcesManager& resources; Cookie::ECS::Coordinator& coordinator; reactphysics3d::Collider* selectedCollider = nullptr; private: // Starter of the entity analysis. Determines what component it has and allows sub-sections to display, and also allows to add new components. void EntityInspection(); // Basic interface for the Transform: // Allows live editing of the position, rotation, and scale. void TransformInterface(); // Allows live editing of the current model used by the entity, as well as it's texture. void ModelInterface(); /* Advanced interface: - Allows to edit colliders after selected from the display list, - Allows to add/remove colliders, - Provides many options to edit the rigibody/entity as well. Fair warning for your sanity: the interface is very, very long. Refer yourself to the other comments to know where you are inside! */ void PhysicsInterface(); // Allows live/hot-swapping of the scripts in-use by the entity. void ScriptInterface(); // Allows to interface with three inner components corresponding to the entity's health and armor, movement capacities and attack abilities. void GameplayInterface(); // Gives plenty of options to edit the live sounds inside the game, on entities. void FXInterface(); public: inline Inspector(FocusEntity& _selectedEntity, Cookie::Resources::ResourcesManager& _resources, Cookie::ECS::Coordinator& _coordinator) : WItemBase ("Inspector", false), selectedEntity (_selectedEntity), resources (_resources), coordinator (_coordinator) {} void WindowDisplay() override; }; } #endif
32.84058
144
0.74669
[ "model", "transform" ]
f0b1658961990eb56323e45d6119abaf5ff74003
1,067
hpp
C++
gspan/include/gspan_subgraph_lists.hpp
dtchuink/DFG-Pattern-Generator
a57b46dd3439b316f98e856bbd1841cc1b34bb29
[ "MIT" ]
null
null
null
gspan/include/gspan_subgraph_lists.hpp
dtchuink/DFG-Pattern-Generator
a57b46dd3439b316f98e856bbd1841cc1b34bb29
[ "MIT" ]
null
null
null
gspan/include/gspan_subgraph_lists.hpp
dtchuink/DFG-Pattern-Generator
a57b46dd3439b316f98e856bbd1841cc1b34bb29
[ "MIT" ]
null
null
null
#ifndef GSPAN_SUBGRAPH_LISTS_HPP #define GSPAN_SUBGRAPH_LISTS_HPP #include <list> #include <vector> namespace gspan { template <typename S> class subgraph_lists { public: subgraph_lists() : aut_list_size(0) { } subgraph_lists(const subgraph_lists&) = delete; subgraph_lists& operator=(const subgraph_lists&) = delete; subgraph_lists(subgraph_lists&& rhs) = default; std::list<S> all_list; std::list<std::vector<const S*>> aut_list; unsigned int aut_list_size; template <class ... Args> void insert(Args&& ... args); }; template <typename S> template <class ... Args> void subgraph_lists<S>::insert(Args&& ... args) { const S* s = &*all_list.emplace(all_list.begin(), args...); const auto ri_end = aut_list.rend(); for (auto ri = aut_list.rbegin(); ri != ri_end; ++ri) { if (is_automorphic(s, *ri->begin())) { ri->push_back(s); return; } } aut_list.push_back(std::vector<const S*>({s})); ++aut_list_size; } } // namespace gspan #endif
20.921569
63
0.627929
[ "vector" ]
f0b6003fb11b77b5e8bf488ba18dfb2c83a50305
2,484
hh
C++
libs/easylocal-3/include/helpers/outputmanager.hh
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
1
2020-10-25T07:14:48.000Z
2020-10-25T07:14:48.000Z
libs/easylocal-3/include/helpers/outputmanager.hh
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
null
null
null
libs/easylocal-3/include/helpers/outputmanager.hh
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
2
2020-10-02T12:24:38.000Z
2020-10-25T07:00:24.000Z
#pragma once #include <iostream> namespace EasyLocal { namespace Core { /** The Output Manager is responsible for translating between elements of the search space and output solutions. It also delivers other output information of the search, and stores and retrieves solutions from files. This is the only helper that deals with the @c Output class. All other helpers work only on the @c State class, which represents the elements of the search space used by the algorithms. @ingroup Helpers */ template <class Input, class Output, class State> class OutputManager { public: /** Transforms the given state in an output object. @param st the state to transform @param out the corresponding output object. */ virtual void OutputState(const State &st, Output &out) const = 0; /** Transforms an output object in a state object. @param st the resulting state @param out the output object to transform */ virtual void InputState(State &st, const Output &out) const = 0; /** Reads a state from an input stream. @param st the state to be read @param is the input stream */ virtual void ReadState(State &st, std::istream &is) const; /** Writes a state on an output stream. @param st the state to be written, @param os the output stream */ virtual void WriteState(const State &st, std::ostream &os) const; virtual void PrettyPrintOutput(const State &st, const std::string &file_name) const { std::cout << "Sorry, not implemented yet" << std::endl; } protected: /** Constructs an output manager by providing it an input object. @param in a pointer to an input object */ OutputManager(const Input &i, std::string e_name) : in(i), name(e_name) { } virtual ~OutputManager() {} /** A reference to the input. */ const Input &in; /** Name of the output manager. */ const std::string name; }; /** IMPLEMENTATION */ template <class Input, class Output, class State> void OutputManager<Input, Output, State>::ReadState(State &st, std::istream &is) const { Output out(in); is >> out; InputState(st, out); } template <class Input, class Output, class State> void OutputManager<Input, Output, State>::WriteState(const State &st, std::ostream &os) const { Output out(in); OutputState(st, out); os << out; } } // namespace Core } // namespace EasyLocal
31.05
403
0.666667
[ "object", "transform" ]
f0be49c01e02cbc95b11ca2f77fe7d24b5c667f9
2,291
cpp
C++
libs/gui/color_picker.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
libs/gui/color_picker.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
libs/gui/color_picker.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #include "color_picker.h" #include <draw/color_wheel.h> #include <draw/object.h> /* namespace { constexpr double PI = 3.14159265358979323846; } */ //////////////////////////////////////// namespace gui { //////////////////////////////////////// color_picker::color_picker( void ) : _current( { 1, 0, 0, 1 } ) { set_minimum( 120, 120 ); } //////////////////////////////////////// namespace {} void color_picker::paint( const std::shared_ptr<draw::canvas> &canvas ) { draw::color_wheel wheel; wheel.create( canvas, center(), radius() * 0.95 ); wheel.draw( *canvas ); // Draw the background and sample base::gradient grad; grad.add_stop( 0.0, _current ); grad.add_stop( 0.6666, _current ); grad.add_stop( 0.6666, base::white ); grad.add_stop( 1.0, base::white ); base::path path; path.circle( center(), radius() * 0.75 ); base::paint paint; paint.set_fill_radial( center(), radius() * 0.75, grad ); draw::object obj; obj.create( canvas, path, paint ); obj.draw( *canvas ); } //////////////////////////////////////// bool color_picker::mouse_press( const point &p, int b ) { if ( b == 1 ) { coord_type r = point::distance( p, center() ) / radius(); if ( r > 0.70 && r < 0.95 ) { _tracking = true; point d = p.delta( center() ); coord_type h = std::atan2( d.y(), d.x() ); _current.set_hsl( h, 1.0, 0.5 ); return mouse_move( p ); } } return widget::mouse_press( p, b ); } //////////////////////////////////////// bool color_picker::mouse_release( const point &p, int b ) { if ( _tracking && b == 1 ) { _tracking = false; return true; } return widget::mouse_release( p, b ); } //////////////////////////////////////// bool color_picker::mouse_move( const point &p ) { if ( _tracking ) { point d = p.delta( center() ); coord_type h = std::atan2( d.y(), d.x() ); _current.set_hsl( h, 1.0, 0.5 ); invalidate(); return true; } return widget::mouse_move( p ); } //////////////////////////////////////// } // namespace gui
21.411215
71
0.492798
[ "object" ]
f0c02524210a034d2cfa89f587b24a9ae0af8139
422
cpp
C++
testDictionary.cpp
joanaferreira0011/cross-words
ed27f12768cf5cfe312973822ddb5116ae8840bb
[ "MIT" ]
null
null
null
testDictionary.cpp
joanaferreira0011/cross-words
ed27f12768cf5cfe312973822ddb5116ae8840bb
[ "MIT" ]
null
null
null
testDictionary.cpp
joanaferreira0011/cross-words
ed27f12768cf5cfe312973822ddb5116ae8840bb
[ "MIT" ]
null
null
null
/* ------------------ Dictionary Test Zone ------------------ */ #include "dictionary.h" #include "board.h" #include <iostream> #include <vector> #include <map> #include <string> #include <algorithm> #include <fstream> #include <sstream> using namespace std; int main() { string filename; string word; cin >> filename; Dictionary d1(filename); //Dictionary d1; //cin >> word; //d1.validword(word); }
12.411765
59
0.609005
[ "vector" ]
f0cdd70c640ec77cbfd986692fc53da79c7b60d8
6,004
cpp
C++
src/eepp/window/backend/SFML/cwindowsfml.cpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/window/backend/SFML/cwindowsfml.cpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/window/backend/SFML/cwindowsfml.cpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#include <eepp/window/backend/SFML/cwindowsfml.hpp> #ifdef EE_BACKEND_SFML_ACTIVE #if defined( EE_X11_PLATFORM ) #include <X11/Xlib.h> #endif #undef None #include <SFML/Graphics.hpp> #include <eepp/window/backend/SFML/cclipboardsfml.hpp> #include <eepp/window/backend/SFML/cinputsfml.hpp> #include <eepp/window/backend/SFML/ccursormanagersfml.hpp> #include <eepp/window/platform/platformimpl.hpp> #include <eepp/graphics/renderer/cgl.hpp> namespace EE { namespace Window { namespace Backend { namespace SFML { cWindowSFML::cWindowSFML( WindowSettings Settings, ContextSettings Context ) : cWindow( Settings, Context, eeNew( cClipboardSFML, ( this ) ), eeNew( cInputSFML, ( this ) ), eeNew( cCursorManagerSFML, ( this ) ) ), mWinHandler( 0 ), mVisible( false ) { Create( Settings, Context ); } cWindowSFML::~cWindowSFML() { } bool cWindowSFML::Create( WindowSettings Settings, ContextSettings Context ) { if ( mWindow.Created ) return false; sf::VideoMode mode = sf::VideoMode::getDesktopMode(); mWindow.WindowConfig = Settings; mWindow.ContextConfig = Context; mWindow.DesktopResolution = eeSize( mode.width, mode.height ); if ( mWindow.WindowConfig.Style & WindowStyle::Titlebar ) mWindow.Flags |= sf::Style::Titlebar; if ( mWindow.WindowConfig.Style & WindowStyle::Resize ) mWindow.Flags |= sf::Style::Resize; if ( mWindow.WindowConfig.Style & WindowStyle::NoBorder ) mWindow.Flags = sf::Style::None; if ( mWindow.WindowConfig.Style & WindowStyle::UseDesktopResolution ) { mWindow.WindowConfig.Width = mode.width; mWindow.WindowConfig.Height = mode.height; } Uint32 TmpFlags = mWindow.Flags; if ( mWindow.WindowConfig.Style & WindowStyle::Fullscreen ) TmpFlags |= sf::Style::Fullscreen; mSFMLWindow.create( sf::VideoMode( Settings.Width, Settings.Height, Settings.BitsPerPixel ), mWindow.WindowConfig.Caption, TmpFlags, sf::ContextSettings( Context.DepthBufferSize, Context.StencilBufferSize ) ); mSFMLWindow.setVerticalSyncEnabled( Context.VSync ); if ( NULL == cGL::ExistsSingleton() ) { cGL::CreateSingleton( mWindow.ContextConfig.Version ); cGL::instance()->Init(); } CreatePlatform(); GetMainContext(); CreateView(); Setup2D(); mWindow.Created = true; mVisible = true; if ( "" != mWindow.WindowConfig.Icon ) { Icon( mWindow.WindowConfig.Icon ); } /// Init the clipboard after the window creation reinterpret_cast<cClipboardSFML*> ( mClipboard )->Init(); /// Init the input after the window creation reinterpret_cast<cInputSFML*> ( mInput )->Init(); LogSuccessfulInit( GetVersion() ); return true; } std::string cWindowSFML::GetVersion() { return std::string( "SFML 2" ); } void cWindowSFML::CreatePlatform() { #if defined( EE_X11_PLATFORM ) if ( 0 != GetWindowHandler() ) { mPlatform = eeNew( Platform::cX11Impl, ( this, GetWindowHandler(), mSFMLWindow.getSystemHandle(), mSFMLWindow.getSystemHandle(), NULL, NULL ) ); } else { cWindow::CreatePlatform(); } #elif EE_PLATFORM == EE_PLATFORM_WIN mPlatform = eeNew( Platform::cWinImpl, ( this, GetWindowHandler() ) ); #elif EE_PLATFORM == EE_PLATFORM_MACOSX mPlatform = eeNew( Platform::cOSXImpl, ( this ) ); #else cWindow::CreatePlatform(); #endif } void cWindowSFML::ToggleFullscreen() { } void cWindowSFML::Caption( const std::string& Caption ) { mWindow.WindowConfig.Caption = Caption; mSFMLWindow.setTitle( Caption ); } bool cWindowSFML::Icon( const std::string& Path ) { mWindow.WindowConfig.Icon = Path; cImage Img( Path ); mSFMLWindow.setIcon( Img.Width(), Img.Height(), Img.GetPixelsPtr() ); return true; } void cWindowSFML::Hide() { mSFMLWindow.setVisible( false ); mVisible = false; } void cWindowSFML::Show() { mSFMLWindow.setVisible( true ); mVisible = true; } void cWindowSFML::Position( Int16 Left, Int16 Top ) { mSFMLWindow.setPosition( sf::Vector2i( Left, Top ) ); } bool cWindowSFML::Active() { return reinterpret_cast<cInputSFML*> ( mInput )->mWinActive; } bool cWindowSFML::Visible() { return mVisible; } eeVector2i cWindowSFML::Position() { sf::Vector2i v( mSFMLWindow.getPosition() ); return eeVector2i( v.x, v.y ); } void cWindowSFML::Size( Uint32 Width, Uint32 Height, bool Windowed ) { if ( ( !Width || !Height ) ) { Width = mWindow.DesktopResolution.Width(); Height = mWindow.DesktopResolution.Height(); } if ( this->Windowed() == Windowed && Width == mWindow.WindowConfig.Width && Height == mWindow.WindowConfig.Height ) return; sf::Vector2u v( Width, Height ); mSFMLWindow.setSize( v ); } void cWindowSFML::VideoResize( Uint32 Width, Uint32 Height ) { mWindow.WindowConfig.Width = Width; mWindow.WindowConfig.Height = Height; mDefaultView.SetView( 0, 0, Width, Height ); Setup2D(); mCursorManager->Reload(); SendVideoResizeCb(); } void cWindowSFML::SwapBuffers() { mSFMLWindow.display(); } std::vector<DisplayMode> cWindowSFML::GetDisplayModes() const { std::vector<DisplayMode> result; std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes(); for (std::size_t i = 0; i < modes.size(); ++i) { sf::VideoMode mode = modes[i]; result.push_back( DisplayMode( mode.width, mode.height, 60, x ) ); } return result; } void cWindowSFML::SetGamma( eeFloat Red, eeFloat Green, eeFloat Blue ) { } eeWindowContex cWindowSFML::GetContext() const { return 0; } void cWindowSFML::GetMainContext() { } eeWindowHandle cWindowSFML::GetWindowHandler() { #if defined( EE_X11_PLATFORM ) if ( 0 == mWinHandler ) { #ifdef EE_SUPPORT_EXCEPTIONS try { #endif mWinHandler = XOpenDisplay( NULL ); #ifdef EE_SUPPORT_EXCEPTIONS } catch (...) { mWinHandler = 0; } #endif } return mWinHandler; #elif EE_PLATFORM == EE_PLATFORM_WIN return (eeWindowHandle)mSFMLWindow.getSystemHandle(); #elif EE_PLATFORM == EE_PLATFORM_MACOSX return (eeWindowHandle)mSFMLWindow.getSystemHandle(); #else return 0; #endif } void cWindowSFML::SetDefaultContext() { } sf::Window * cWindowSFML::GetSFMLWindow() { return &mSFMLWindow; } }}}} #endif
24.016
210
0.720353
[ "vector" ]
f0d3da8ec966c21f1ac0f381be1d822e0aef1171
646
cpp
C++
Leetcode1691.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
1
2020-06-28T06:29:05.000Z
2020-06-28T06:29:05.000Z
Leetcode1691.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
Leetcode1691.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
class Solution { public: int maxHeight(vector<vector<int>>& cuboids) { for (auto& x: cuboids) sort(x.begin(), x.end()); sort(cuboids.begin(), cuboids.end()); int ans = 0, n = cuboids.size(); vector<int> f(n); for (int i = 0; i < n; i++) { f[i] = cuboids[i][2]; for (int j = 0; j < i; j++) { if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { f[i] = max(f[i], f[j] + cuboids[i][2]); } } ans = max(ans, f[i]); } return ans; } };
32.3
121
0.410217
[ "vector" ]
f0dd475eee8a33de375167a68c1b523771fa8ad5
497
cpp
C++
leetcode/1. Two-sum.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
1
2018-09-13T12:16:42.000Z
2018-09-13T12:16:42.000Z
leetcode/1. Two-sum.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
leetcode/1. Two-sum.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> m; vector<int> answer; for(int i = 0; i < nums.size(); i++) { int other = target - nums[i]; if(m.find(other) != m.end()) { answer.push_back(m.find(other)->second); answer.push_back(i); } m[nums[i]] = i; } return answer; } };
24.85
56
0.402414
[ "vector" ]
f0ed9ab3fa2b9ed1aebc7d2574e88ed6ddff313c
3,109
cpp
C++
NodeJSAddon/HomeKitAmpAddon.cpp
aronisch/HomeKitAmp
169ed1aae44a41dc17de55250ad69cf35b3e64ec
[ "MIT" ]
null
null
null
NodeJSAddon/HomeKitAmpAddon.cpp
aronisch/HomeKitAmp
169ed1aae44a41dc17de55250ad69cf35b3e64ec
[ "MIT" ]
null
null
null
NodeJSAddon/HomeKitAmpAddon.cpp
aronisch/HomeKitAmp
169ed1aae44a41dc17de55250ad69cf35b3e64ec
[ "MIT" ]
null
null
null
#include <cstdlib> #include <RF24/RF24.h> #include <RF24Network/RF24Network.h> #include <iostream> #include <ctime> #include <stdio.h> #include <time.h> #include "streaming-worker.h" using namespace std; // Address of our node in Octal format (01,021, etc) const uint16_t amp_node = 01; const uint16_t rpi_node = 00; typedef enum { NONE, POWER_UP, POWER_DOWN, UPDATE_STATE }Action; typedef struct { // Structure of our request Action actionReq; // 'I' => POWER_ON - 'O' => POWER_DOWN - 'S' => UPDATE_STATE } request_t; typedef struct { //Structure of our answer char currentState; // ON => 'I', OFF => 'O' uint16_t delay; //delay in s unsigned long time; } answer_t; class HomeKitAmp : public StreamingWorker { public: HomeKitAmp(Callback *data, Callback *complete, Callback *error_callback, v8::Local<v8::Object> & options) : StreamingWorker(data, complete, error_callback) {} void Execute(const AsyncProgressWorker::ExecutionProgress& progress) { // Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 8Mhz RF24 radio(RPI_V2_GPIO_P1_22, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_8MHZ); RF24Network network(radio); radio.begin(); delay(5); network.begin(/*channel*/ 90, /*node address*/ rpi_node); radio.printDetails(); while (!closed()) { network.update(); while (network.available()) { // Check for incoming radio data RF24NetworkHeader header; answer_t answer; network.read(header, &answer, sizeof(answer)); printf("Received answer with status : "); printf("Status : %c, delay : %d ms\n", answer.currentState, answer.delay); Message tosendStatus("status", std::to_string(answer.currentState)); Message tosendDelay("delay", std::to_string(answer.delay)); writeToNode(progress, tosendStatus); writeToNode(progress, tosendDelay); } Message m = fromNode.read(); if (m.name == "Instructions") { request_t newReq; RF24NetworkHeader header(/*to node*/ amp_node); char instruction = m.data[0]; bool sent = false; int attempt = 0; switch (instruction) { case 'I': newReq = { POWER_UP }; while (!sent && attempt <= 10) { sent = network.write(header, &newReq, sizeof(newReq)); printf("Failed to send\n"); } printf("Successfully sent\n"); break; case 'O': newReq = { POWER_DOWN }; while (!sent && attempt <= 10) { sent = network.write(header, &newReq, sizeof(newReq)); printf("Failed to send\n"); } printf("Successfully sent\n"); break; case 'S': newReq = { UPDATE_STATE }; while (!sent && attempt <= 10) { sent = network.write(header, &newReq, sizeof(newReq)); printf("Failed to send\n"); } printf("Successfully sent\n"); break; default: break; } } } } }; StreamingWorker * create_worker(Callback *data , Callback *complete , Callback *error_callback, v8::Local<v8::Object> & options) { return new HomeKitAmp(data, complete, error_callback, options); } NODE_MODULE(HomeKitAmp, StreamWorkerWrapper::Init)
30.480392
106
0.651978
[ "object" ]
e7d089192514ecf8b35f76a87c205028cfed2a3f
3,801
hpp
C++
include/codegen/include/System/Collections/Generic/Comparer_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Collections/Generic/Comparer_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Collections/Generic/Comparer_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:52 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Collections.Generic.IComparer`1 #include "System/Collections/Generic/IComparer_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: System.Collections.Generic namespace System::Collections::Generic { // Autogenerated type: System.Collections.Generic.Comparer`1 template<typename T> class Comparer_1 : public ::Il2CppObject, public System::Collections::IComparer, public System::Collections::Generic::IComparer_1<T> { public: // Autogenerated static field getter // Get static field: static private System.Collections.Generic.Comparer`1<T> defaultComparer static System::Collections::Generic::Comparer_1<T>* _get_defaultComparer() { return CRASH_UNLESS((il2cpp_utils::GetFieldValue<System::Collections::Generic::Comparer_1<T>*>(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Comparer_1<T>*>::get(), "defaultComparer"))); } // Autogenerated static field setter // Set static field: static private System.Collections.Generic.Comparer`1<T> defaultComparer static void _set_defaultComparer(System::Collections::Generic::Comparer_1<T>* value) { CRASH_UNLESS(il2cpp_utils::SetFieldValue(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Comparer_1<T>*>::get(), "defaultComparer", value)); } // static public System.Collections.Generic.Comparer`1<T> get_Default() // Offset: 0x176F3D8 static System::Collections::Generic::Comparer_1<T>* get_Default() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::Comparer_1<T>*>(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Comparer_1<T>*>::get(), "get_Default")); } // static private System.Collections.Generic.Comparer`1<T> CreateComparer() // Offset: 0x1768CC8 static System::Collections::Generic::Comparer_1<T>* CreateComparer() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::Comparer_1<T>*>(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Comparer_1<T>*>::get(), "CreateComparer")); } // public System.Int32 Compare(T x, T y) // Offset: 0xFFFFFFFF // Implemented from: System.Collections.Generic.IComparer`1 // Base method: System.Int32 IComparer`1::Compare(T x, T y) int Compare(T x, T y) { return CRASH_UNLESS(il2cpp_utils::RunMethod<int>(this, "Compare", x, y)); } // private System.Int32 System.Collections.IComparer.Compare(System.Object x, System.Object y) // Offset: 0x17690C0 // Implemented from: System.Collections.IComparer // Base method: System.Int32 IComparer::Compare(System.Object x, System.Object y) int System_Collections_IComparer_Compare(::Il2CppObject* x, ::Il2CppObject* y) { return CRASH_UNLESS(il2cpp_utils::RunMethod<int>(this, "System.Collections.IComparer.Compare", x, y)); } // protected System.Void .ctor() // Offset: 0x176926C // Implemented from: System.Object // Base method: System.Void Object::.ctor() static Comparer_1<T>* New_ctor() { return (Comparer_1<T>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Comparer_1<T>*>::get())); } }; // System.Collections.Generic.Comparer`1 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::Collections::Generic::Comparer_1, "System.Collections.Generic", "Comparer`1"); #pragma pack(pop)
55.086957
199
0.726914
[ "object" ]
e7d87707900ef17f96cc51ce03a84684483acdd7
46,338
cpp
C++
src/mongo/db/pipeline/document_source_merge_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document_source_merge_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document_source_merge_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include <boost/intrusive_ptr.hpp> #include "mongo/db/exec/document_value/document.h" #include "mongo/db/exec/document_value/document_value_test_util.h" #include "mongo/db/pipeline/aggregation_context_fixture.h" #include "mongo/db/pipeline/document_source_merge.h" #include "mongo/db/pipeline/process_interface/non_shardsvr_process_interface.h" namespace mongo { namespace { using boost::intrusive_ptr; constexpr StringData kWhenMatchedModeFieldName = DocumentSourceMergeSpec::kWhenMatchedFieldName; constexpr StringData kWhenNotMatchedModeFieldName = DocumentSourceMergeSpec::kWhenNotMatchedFieldName; constexpr StringData kIntoFieldName = DocumentSourceMergeSpec::kTargetNssFieldName; constexpr StringData kOnFieldName = DocumentSourceMergeSpec::kOnFieldName; const StringData kDefaultWhenMatchedMode = MergeWhenMatchedMode_serializer(MergeWhenMatchedModeEnum::kMerge); const StringData kDefaultWhenNotMatchedMode = MergeWhenNotMatchedMode_serializer(MergeWhenNotMatchedModeEnum::kInsert); /** * For the purpsoses of this test, assume every collection is unsharded. Stages may ask this during * setup. For example, to compute its constraints, the $merge stage needs to know if the output * collection is sharded. */ class MongoProcessInterfaceForTest : public StubMongoProcessInterface { public: bool isSharded(OperationContext* opCtx, const NamespaceString& ns) override { return false; } /** * For the purposes of these tests, assume each collection is unsharded and has a document key * of just "_id". */ std::vector<FieldPath> collectDocumentKeyFieldsActingAsRouter( OperationContext* opCtx, const NamespaceString& nss) const override { return {"_id"}; } void checkRoutingInfoEpochOrThrow(const boost::intrusive_ptr<ExpressionContext>& expCtx, const NamespaceString&, ChunkVersion) const override { return; // Assume it always matches for our tests here. } }; class DocumentSourceMergeTest : public AggregationContextFixture { public: DocumentSourceMergeTest() : AggregationContextFixture() { getExpCtx()->mongoProcessInterface = std::make_shared<MongoProcessInterfaceForTest>(); } intrusive_ptr<DocumentSourceMerge> createMergeStage(BSONObj spec) { auto specElem = spec.firstElement(); intrusive_ptr<DocumentSourceMerge> mergeStage = dynamic_cast<DocumentSourceMerge*>( DocumentSourceMerge::createFromBson(specElem, getExpCtx()).get()); ASSERT_TRUE(mergeStage); return mergeStage; } }; TEST_F(DocumentSourceMergeTest, CorrectlyParsesIfMergeSpecIsString) { const auto& defaultDb = getExpCtx()->ns.db(); const auto& targetColl = "target_collection"; auto spec = BSON("$merge" << targetColl); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); ASSERT_EQ(mergeStage->getOutputNs().db(), defaultDb); ASSERT_EQ(mergeStage->getOutputNs().coll(), targetColl); } TEST_F(DocumentSourceMergeTest, CorrectlyParsesIfIntoIsString) { const auto& defaultDb = getExpCtx()->ns.db(); const auto& targetColl = "target_collection"; auto spec = BSON("$merge" << BSON("into" << targetColl)); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); ASSERT_EQ(mergeStage->getOutputNs().db(), defaultDb); ASSERT_EQ(mergeStage->getOutputNs().coll(), targetColl); } TEST_F(DocumentSourceMergeTest, CorrectlyParsesIfIntoIsObject) { const auto& defaultDb = getExpCtx()->ns.db(); const auto& targetDb = "target_db"; const auto& targetColl = "target_collection"; auto spec = BSON("$merge" << BSON("into" << BSON("coll" << targetColl))); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); ASSERT_EQ(mergeStage->getOutputNs().db(), defaultDb); ASSERT_EQ(mergeStage->getOutputNs().coll(), targetColl); spec = BSON("$merge" << BSON("into" << BSON("db" << targetDb << "coll" << targetColl))); mergeStage = createMergeStage(spec); ASSERT(mergeStage); ASSERT_EQ(mergeStage->getOutputNs().db(), targetDb); ASSERT_EQ(mergeStage->getOutputNs().coll(), targetColl); } TEST_F(DocumentSourceMergeTest, CorrectlyParsesIfWhenMatchedIsStringOrArray) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "merge")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSONArray())); ASSERT(createMergeStage(spec)); } TEST_F(DocumentSourceMergeTest, CorrectlyParsesIfTargetAndAggregationNamespacesAreSame) { const auto targetNsSameAsAggregationNs = getExpCtx()->ns; const auto targetColl = targetNsSameAsAggregationNs.coll(); const auto targetDb = targetNsSameAsAggregationNs.db(); auto spec = BSON("$merge" << BSON("into" << BSON("coll" << targetColl << "db" << targetDb))); ASSERT(createMergeStage(spec)); } TEST_F(DocumentSourceMergeTest, FailsToParseIncorrectMergeSpecType) { auto spec = BSON("$merge" << 1); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51182); spec = BSON("$merge" << BSONArray()); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51182); } TEST_F(DocumentSourceMergeTest, FailsToParseIfMergeSpecObjectWithoutInto) { auto spec = BSON("$merge" << BSONObj()); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 40414); spec = BSON("$merge" << BSON("whenMatched" << "replace")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 40414); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsNotStringAndNotObject) { auto spec = BSON("$merge" << BSON("into" << 1)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51178); spec = BSON("$merge" << BSON("into" << BSON_ARRAY(1 << 2))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51178); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsNullish) { auto spec = BSON("$merge" << BSON("into" << BSONNULL)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51178); spec = BSON("$merge" << BSON("into" << BSONUndefined)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51178); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsAnEmptyString) { auto spec = BSON("$merge" << BSON("into" << "")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786800); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithInvalidFields) { auto spec = BSON("$merge" << BSON("into" << BSON("a" << "b"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 40415); spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection" << "a" << "b"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 40415); spec = BSON("$merge" << BSON("into" << BSON("db" << "target_db" << "a" << "b"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 40415); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithEmptyCollectionName) { auto spec = BSON("$merge" << BSON("into" << BSON("coll" << ""))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); spec = BSON("$merge" << BSON("into" << BSONObj())); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithNullishCollection) { auto spec = BSON("$merge" << BSON("into" << BSON("coll" << BSONNULL))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); spec = BSON("$merge" << BSON("into" << BSON("coll" << BSONUndefined))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsNotAValidUserCollection) { auto spec = BSON("$merge" << ".test."); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::InvalidNamespace); spec = BSON("$merge" << BSON("into" << ".test.")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::InvalidNamespace); spec = BSON("$merge" << BSON("into" << BSON("coll" << ".test."))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::InvalidNamespace); } TEST_F(DocumentSourceMergeTest, FailsToParseIfDbIsNotString) { auto spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection" << "db" << true))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection" << "db" << BSONArray()))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection" << "db" << BSON("" << "test")))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); } TEST_F(DocumentSourceMergeTest, FailsToParseIfCollIsNotString) { auto spec = BSON("$merge" << BSON("into" << BSON("db" << "target_db" << "coll" << true))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << BSON("db" << "target_db" << "coll" << BSONArray()))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << BSON("db" << "target_db" << "coll" << BSON("" << "test")))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); } TEST_F(DocumentSourceMergeTest, FailsToParseIfDbIsNotAValidDatabaseName) { auto spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection" << "db" << ".test"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::InvalidNamespace); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithDbSpecifiedAndNoColl) { auto targetDb = "target_db"; auto spec = BSON("$merge" << BSON("into" << BSON("db" << targetDb))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithDbSpecifiedAndEmptyColl) { auto targetDb = "target_db"; auto spec = BSON("$merge" << BSON("into" << BSON("coll" << "" << "db" << targetDb))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); } TEST_F(DocumentSourceMergeTest, FailsToParseIfIntoIsObjectWithDbSpecifiedAndNullishColl) { auto targetDb = "target_db"; auto spec = BSON("$merge" << BSON("into" << BSON("coll" << BSONNULL << "db" << targetDb))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); spec = BSON("$merge" << BSON("into" << BSON("coll" << BSONUndefined << "db" << targetDb))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 5786801); } TEST_F(DocumentSourceMergeTest, FailsToParseIfWhenMatchedModeIsNotStringOrArray) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << true)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51191); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << 100)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51191); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSON("" << kDefaultWhenMatchedMode))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51191); } TEST_F(DocumentSourceMergeTest, FailsToParseIfWhenNotMatchedModeIsNotString) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenNotMatched" << true)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenNotMatched" << BSONArray())); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenNotMatched" << BSON("" << kDefaultWhenNotMatchedMode))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); } TEST_F(DocumentSourceMergeTest, FailsToParseIfWhenMatchedModeIsUnsupportedString) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "unsupported")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); } TEST_F(DocumentSourceMergeTest, FailsToParseIfWhenNotMatchedModeIsUnsupportedString) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenNotMatched" << "unsupported")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenNotMatched" << "merge")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); } TEST_F(DocumentSourceMergeTest, FailsToParseIfOnFieldIsNotStringOrArrayOfStrings) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << 1)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51186); spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSONArray())); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51187); spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON_ARRAY(1 << 2 << BSON("a" << 3)))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51134); spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON("_id" << 1))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51186); } TEST_F(DocumentSourceMergeTest, CorrectlyUsesTargetDbThatMatchesAggregationDb) { const auto targetDbSameAsAggregationDb = getExpCtx()->ns.db(); const auto targetColl = "target_collection"; auto spec = BSON("$merge" << BSON("into" << BSON("coll" << targetColl << "db" << targetDbSameAsAggregationDb))); auto mergeStage = createMergeStage(spec); ASSERT_EQ(mergeStage->getOutputNs().db(), targetDbSameAsAggregationDb); ASSERT_EQ(mergeStage->getOutputNs().coll(), targetColl); } TEST_F(DocumentSourceMergeTest, SerializeDefaultModesWhenMatchedWhenNotMatched) { auto spec = BSON("$out" << BSON("into" << "target_collection")); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kWhenMatchedModeFieldName].getStringData(), kDefaultWhenMatchedMode); ASSERT_EQ(serialized["$merge"][kWhenNotMatchedModeFieldName].getStringData(), kDefaultWhenNotMatchedMode); // Make sure we can reparse the serialized BSON. auto reparsedMergeStage = createMergeStage(serialized.toBson()); auto reSerialized = reparsedMergeStage->serialize().getDocument(); ASSERT_EQ(reSerialized["$merge"][kWhenMatchedModeFieldName].getStringData(), kDefaultWhenMatchedMode); ASSERT_EQ(reSerialized["$merge"][kWhenNotMatchedModeFieldName].getStringData(), kDefaultWhenNotMatchedMode); } TEST_F(DocumentSourceMergeTest, SerializeOnFieldDefaultsToId) { auto spec = BSON("$merge" << BSON("into" << "target_collection")); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kOnFieldName].getStringData(), "_id"); } TEST_F(DocumentSourceMergeTest, SerializeCompoundOnFields) { auto spec = BSON("$out" << BSON("into" << "target_collection" << "on" << BSON_ARRAY("_id" << "shardKey"))); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); auto on = serialized["$merge"][kOnFieldName].getArray(); ASSERT_EQ(on.size(), 2UL); auto comparator = ValueComparator(); ASSERT_TRUE(comparator.evaluate(on[0] == Value(std::string("_id")))); ASSERT_TRUE(comparator.evaluate(on[1] == Value(std::string("shardKey")))); } TEST_F(DocumentSourceMergeTest, SerializeDottedPathOnFields) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON_ARRAY("_id" << "a.b"))); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); auto on = serialized["$merge"][kOnFieldName].getArray(); ASSERT_EQ(on.size(), 2UL); auto comparator = ValueComparator(); ASSERT_TRUE(comparator.evaluate(on[0] == Value(std::string("_id")))); ASSERT_TRUE(comparator.evaluate(on[1] == Value(std::string("a.b")))); spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << "_id.a")); mergeStage = createMergeStage(spec); serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kOnFieldName].getStringData(), "_id.a"); } TEST_F(DocumentSourceMergeTest, SerializeDottedPathOnFieldsSharedPrefix) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON_ARRAY("_id" << "a.b" << "a.c"))); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); auto on = serialized["$merge"][kOnFieldName].getArray(); ASSERT_EQ(on.size(), 3UL); auto comparator = ValueComparator(); ASSERT_TRUE(comparator.evaluate(on[0] == Value(std::string("_id")))); ASSERT_TRUE(comparator.evaluate(on[1] == Value(std::string("a.b")))); ASSERT_TRUE(comparator.evaluate(on[2] == Value(std::string("a.c")))); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenMergeSpecIsStringNotDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << "target_collection"); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "target_collection"); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenMergeSpecIsStringDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << "my.target_collection"); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "my.target_collection"); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenIntoIsStringNotDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << BSON("into" << "target_collection")); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "target_collection"); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenIntoIsStringDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << BSON("into" << "my.target_collection")); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "my.target_collection"); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenIntoIsObjectWithCollNotDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << BSON("into" << BSON("coll" << "target_collection"))); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "target_collection"); } TEST_F(DocumentSourceMergeTest, SerializeIntoWhenIntoIsObjectWithCollDotted) { const auto aggregationDb = getExpCtx()->ns.db(); auto spec = BSON("$merge" << BSON("into" << BSON("coll" << "my.target_collection"))); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["db"].getStringData(), aggregationDb); ASSERT_EQ(serialized["$merge"][kIntoFieldName]["coll"].getStringData(), "my.target_collection"); } TEST_F(DocumentSourceMergeTest, CorrectlyHandlesWhenMatchedAndWhenNotMatchedModes) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "replace" << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "replace" << "whenNotMatched" << "fail")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "replace" << "whenNotMatched" << "discard")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "fail" << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "fail" << "whenNotMatched" << "fail")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51189); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "fail" << "whenNotMatched" << "discard")); ASSERT_THROWS_CODE(createMergeStage(spec), DBException, 51189); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "merge" << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "merge" << "whenNotMatched" << "fail")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "merge" << "whenNotMatched" << "discard")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "keepExisting" << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "keepExisting" << "whenNotMatched" << "fail")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51189); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "keepExisting" << "whenNotMatched" << "discard")); ASSERT_THROWS_CODE(createMergeStage(spec), DBException, 51189); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "fail")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "discard")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "pipeline" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << "[{$addFields: {x: 1}}]" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::BadValue); } TEST_F(DocumentSourceMergeTest, LetVariablesCanOnlyBeUsedWithPipelineMode) { auto let = BSON("foo" << "bar"); auto spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "insert")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "fail")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << "discard")); ASSERT(createMergeStage(spec)); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "replace" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "replace" << "whenNotMatched" << "fail")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "replace" << "whenNotMatched" << "discard")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "merge" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "merge" << "whenNotMatched" << "fail")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "merge" << "whenNotMatched" << "discard")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "keepExisting" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << let << "whenMatched" << "fail" << "whenNotMatched" << "insert")); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 51199); } // We always serialize the default let variables as {new: "$$ROOT"} if omitted. TEST_F(DocumentSourceMergeTest, SerializeDefaultLetVariable) { for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "whenMatched" << BSON_ARRAY(BSON("$project" << BSON("x" << 1))) << "whenNotMatched" << whenNotMatched)); auto mergeStage = createMergeStage(spec); auto serialized = mergeStage->serialize().getDocument(); ASSERT_VALUE_EQ(serialized["$merge"]["let"], Value(BSON("new" << "$$ROOT"))); } } // Test the behaviour of 'let' serialization for each whenNotMatched mode. TEST_F(DocumentSourceMergeTest, SerializeLetVariables) { auto pipeline = BSON_ARRAY(BSON("$project" << BSON("x" << "$$v1" << "y" << "$$v2" << "z" << "$$v3"))); const auto createAndSerializeMergeStage = [this, &pipeline](StringData whenNotMatched) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << BSON("v1" << 10 << "v2" << "foo" << "v3" << BSON("x" << 1 << "y" << BSON("z" << "bar"))) << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); return mergeStage->serialize().getDocument(); }; for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { const auto serialized = createAndSerializeMergeStage(whenNotMatched); // For {whenNotMatched:insert}, we always attach the 'new' document even if the user has // already specified a set of variables. This is because a {whenNotMatched: insert} merge // generates an upsert, and if no documents in the target collection match the query we must // insert the original document. For other 'whenNotMatched' modes, we do not serialize the // new document, since neither 'fail' nor 'discard' can result in an upsert. ASSERT_VALUE_EQ(serialized["$merge"]["let"]["new"], (whenNotMatched == "insert"_sd ? Value("$$ROOT"_sd) : Value())); // The user's variables should be serialized in all cases. ASSERT_VALUE_EQ(serialized["$merge"]["let"]["v1"], Value(BSON("$const" << 10))); ASSERT_VALUE_EQ(serialized["$merge"]["let"]["v2"], Value(BSON("$const" << "foo"))); ASSERT_VALUE_EQ(serialized["$merge"]["let"]["v3"], Value(BSON("x" << BSON("$const" << 1) << "y" << BSON("z" << BSON("$const" << "bar"))))); ASSERT_VALUE_EQ(serialized["$merge"]["whenMatched"], Value(pipeline)); } } TEST_F(DocumentSourceMergeTest, SerializeLetArrayVariable) { for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { auto pipeline = BSON_ARRAY(BSON("$project" << BSON("x" << "$$v1"))); auto spec = BSON( "$merge" << BSON("into" << "target_collection" << "let" << BSON("v1" << BSON_ARRAY(1 << "2" << BSON("x" << 1 << "y" << 2))) << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); auto serialized = mergeStage->serialize().getDocument(); ASSERT_VALUE_EQ( serialized["$merge"]["let"]["v1"], Value(BSON_ARRAY(BSON("$const" << 1) << BSON("$const" << "2") << BSON("x" << BSON("$const" << 1) << "y" << BSON("$const" << 2))))); ASSERT_VALUE_EQ(serialized["$merge"]["whenMatched"], Value(pipeline)); } } // This test verifies that when the 'let' argument is specified as 'null', the default 'new' // variable is still available. This is not a desirable behaviour but rather a limitation in the // IDL parser which cannot differentiate between an optional field specified explicitly as 'null', // or not specified at all. In both cases it will treat the field like it wasn't specified. So, // this test ensures that we're aware of this limitation. Once the limitation is addressed in // SERVER-41272, this test should be updated to accordingly. TEST_F(DocumentSourceMergeTest, SerializeNullLetVariablesAsDefault) { for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { auto pipeline = BSON_ARRAY(BSON("$project" << BSON("x" << "1"))); auto spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << BSONNULL << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); auto serialized = mergeStage->serialize().getDocument(); ASSERT_VALUE_EQ(serialized["$merge"]["let"], Value(BSON("new" << "$$ROOT"))); ASSERT_VALUE_EQ(serialized["$merge"]["whenMatched"], Value(pipeline)); } } TEST_F(DocumentSourceMergeTest, SerializeEmptyLetVariables) { for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { auto pipeline = BSON_ARRAY(BSON("$project" << BSON("x" << "1"))); auto spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << BSONObj() << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); auto mergeStage = createMergeStage(spec); ASSERT(mergeStage); auto serialized = mergeStage->serialize().getDocument(); ASSERT_VALUE_EQ(serialized["$merge"]["let"], (whenNotMatched == "insert"_sd ? Value(BSON("new" << "$$ROOT")) : Value(BSONObj()))); ASSERT_VALUE_EQ(serialized["$merge"]["whenMatched"], Value(pipeline)); } } TEST_F(DocumentSourceMergeTest, OnlyObjectCanBeUsedAsLetVariables) { for (auto&& whenNotMatched : {"insert", "fail", "discard"}) { auto pipeline = BSON_ARRAY(BSON("$project" << BSON("x" << "1"))); auto spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << 1 << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << "foo" << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); spec = BSON("$merge" << BSON("into" << "target_collection" << "let" << BSON_ARRAY(1 << "2") << "whenMatched" << pipeline << "whenNotMatched" << whenNotMatched)); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, ErrorCodes::TypeMismatch); } } TEST_F(DocumentSourceMergeTest, FailsToParseIfOnFieldHaveDuplicates) { auto spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON_ARRAY("x" << "y" << "x"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 31465); spec = BSON("$merge" << BSON("into" << "target_collection" << "on" << BSON_ARRAY("_id" << "_id"))); ASSERT_THROWS_CODE(createMergeStage(spec), AssertionException, 31465); } } // namespace } // namespace mongo
48.521466
100
0.521408
[ "vector" ]
e7eef166ddab93755baaa940252631c66d00b2b3
6,169
cc
C++
tests/cpp/metric/test_rank_metric.cc
GinkoBalboa/xgboost
29bfa94bb6a99721f3ab9e0c4f05ee2df4345294
[ "Apache-2.0" ]
23,866
2015-03-22T05:53:05.000Z
2022-03-31T23:59:37.000Z
tests/cpp/metric/test_rank_metric.cc
Nihilitior/xgboost
7366d3b20cad8e28ecef67d5130c71e81bb0b088
[ "Apache-2.0" ]
6,405
2015-03-22T09:41:16.000Z
2022-03-31T23:28:40.000Z
tests/cpp/metric/test_rank_metric.cc
Nihilitior/xgboost
7366d3b20cad8e28ecef67d5130c71e81bb0b088
[ "Apache-2.0" ]
9,745
2015-03-22T05:25:51.000Z
2022-03-31T09:24:51.000Z
// Copyright by Contributors #include <xgboost/metric.h> #include "../helpers.h" #if !defined(__CUDACC__) TEST(Metric, AMS) { auto tparam = xgboost::CreateEmptyGenericParam(GPUIDX); EXPECT_ANY_THROW(xgboost::Metric::Create("ams", &tparam)); xgboost::Metric * metric = xgboost::Metric::Create("ams@0.5f", &tparam); ASSERT_STREQ(metric->Name(), "ams@0.5"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0.311f, 0.001f); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.29710f, 0.001f); delete metric; metric = xgboost::Metric::Create("ams@0", &tparam); ASSERT_STREQ(metric->Name(), "ams@0"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0.311f, 0.001f); delete metric; } #endif TEST(Metric, DeclareUnifiedTest(Precision)) { // When the limit for precision is not given, it takes the limit at // std::numeric_limits<unsigned>::max(); hence all values are very small // NOTE(AbdealiJK): Maybe this should be fixed to be num_row by default. auto tparam = xgboost::CreateEmptyGenericParam(GPUIDX); xgboost::Metric * metric = xgboost::Metric::Create("pre", &tparam); ASSERT_STREQ(metric->Name(), "pre"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-7); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0, 1e-7); delete metric; metric = xgboost::Metric::Create("pre@2", &tparam); ASSERT_STREQ(metric->Name(), "pre@2"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0.5f, 1e-7); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.5f, 0.001f); EXPECT_ANY_THROW(GetMetricEval(metric, {0, 1}, {})); delete metric; } TEST(Metric, DeclareUnifiedTest(NDCG)) { auto tparam = xgboost::CreateEmptyGenericParam(GPUIDX); xgboost::Metric * metric = xgboost::Metric::Create("ndcg", &tparam); ASSERT_STREQ(metric->Name(), "ndcg"); EXPECT_ANY_THROW(GetMetricEval(metric, {0, 1}, {})); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, {}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.6509f, 0.001f); delete metric; metric = xgboost::Metric::Create("ndcg@2", &tparam); ASSERT_STREQ(metric->Name(), "ndcg@2"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.3868f, 0.001f); delete metric; metric = xgboost::Metric::Create("ndcg@-", &tparam); ASSERT_STREQ(metric->Name(), "ndcg-"); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, {}), 0, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.6509f, 0.001f); delete metric; metric = xgboost::Metric::Create("ndcg-", &tparam); ASSERT_STREQ(metric->Name(), "ndcg-"); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, {}), 0, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.6509f, 0.001f); delete metric; metric = xgboost::Metric::Create("ndcg@2-", &tparam); ASSERT_STREQ(metric->Name(), "ndcg@2-"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.3868f, 0.001f); delete metric; } TEST(Metric, DeclareUnifiedTest(MAP)) { auto tparam = xgboost::CreateEmptyGenericParam(GPUIDX); xgboost::Metric * metric = xgboost::Metric::Create("map", &tparam); ASSERT_STREQ(metric->Name(), "map"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.5f, 0.001f); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, std::vector<xgboost::bst_float>{}), 1, 1e-10); // Rank metric with group info EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.2f, 0.8f, 0.4f, 1.7f}, {2, 7, 1, 0, 5, 0}, // Labels {}, // Weights {0, 2, 5, 6}), // Group info 0.8611f, 0.001f); delete metric; metric = xgboost::Metric::Create("map@-", &tparam); ASSERT_STREQ(metric->Name(), "map-"); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, {}), 0, 1e-10); delete metric; metric = xgboost::Metric::Create("map-", &tparam); ASSERT_STREQ(metric->Name(), "map-"); EXPECT_NEAR(GetMetricEval(metric, xgboost::HostDeviceVector<xgboost::bst_float>{}, {}), 0, 1e-10); delete metric; metric = xgboost::Metric::Create("map@2", &tparam); ASSERT_STREQ(metric->Name(), "map@2"); EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 1, 1e-10); EXPECT_NEAR(GetMetricEval(metric, {0.1f, 0.9f, 0.1f, 0.9f}, { 0, 0, 1, 1}), 0.25f, 0.001f); delete metric; }
39.292994
76
0.524558
[ "vector" ]
e7f711142b7afc3c633fe4eea8a9fe0419dacdf3
60,166
cpp
C++
engine/src/Rendering/Renderer.cpp
aleksigron/kokko
c0517c153029977ac347a7e1da0cb79fd3060d32
[ "MIT" ]
14
2017-10-17T16:20:20.000Z
2021-12-21T14:49:00.000Z
engine/src/Rendering/Renderer.cpp
aleksigron/kokko
c0517c153029977ac347a7e1da0cb79fd3060d32
[ "MIT" ]
null
null
null
engine/src/Rendering/Renderer.cpp
aleksigron/kokko
c0517c153029977ac347a7e1da0cb79fd3060d32
[ "MIT" ]
1
2019-05-12T13:50:23.000Z
2019-05-12T13:50:23.000Z
#include "Rendering/Renderer.hpp" #include <cassert> #include <cstdio> #include <cstring> #include "Core/Core.hpp" #include "Core/Sort.hpp" #include "Debug/Debug.hpp" #include "Debug/DebugVectorRenderer.hpp" #include "Engine/Engine.hpp" #include "Engine/EntityManager.hpp" #include "Graphics/BloomEffect.hpp" #include "Graphics/ScreenSpaceAmbientOcclusion.hpp" #include "Graphics/EnvironmentManager.hpp" #include "Graphics/Scene.hpp" #include "Math/Rectangle.hpp" #include "Math/BoundingBox.hpp" #include "Math/Intersect3D.hpp" #include "Memory/Allocator.hpp" #include "Rendering/CameraParameters.hpp" #include "Rendering/CameraSystem.hpp" #include "Rendering/CascadedShadowMap.hpp" #include "Rendering/Framebuffer.hpp" #include "Rendering/LightManager.hpp" #include "Rendering/PostProcessRenderer.hpp" #include "Rendering/PostProcessRenderPass.hpp" #include "Rendering/RenderCommandData.hpp" #include "Rendering/RenderCommandType.hpp" #include "Rendering/RenderDevice.hpp" #include "Rendering/RenderTargetContainer.hpp" #include "Rendering/RenderViewport.hpp" #include "Rendering/StaticUniformBuffer.hpp" #include "Rendering/Uniform.hpp" #include "Resources/MaterialManager.hpp" #include "Resources/MeshManager.hpp" #include "Resources/MeshPresets.hpp" #include "Resources/ResourceManagers.hpp" #include "Resources/ShaderManager.hpp" #include "Resources/TextureManager.hpp" #include "System/Window.hpp" const RenderObjectId RenderObjectId::Null = RenderObjectId{ 0 }; struct LightingUniformBlock { static constexpr size_t MaxLightCount = 8; static constexpr size_t MaxCascadeCount = 4; UniformBlockArray<Vec3f, MaxLightCount> lightColors; UniformBlockArray<Vec4f, MaxLightCount> lightPositions; // xyz: position, w: inverse square radius UniformBlockArray<Vec4f, MaxLightCount> lightDirections; // xyz: direction, w: spot light angle UniformBlockArray<bool, MaxLightCount> lightCastShadow; UniformBlockArray<Mat4x4f, MaxCascadeCount> shadowMatrices; UniformBlockArray<float, MaxCascadeCount + 1> shadowSplits; alignas(16) Mat4x4f perspectiveMatrix; alignas(16) Mat4x4f viewToWorld; alignas(8) Vec2f halfNearPlane; alignas(8) Vec2f shadowMapScale; alignas(8) Vec2f frameResolution; alignas(4) int directionalLightCount; alignas(4) int pointLightCount; alignas(4) int spotLightCount; alignas(4) int cascadeCount; alignas(4) float shadowBiasOffset; alignas(4) float shadowBiasFactor; alignas(4) float shadowBiasClamp; }; struct SkyboxUniformBlock { alignas(16) Mat4x4f transform; }; struct TonemapUniformBlock { alignas(16) float exposure; }; Renderer::Renderer( Allocator* allocator, RenderDevice* renderDevice, Scene* scene, CameraSystem* cameraSystem, LightManager* lightManager, const ResourceManagers& resourceManagers) : allocator(allocator), device(renderDevice), renderTargetContainer(nullptr), ssao(nullptr), bloomEffect(nullptr), targetFramebufferId(0), viewportData(nullptr), viewportCount(0), viewportIndexFullscreen(0), uniformStagingBuffer(allocator), objectUniformBufferLists{ Array<unsigned int>(allocator) }, currentFrameIndex(0), entityMap(allocator), scene(scene), cameraSystem(cameraSystem), lightManager(lightManager), shaderManager(resourceManagers.shaderManager), meshManager(resourceManagers.meshManager), materialManager(resourceManagers.materialManager), textureManager(resourceManagers.textureManager), environmentManager(resourceManagers.environmentManager), lockCullingCamera(false), commandList(allocator), objectVisibility(allocator), lightResultArray(allocator), customRenderers(allocator), skyboxShaderId(ShaderId::Null), skyboxMeshId(MeshId::Null), skyboxUniformBufferId(0) { KOKKO_PROFILE_FUNCTION(); renderTargetContainer = allocator->MakeNew<RenderTargetContainer>(allocator, renderDevice); postProcessRenderer = allocator->MakeNew<PostProcessRenderer>( renderDevice, meshManager, shaderManager, renderTargetContainer); ssao = allocator->MakeNew<ScreenSpaceAmbientOcclusion>( allocator, renderDevice, shaderManager, postProcessRenderer); bloomEffect = allocator->MakeNew<BloomEffect>( allocator, renderDevice, shaderManager, postProcessRenderer); framebufferShadow.SetRenderDevice(renderDevice); framebufferGbuffer.SetRenderDevice(renderDevice); framebufferLightAcc.SetRenderDevice(renderDevice); fullscreenMesh = MeshId{ 0 }; lightingShaderId = ShaderId{ 0 }; tonemappingShaderId = ShaderId{ 0 }; shadowMaterial = MaterialId{ 0 }; lightingUniformBufferId = 0; tonemapUniformBufferId = 0; brdfLutTextureId = 0; objectUniformBlockStride = 0; objectsPerUniformBuffer = 0; data = InstanceData{}; data.count = 1; // Reserve index 0 as RenderObjectId::Null value this->ReallocateRenderObjects(512); } Renderer::~Renderer() { this->Deinitialize(); allocator->Deallocate(data.buffer); allocator->MakeDelete(bloomEffect); allocator->MakeDelete(ssao); allocator->MakeDelete(postProcessRenderer); allocator->MakeDelete(renderTargetContainer); } void Renderer::Initialize() { KOKKO_PROFILE_FUNCTION(); device->CubemapSeamlessEnable(); device->SetClipBehavior(RenderClipOriginMode::LowerLeft, RenderClipDepthMode::ZeroToOne); int aligment = 0; device->GetIntegerValue(RenderDeviceParameter::UniformBufferOffsetAlignment, &aligment); objectUniformBlockStride = (sizeof(TransformUniformBlock) + aligment - 1) / aligment * aligment; objectsPerUniformBuffer = ObjectUniformBufferSize / objectUniformBlockStride; postProcessRenderer->Initialize(); ssao->Initialize(); bloomEffect->Initialize(); BloomEffect::Params bloomParams; bloomParams.iterationCount = 4; bloomParams.bloomThreshold = 1.2f; bloomParams.bloomSoftThreshold = 0.8f; bloomParams.bloomIntensity = 0.6f; bloomEffect->SetParams(bloomParams); { KOKKO_PROFILE_SCOPE("Allocate viewport data"); // Allocate viewport data storage void* buf = allocator->Allocate(sizeof(RenderViewport) * MaxViewportCount, "Renderer::viewportData"); viewportData = static_cast<RenderViewport*>(buf); // Create uniform buffer objects unsigned int buffers[MaxViewportCount]; device->CreateBuffers(MaxViewportCount, buffers); for (size_t i = 0; i < MaxViewportCount; ++i) { viewportData[i].uniformBlockObject = buffers[i]; device->BindBuffer(RenderBufferTarget::UniformBuffer, viewportData[i].uniformBlockObject); RenderCommandData::SetBufferStorage storage{}; storage.target = RenderBufferTarget::UniformBuffer; storage.size = sizeof(ViewportUniformBlock); storage.data = nullptr; storage.dynamicStorage = true; device->SetBufferStorage(&storage); StringRef label("Renderer viewport uniform buffer"); device->SetObjectLabel(RenderObjectType::Buffer, buffers[i], label); } } { KOKKO_PROFILE_SCOPE("Create shadow framebuffer"); // Create shadow framebuffer int shadowSide = CascadedShadowMap::GetShadowCascadeResolution(); unsigned int shadowCascadeCount = CascadedShadowMap::GetCascadeCount(); Vec2i size(shadowSide * shadowCascadeCount, shadowSide); RenderTextureSizedFormat depthFormat = RenderTextureSizedFormat::D32F; framebufferShadow.Create(size.x, size.y, depthFormat, ArrayView<RenderTextureSizedFormat>()); framebufferShadow.SetDepthTextureCompare( RenderTextureCompareMode::CompareRefToTexture, RenderDepthCompareFunc::GreaterThanOrEqual); framebufferShadow.SetDebugLabel(StringRef("Renderer shadow framebuffer")); } { KOKKO_PROFILE_SCOPE("Create tonemap uniform buffer"); // Set up uniform buffer for tonemapping pass device->CreateBuffers(1, &tonemapUniformBufferId); device->BindBuffer(RenderBufferTarget::UniformBuffer, tonemapUniformBufferId); RenderCommandData::SetBufferStorage storage{}; storage.target = RenderBufferTarget::UniformBuffer; storage.size = sizeof(TonemapUniformBlock); storage.data = nullptr; storage.dynamicStorage = true; device->SetBufferStorage(&storage); StringRef label("Renderer tonemap uniform buffer"); device->SetObjectLabel(RenderObjectType::Buffer, tonemapUniformBufferId, label); } { KOKKO_PROFILE_SCOPE("Create lighting uniform buffer"); // Create opaque lighting pass uniform buffer device->CreateBuffers(1, &lightingUniformBufferId); device->BindBuffer(RenderBufferTarget::UniformBuffer, lightingUniformBufferId); RenderCommandData::SetBufferStorage storage{}; storage.target = RenderBufferTarget::UniformBuffer; storage.size = sizeof(LightingUniformBlock); storage.data = nullptr; storage.dynamicStorage = true; device->SetBufferStorage(&storage); StringRef label("Renderer deferred lighting uniform buffer"); device->SetObjectLabel(RenderObjectType::Buffer, lightingUniformBufferId, label); } { // Create screen filling quad fullscreenMesh = meshManager->CreateMesh(); MeshPresets::UploadPlane(meshManager, fullscreenMesh); } { const char* path = "engine/materials/forward/shadow_depth.material"; shadowMaterial = materialManager->FindMaterialByPath(StringRef(path)); } { const char* path = "engine/materials/deferred_geometry/fallback.material"; fallbackMeshMaterial = materialManager->FindMaterialByPath(StringRef(path)); } { const char* path = "engine/shaders/deferred_lighting/lighting.glsl"; lightingShaderId = shaderManager->GetIdByPath(StringRef(path)); } { const char* path = "engine/shaders/post_process/tonemap.shader.json"; tonemappingShaderId = shaderManager->GetIdByPath(StringRef(path)); } { KOKKO_PROFILE_SCOPE("Calculate BRDF LUT"); // Calculate the BRDF LUT static const int LutSize = 512; device->CreateTextures(1, &brdfLutTextureId); device->BindTexture(RenderTextureTarget::Texture2d, brdfLutTextureId); RenderCommandData::SetTextureStorage2D storage{ RenderTextureTarget::Texture2d, 1, RenderTextureSizedFormat::RG16F, LutSize, LutSize }; device->SetTextureStorage2D(&storage); device->SetTextureWrapModeU(RenderTextureTarget::Texture2d, RenderTextureWrapMode::ClampToEdge); device->SetTextureWrapModeV(RenderTextureTarget::Texture2d, RenderTextureWrapMode::ClampToEdge); device->SetTextureMinFilter(RenderTextureTarget::Texture2d, RenderTextureFilterMode::Linear); device->SetTextureMagFilter(RenderTextureTarget::Texture2d, RenderTextureFilterMode::Linear); unsigned int framebuffer; device->CreateFramebuffers(1, &framebuffer); RenderCommandData::BindFramebufferData bindFramebuffer{ RenderFramebufferTarget::Framebuffer, framebuffer }; device->BindFramebuffer(&bindFramebuffer); RenderCommandData::AttachFramebufferTexture2D attachTexture{ RenderFramebufferTarget::Framebuffer, RenderFramebufferAttachment::Color0, RenderTextureTarget::Texture2d, brdfLutTextureId, 0 }; device->AttachFramebufferTexture2D(&attachTexture); RenderCommandData::ViewportData viewport{ 0, 0, LutSize, LutSize }; device->Viewport(&viewport); const char* path = "engine/shaders/preprocess/calc_brdf_lut.shader.json"; ShaderId calcBrdfShaderId = shaderManager->GetIdByPath(StringRef(path)); const ShaderData& calcBrdfShader = shaderManager->GetShaderData(calcBrdfShaderId); device->UseShaderProgram(calcBrdfShader.driverId); const MeshDrawData* meshDraw = meshManager->GetDrawData(fullscreenMesh); device->BindVertexArray(meshDraw->vertexArrayObject); device->DrawIndexed(meshDraw->primitiveMode, meshDraw->count, meshDraw->indexType); device->DestroyFramebuffers(1, &framebuffer); StringRef label("Renderer BRDF LUT"); device->SetObjectLabel(RenderObjectType::Texture, brdfLutTextureId, label); } // Inialize skybox resources { skyboxMeshId = meshManager->CreateMesh(); MeshPresets::UploadCube(meshManager, skyboxMeshId); const char* shaderPath = "engine/shaders/skybox/skybox.shader.json"; skyboxShaderId = shaderManager->GetIdByPath(StringRef(shaderPath)); device->CreateBuffers(1, &skyboxUniformBufferId); device->BindBuffer(RenderBufferTarget::UniformBuffer, skyboxUniformBufferId); RenderCommandData::SetBufferStorage storage{}; storage.target = RenderBufferTarget::UniformBuffer; storage.size = sizeof(SkyboxUniformBlock); storage.data = nullptr; storage.dynamicStorage = true; device->SetBufferStorage(&storage); } } void Renderer::Deinitialize() { if (skyboxUniformBufferId != 0) { device->DestroyBuffers(1, &skyboxUniformBufferId); skyboxUniformBufferId = 0; } if (fullscreenMesh != MeshId::Null) { meshManager->RemoveMesh(fullscreenMesh); fullscreenMesh = MeshId{ 0 }; } if (lightingUniformBufferId != 0) { device->DestroyBuffers(1, &lightingUniformBufferId); lightingUniformBufferId = 0; } for (unsigned int i = 0; i < FramesInFlightCount; ++i) { if (objectUniformBufferLists[i].GetCount() > 0) { Array<uint32_t>& list = objectUniformBufferLists[i]; device->DestroyBuffers(static_cast<unsigned int>(list.GetCount()), list.GetData()); list.Clear(); } } framebufferShadow.Destroy(); framebufferGbuffer.Destroy(); framebufferLightAcc.Destroy(); if (viewportData != nullptr) { for (size_t i = 0; i < MaxViewportCount; ++i) { if (viewportData[i].uniformBlockObject != 0) { device->DestroyBuffers(1, &(viewportData[i].uniformBlockObject)); viewportData[i].uniformBlockObject = 0; } } allocator->Deallocate(viewportData); viewportData = nullptr; viewportCount = 0; } } void Renderer::CreateResolutionDependentFramebuffers(int width, int height) { ssao->SetFramebufferSize(Vec2i(width, height)); { KOKKO_PROFILE_SCOPE("Create geometry framebuffer"); // Create geometry framebuffer and textures RenderTextureSizedFormat depthFormat = RenderTextureSizedFormat::D32F; RenderTextureSizedFormat colorFormats[GbufferColorCount]; colorFormats[GbufferAlbedoIndex] = RenderTextureSizedFormat::SRGB8; colorFormats[GbufferNormalIndex] = RenderTextureSizedFormat::RG16, colorFormats[GbufferMaterialIndex] = RenderTextureSizedFormat::RGB8; ArrayView<RenderTextureSizedFormat> colorFormatsList(colorFormats, GbufferColorCount); framebufferGbuffer.Create(width, height, depthFormat, colorFormatsList); framebufferGbuffer.SetDebugLabel(StringRef("Renderer G-buffer")); } { KOKKO_PROFILE_SCOPE("Create HDR light accumulation framebuffer"); // HDR light accumulation framebuffer RenderTextureSizedFormat colorFormat = RenderTextureSizedFormat::RGB16F; ArrayView<RenderTextureSizedFormat> colorFormatList(&colorFormat, 1); framebufferLightAcc.Create(width, height, Optional<RenderTextureSizedFormat>(), colorFormatList); framebufferLightAcc.AttachExternalDepthTexture(framebufferGbuffer.GetDepthTextureId()); framebufferLightAcc.SetDebugLabel(StringRef("Renderer light accumulation framebuffer")); } } void Renderer::DestroyResolutionDependentFramebuffers() { KOKKO_PROFILE_FUNCTION(); framebufferGbuffer.Destroy(); framebufferLightAcc.Destroy(); renderTargetContainer->DestroyAllRenderTargets(); } void Renderer::Render(const Optional<CameraParameters>& editorCamera, const Framebuffer& targetFramebuffer) { KOKKO_PROFILE_FUNCTION(); if (targetFramebuffer.IsInitialized() == false) return; if (targetFramebuffer.GetSize() != framebufferGbuffer.GetSize()) { DestroyResolutionDependentFramebuffers(); CreateResolutionDependentFramebuffers(targetFramebuffer.GetWidth(), targetFramebuffer.GetHeight()); } deferredLightingCallback = AddCustomRenderer(this); skyboxRenderCallback = AddCustomRenderer(this); postProcessCallback = AddCustomRenderer(this); targetFramebufferId = targetFramebuffer.GetFramebufferId(); unsigned int objectDrawCount = PopulateCommandList(editorCamera, targetFramebuffer); UpdateUniformBuffers(objectDrawCount); intptr_t objectDrawsProcessed = 0; uint64_t lastVpIdx = MaxViewportCount; uint64_t lastShaderProgram = 0; const MeshDrawData* draw = nullptr; MeshId lastMeshId = MeshId{ 0 }; MaterialId lastMaterialId = MaterialId{ 0 }; Array<unsigned int>& objUniformBuffers = objectUniformBufferLists[currentFrameIndex]; CameraParameters cameraParams = GetCameraParameters(editorCamera, targetFramebuffer); uint64_t* itr = commandList.commands.GetData(); uint64_t* end = itr + commandList.commands.GetCount(); for (; itr != end; ++itr) { uint64_t command = *itr; // If command is not control command, draw object if (ParseControlCommand(command) == false) { KOKKO_PROFILE_SCOPE("Draw command"); uint64_t mat = renderOrder.materialId.GetValue(command); uint64_t vpIdx = renderOrder.viewportIndex.GetValue(command); const RenderViewport& viewport = viewportData[vpIdx]; if (mat != RenderOrderConfiguration::CallbackMaterialId) { MaterialId matId = MaterialId{ static_cast<unsigned int>(mat) }; if (matId == MaterialId::Null) matId = fallbackMeshMaterial; uint64_t objIdx = renderOrder.renderObject.GetValue(command); // Update viewport uniform block if (vpIdx != lastVpIdx) { unsigned int ubo = viewportData[vpIdx].uniformBlockObject; device->BindBufferBase(RenderBufferTarget::UniformBuffer, UniformBlockBinding::Viewport, ubo); lastVpIdx = vpIdx; } if (matId != lastMaterialId) { lastMaterialId = matId; unsigned int matShaderId = materialManager->GetMaterialShaderDeviceId(matId); unsigned int matUniformBuffer = materialManager->GetMaterialUniformBufferId(matId); if (matShaderId != lastShaderProgram) { device->UseShaderProgram(matShaderId); lastShaderProgram = matShaderId; } BindMaterialTextures(materialManager->GetMaterialUniforms(matId)); // Bind material uniform block to shader device->BindBufferBase(RenderBufferTarget::UniformBuffer, UniformBlockBinding::Material, matUniformBuffer); } // Bind object transform uniform block to shader intptr_t bufferIndex = objectDrawsProcessed / objectsPerUniformBuffer; intptr_t objectInBuffer = objectDrawsProcessed % objectsPerUniformBuffer; size_t rangeSize = static_cast<size_t>(objectUniformBlockStride); RenderCommandData::BindBufferRange bind{ RenderBufferTarget::UniformBuffer, UniformBlockBinding::Object, objUniformBuffers[bufferIndex], objectInBuffer * objectUniformBlockStride, rangeSize }; device->BindBufferRange(&bind); MeshId mesh = data.mesh[objIdx]; if (mesh != lastMeshId) { lastMeshId = mesh; draw = meshManager->GetDrawData(mesh); device->BindVertexArray(draw->vertexArrayObject); } device->DrawIndexed(draw->primitiveMode, draw->count, draw->indexType); objectDrawsProcessed += 1; } else // Render with callback { size_t callbackId = renderOrder.renderObject.GetValue(command); if (callbackId > 0 && callbackId <= customRenderers.GetCount()) { CustomRenderer* customRenderer = customRenderers[callbackId - 1]; if (customRenderer != nullptr) { CustomRenderer::RenderParams params; params.viewport = &viewport; params.cameraParams = cameraParams; params.callbackId = static_cast<unsigned int>(callbackId); params.command = command; params.scene = scene; customRenderer->RenderCustom(params); // Reset state cache lastVpIdx = MaxViewportCount; lastShaderProgram = 0; draw = nullptr; lastMeshId = MeshId{ 0 }; lastMaterialId = MaterialId{ 0 }; // TODO: manage sampler state more robustly device->BindSampler(0, 0); // TODO: Figure how to restore viewport and other relevant state } } } } } commandList.Clear(); renderTargetContainer->ConfirmAllTargetsAreUnused(); currentFrameIndex = (currentFrameIndex + 1) % FramesInFlightCount; customRenderers.Clear(); targetFramebufferId = 0; } void Renderer::BindMaterialTextures(const kokko::UniformData& materialUniforms) const { KOKKO_PROFILE_FUNCTION(); unsigned int usedTextures = 0; for (auto& uniform : materialUniforms.GetTextureUniforms()) { switch (uniform.type) { case kokko::UniformDataType::Tex2D: case kokko::UniformDataType::TexCube: device->SetActiveTextureUnit(usedTextures); device->BindTexture(uniform.textureTarget, uniform.textureObject); device->SetUniformInt(uniform.uniformLocation, usedTextures); ++usedTextures; break; default: break; } } } void Renderer::BindTextures(const ShaderData& shader, unsigned int count, const uint32_t* nameHashes, const unsigned int* textures) { for (unsigned int i = 0; i < count; ++i) { const kokko::TextureUniform* tu = shader.uniforms.FindTextureUniformByNameHash(nameHashes[i]); if (tu != nullptr) { device->SetUniformInt(tu->uniformLocation, i); device->SetActiveTextureUnit(i); device->BindTexture(tu->textureTarget, textures[i]); } } } void Renderer::RenderCustom(const CustomRenderer::RenderParams& params) { if (params.callbackId == deferredLightingCallback) RenderDeferredLighting(params); else if (params.callbackId == skyboxRenderCallback) RenderSkybox(params); else if (params.callbackId == postProcessCallback) RenderPostProcess(params); } void Renderer::SetLockCullingCamera(bool lockEnable) { lockCullingCamera = lockEnable; } const Mat4x4f& Renderer::GetCullingCameraTransform() const { return lockCullingCameraTransform.forward; } void Renderer::RenderDeferredLighting(const CustomRenderer::RenderParams& params) { // Both SSAO and deferred lighting passes use these ProjectionParameters projParams = params.cameraParams.projection; LightingUniformBlock lightingUniforms; UpdateLightingDataToUniformBuffer(projParams, lightingUniforms); device->BindBuffer(RenderBufferTarget::UniformBuffer, lightingUniformBufferId); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, sizeof(LightingUniformBlock), &lightingUniforms); device->DepthTestDisable(); ScreenSpaceAmbientOcclusion::RenderParams ssaoRenderParams; ssaoRenderParams.normalTexture = framebufferGbuffer.GetColorTextureId(GbufferNormalIndex); ssaoRenderParams.depthTexture = framebufferGbuffer.GetDepthTextureId(); ssaoRenderParams.projection = projParams; ssao->Render(ssaoRenderParams); EnvironmentTextures envMap; int environmentId = scene->GetEnvironmentId(); if (environmentId >= 0) envMap = environmentManager->GetEnvironmentMap(environmentId); else envMap = environmentManager->GetEmptyEnvironmentMap(); const TextureData& diffIrrTexture = textureManager->GetTextureData(envMap.diffuseIrradianceTexture); const TextureData& specIrrTexture = textureManager->GetTextureData(envMap.specularIrradianceTexture); // Deferred lighting PostProcessRenderPass deferredPass; deferredPass.textureNameHashes[0] = "g_albedo"_hash; deferredPass.textureNameHashes[1] = "g_normal"_hash; deferredPass.textureNameHashes[2] = "g_material"_hash; deferredPass.textureNameHashes[3] = "g_depth"_hash; deferredPass.textureNameHashes[4] = "ssao_map"_hash; deferredPass.textureNameHashes[5] = "shadow_map"_hash; deferredPass.textureNameHashes[6] = "diff_irradiance_map"_hash; deferredPass.textureNameHashes[7] = "spec_irradiance_map"_hash; deferredPass.textureNameHashes[8] = "brdf_lut"_hash; deferredPass.textureIds[0] = framebufferGbuffer.GetColorTextureId(GbufferAlbedoIndex); deferredPass.textureIds[1] = framebufferGbuffer.GetColorTextureId(GbufferNormalIndex); deferredPass.textureIds[2] = framebufferGbuffer.GetColorTextureId(GbufferMaterialIndex); deferredPass.textureIds[3] = framebufferGbuffer.GetDepthTextureId(); deferredPass.textureIds[4] = ssao->GetResultTextureId(); deferredPass.textureIds[5] = framebufferShadow.GetDepthTextureId(); deferredPass.textureIds[6] = diffIrrTexture.textureObjectId; deferredPass.textureIds[7] = specIrrTexture.textureObjectId; deferredPass.textureIds[8] = brdfLutTextureId; deferredPass.samplerIds[0] = 0; deferredPass.samplerIds[1] = 0; deferredPass.samplerIds[2] = 0; deferredPass.samplerIds[3] = 0; deferredPass.samplerIds[4] = 0; deferredPass.samplerIds[5] = 0; deferredPass.samplerIds[6] = 0; deferredPass.samplerIds[7] = 0; deferredPass.samplerIds[8] = 0; deferredPass.textureCount = 9; deferredPass.uniformBufferId = lightingUniformBufferId; deferredPass.uniformBindingPoint = UniformBlockBinding::Object; deferredPass.uniformBufferRangeStart = 0; deferredPass.uniformBufferRangeSize = sizeof(LightingUniformBlock); deferredPass.framebufferId = framebufferLightAcc.GetFramebufferId(); deferredPass.viewportSize = framebufferLightAcc.GetSize(); deferredPass.shaderId = lightingShaderId; deferredPass.enableBlending = false; postProcessRenderer->RenderPass(deferredPass); ssao->ReleaseResult(); } void Renderer::RenderSkybox(const CustomRenderer::RenderParams& params) { KOKKO_PROFILE_FUNCTION(); EnvironmentTextures envMap; int environmentId = scene->GetEnvironmentId(); if (environmentId >= 0) envMap = environmentManager->GetEnvironmentMap(environmentId); else envMap = environmentManager->GetEmptyEnvironmentMap(); const TextureData& envTexture = textureManager->GetTextureData(envMap.environmentTexture); const ShaderData& shader = shaderManager->GetShaderData(skyboxShaderId); device->UseShaderProgram(shader.driverId); const kokko::TextureUniform* uniform = shader.uniforms.FindTextureUniformByNameHash("environment_map"_hash); if (uniform != nullptr) { device->SetActiveTextureUnit(0); device->BindTexture(envTexture.textureTarget, envTexture.textureObjectId); device->SetUniformInt(uniform->uniformLocation, 0); } device->BindBufferBase(RenderBufferTarget::UniformBuffer, UniformBlockBinding::Object, skyboxUniformBufferId); const MeshDrawData* draw = meshManager->GetDrawData(skyboxMeshId); device->BindVertexArray(draw->vertexArrayObject); device->DrawIndexed(draw->primitiveMode, draw->count, draw->indexType); } void Renderer::RenderPostProcess(const CustomRenderer::RenderParams& params) { KOKKO_PROFILE_FUNCTION(); RenderBloom(params); RenderTonemapping(params); } void Renderer::RenderBloom(const CustomRenderer::RenderParams& params) { unsigned int sourceTexture = framebufferLightAcc.GetColorTextureId(0); unsigned int framebufferId = framebufferLightAcc.GetFramebufferId(); bloomEffect->Render(sourceTexture, framebufferId, framebufferLightAcc.GetSize()); } void Renderer::RenderTonemapping(const CustomRenderer::RenderParams& params) { KOKKO_PROFILE_FUNCTION(); if (targetFramebufferId != 0) { device->BlendingDisable(); device->DepthTestDisable(); const MeshDrawData* meshDrawData = meshManager->GetDrawData(fullscreenMesh); device->BindVertexArray(meshDrawData->vertexArrayObject); // Bind default framebuffer RenderCommandData::BindFramebufferData bindFramebufferCommand; bindFramebufferCommand.target = RenderFramebufferTarget::Framebuffer; bindFramebufferCommand.framebuffer = targetFramebufferId; device->BindFramebuffer(&bindFramebufferCommand); const ShaderData& shader = shaderManager->GetShaderData(tonemappingShaderId); device->UseShaderProgram(shader.driverId); TonemapUniformBlock uniforms; uniforms.exposure = 1.0f; device->BindBuffer(RenderBufferTarget::UniformBuffer, tonemapUniformBufferId); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, sizeof(TonemapUniformBlock), &uniforms); device->BindBufferBase(RenderBufferTarget::UniformBuffer, UniformBlockBinding::Object, tonemapUniformBufferId); { uint32_t textureNameHashes[] = { "light_acc_map"_hash }; unsigned int textureIds[] = { framebufferLightAcc.GetColorTextureId(0) }; BindTextures(shader, 1, textureNameHashes, textureIds); } device->DrawIndexed(meshDrawData->primitiveMode, meshDrawData->count, meshDrawData->indexType); } } void Renderer::UpdateLightingDataToUniformBuffer( const ProjectionParameters& projection, LightingUniformBlock& uniformsOut) { KOKKO_PROFILE_FUNCTION(); const RenderViewport& fsvp = viewportData[viewportIndexFullscreen]; // Update directional light viewports Array<LightId>& directionalLights = lightResultArray; lightManager->GetDirectionalLights(directionalLights); Vec2f halfNearPlane; halfNearPlane.y = std::tan(projection.perspectiveFieldOfView * 0.5f); halfNearPlane.x = halfNearPlane.y * projection.aspect; uniformsOut.halfNearPlane = halfNearPlane; int shadowSide = CascadedShadowMap::GetShadowCascadeResolution(); unsigned int cascadeCount = CascadedShadowMap::GetCascadeCount(); uniformsOut.shadowMapScale = Vec2f(1.0f / (cascadeCount * shadowSide), 1.0f / shadowSide); uniformsOut.frameResolution = framebufferGbuffer.GetSize().As<float>(); // Set viewport transform matrices uniformsOut.perspectiveMatrix = fsvp.projection; uniformsOut.viewToWorld = fsvp.view.forward; size_t dirLightCount = directionalLights.GetCount(); uniformsOut.directionalLightCount = static_cast<int>(dirLightCount); // Directional light for (size_t i = 0; i < dirLightCount; ++i) { LightId dirLightId = directionalLights[i]; Mat3x3f orientation = lightManager->GetOrientation(dirLightId); Vec3f wLightDir = orientation * Vec3f(0.0f, 0.0f, -1.0f); Vec4f vLightDir = fsvp.view.inverse * Vec4f(wLightDir, 0.0f); uniformsOut.lightDirections[i] = vLightDir; uniformsOut.lightColors[i] = lightManager->GetColor(dirLightId); uniformsOut.lightCastShadow[i] = lightManager->GetShadowCasting(dirLightId); } lightResultArray.Clear(); Array<LightId>& nonDirLights = lightResultArray; lightManager->GetNonDirectionalLightsWithinFrustum(fsvp.frustum, nonDirLights); // Count the different light types unsigned int pointLightCount = 0; unsigned int spotLightCount = 0; for (size_t lightIdx = 0, count = nonDirLights.GetCount(); lightIdx < count; ++lightIdx) { LightType type = lightManager->GetLightType(nonDirLights[lightIdx]); if (type == LightType::Point) pointLightCount += 1; else if (type == LightType::Spot) spotLightCount += 1; } uniformsOut.pointLightCount = pointLightCount; uniformsOut.spotLightCount = spotLightCount; const size_t dirLightOffset = 1; size_t pointLightsAdded = 0; size_t spotLightsAdded = 0; // Light other visible lights for (size_t lightIdx = 0, count = nonDirLights.GetCount(); lightIdx < count; ++lightIdx) { size_t shaderLightIdx; LightId lightId = nonDirLights[lightIdx]; // Point lights come first, so offset spot lights with the amount of point lights LightType type = lightManager->GetLightType(lightId); if (type == LightType::Spot) { shaderLightIdx = dirLightOffset + pointLightCount + spotLightsAdded; spotLightsAdded += 1; Mat3x3f orientation = lightManager->GetOrientation(lightId); Vec3f wLightDir = orientation * Vec3f(0.0f, 0.0f, -1.0f); Vec4f vLightDir = fsvp.view.inverse * Vec4f(wLightDir, 0.0f); vLightDir.w = lightManager->GetSpotAngle(lightId); uniformsOut.lightDirections[shaderLightIdx] = vLightDir; } else { shaderLightIdx = dirLightOffset + pointLightsAdded; pointLightsAdded += 1; } Vec3f wLightPos = lightManager->GetPosition(lightId); Vec3f vLightPos = (fsvp.view.inverse * Vec4f(wLightPos, 1.0f)).xyz(); float radius = lightManager->GetRadius(lightId); float inverseSquareRadius = 1.0f / (radius * radius); uniformsOut.lightPositions[shaderLightIdx] = Vec4f(vLightPos, inverseSquareRadius); Vec3f lightCol = lightManager->GetColor(lightId); uniformsOut.lightColors[shaderLightIdx] = lightCol; } lightResultArray.Clear(); // shadow_params.splits[0] is the near depth uniformsOut.shadowSplits[0] = projection.perspectiveNear; unsigned int shadowCascadeCount = CascadedShadowMap::GetCascadeCount(); uniformsOut.cascadeCount = shadowCascadeCount; float cascadeSplitDepths[CascadedShadowMap::MaxCascadeCount]; CascadedShadowMap::CalculateSplitDepths(projection, cascadeSplitDepths); Mat4x4f bias; bias[0] = 0.5f; bias[5] = 0.5f; bias[12] = 0.5f; bias[13] = 0.5f; // Update transforms and split depths for each shadow cascade for (size_t vpIdx = 0; vpIdx < shadowCascadeCount; ++vpIdx) { Mat4x4f viewToLight = viewportData[vpIdx].viewProjection * fsvp.view.forward; Mat4x4f shadowMat = bias * viewToLight; uniformsOut.shadowMatrices[vpIdx] = shadowMat; uniformsOut.shadowSplits[vpIdx + 1] = cascadeSplitDepths[vpIdx]; } uniformsOut.shadowBiasOffset = 0.001f; uniformsOut.shadowBiasFactor = 0.0019f; uniformsOut.shadowBiasClamp = 0.01f; } void Renderer::UpdateUniformBuffers(size_t objectDrawCount) { KOKKO_PROFILE_FUNCTION(); size_t buffersRequired = (objectDrawCount + objectsPerUniformBuffer - 1) / objectsPerUniformBuffer; Array<unsigned int>& objUniformBuffers = objectUniformBufferLists[currentFrameIndex]; // Create new object transform uniform buffers if needed if (buffersRequired > objUniformBuffers.GetCount()) { size_t currentCount = objUniformBuffers.GetCount(); objUniformBuffers.Resize(buffersRequired); unsigned int addCount = static_cast<unsigned int>(buffersRequired - currentCount); device->CreateBuffers(addCount, objUniformBuffers.GetData() + currentCount); for (size_t i = currentCount; i < buffersRequired; ++i) { device->BindBuffer(RenderBufferTarget::UniformBuffer, objUniformBuffers[i]); RenderCommandData::SetBufferStorage setStorage{}; setStorage.target = RenderBufferTarget::UniformBuffer; setStorage.size = ObjectUniformBufferSize; setStorage.dynamicStorage = true; device->SetBufferStorage(&setStorage); StringRef label("Renderer object uniform buffer"); device->SetObjectLabel(RenderObjectType::Buffer, objUniformBuffers[i], label); } } intptr_t prevBufferIndex = -1; uniformStagingBuffer.Resize(ObjectUniformBufferSize); unsigned char* stagingBuffer = uniformStagingBuffer.GetData(); size_t objectDrawsProcessed = 0; uint64_t* itr = commandList.commands.GetData(); uint64_t* end = itr + commandList.commands.GetCount(); for (; itr != end; ++itr) { uint64_t command = *itr; uint64_t mat = renderOrder.materialId.GetValue(command); uint64_t vpIdx = renderOrder.viewportIndex.GetValue(command); uint64_t objIdx = renderOrder.renderObject.GetValue(command); // Is regular draw command if (IsDrawCommand(command) && mat != RenderOrderConfiguration::CallbackMaterialId) { intptr_t bufferIndex = objectDrawsProcessed / objectsPerUniformBuffer; intptr_t objectInBuffer = objectDrawsProcessed % objectsPerUniformBuffer; if (bufferIndex != prevBufferIndex) { if (prevBufferIndex >= 0) { KOKKO_PROFILE_SCOPE("Update buffer data"); device->BindBuffer(RenderBufferTarget::UniformBuffer, objUniformBuffers[prevBufferIndex]); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, ObjectUniformBufferSize, stagingBuffer); } prevBufferIndex = bufferIndex; } TransformUniformBlock* tu = reinterpret_cast<TransformUniformBlock*>(stagingBuffer + objectUniformBlockStride * objectInBuffer); const Mat4x4f& model = data.transform[objIdx]; tu->MVP = viewportData[vpIdx].viewProjection * model; tu->MV = viewportData[vpIdx].view.inverse * model; tu->M = model; objectDrawsProcessed += 1; } } if (prevBufferIndex >= 0) { KOKKO_PROFILE_SCOPE("Update buffer data"); unsigned int updateSize = static_cast<unsigned int>((objectDrawsProcessed % objectsPerUniformBuffer) * objectUniformBlockStride); device->BindBuffer(RenderBufferTarget::UniformBuffer, objUniformBuffers[prevBufferIndex]); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, updateSize, stagingBuffer); } } bool Renderer::IsDrawCommand(uint64_t orderKey) { return renderOrder.command.GetValue(orderKey) == static_cast<uint64_t>(RenderCommandType::Draw); } bool Renderer::ParseControlCommand(uint64_t orderKey) { KOKKO_PROFILE_FUNCTION(); if (renderOrder.command.GetValue(orderKey) == static_cast<uint64_t>(RenderCommandType::Draw)) return false; uint64_t commandTypeInt = renderOrder.commandType.GetValue(orderKey); RenderControlType control = static_cast<RenderControlType>(commandTypeInt); switch (control) { case RenderControlType::BlendingEnable: device->BlendingEnable(); break; case RenderControlType::BlendingDisable: device->BlendingDisable(); break; case RenderControlType::BlendFunction: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* blendFn = reinterpret_cast<RenderCommandData::BlendFunctionData*>(data); device->BlendFunction(blendFn); } break; case RenderControlType::Viewport: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* viewport = reinterpret_cast<RenderCommandData::ViewportData*>(data); device->Viewport(viewport); } break; case RenderControlType::ScissorTestEnable: device->ScissorTestEnable(); break; case RenderControlType::ScissorTestDisable: device->ScissorTestDisable(); break; case RenderControlType::DepthRange: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* depthRange = reinterpret_cast<RenderCommandData::DepthRangeData*>(data); device->DepthRange(depthRange); } break; case RenderControlType::DepthTestEnable: device->DepthTestEnable(); break; case RenderControlType::DepthTestDisable: device->DepthTestDisable(); break; case RenderControlType::DepthTestFunction: { uint64_t fn = renderOrder.commandData.GetValue(orderKey); device->DepthTestFunction(static_cast<RenderDepthCompareFunc>(fn)); } break; case RenderControlType::DepthWriteEnable: device->DepthWriteEnable(); break; case RenderControlType::DepthWriteDisable: device->DepthWriteDisable(); break; case RenderControlType::CullFaceEnable: device->CullFaceEnable(); break; case RenderControlType::CullFaceDisable: device->CullFaceDisable(); break; case RenderControlType::CullFaceFront: device->CullFaceFront(); break; case RenderControlType::CullFaceBack: device->CullFaceBack(); break; case RenderControlType::Clear: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* clearMask = reinterpret_cast<RenderCommandData::ClearMask*>(data); device->Clear(clearMask); } break; case RenderControlType::ClearColor: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* color = reinterpret_cast<RenderCommandData::ClearColorData*>(data); device->ClearColor(color); } break; case RenderControlType::ClearDepth: { uint64_t intDepth = renderOrder.commandData.GetValue(orderKey); float depth = *reinterpret_cast<float*>(&intDepth); device->ClearDepth(depth); } break; case RenderControlType::BindFramebuffer: { uint64_t offset = renderOrder.commandData.GetValue(orderKey); uint8_t* data = commandList.commandData.GetData() + offset; auto* bind = reinterpret_cast<RenderCommandData::BindFramebufferData*>(data); device->BindFramebuffer(bind); } break; case RenderControlType::FramebufferSrgbEnable: device->FramebufferSrgbEnable(); break; case RenderControlType::FramebufferSrgbDisable: device->FramebufferSrgbDisable(); break; } return true; } float CalculateDepth(const Vec3f& objPos, const Vec3f& eyePos, const Vec3f& eyeForward, float farMinusNear, float minusNear) { return (Vec3f::Dot(objPos - eyePos, eyeForward) - minusNear) / farMinusNear; } CameraParameters Renderer::GetCameraParameters(const Optional<CameraParameters>& editorCamera, const Framebuffer& targetFramebuffer) { KOKKO_PROFILE_FUNCTION(); if (editorCamera.HasValue()) { return editorCamera.GetValue(); } else { Entity cameraEntity = scene->GetActiveCameraEntity(); CameraParameters result; SceneObjectId cameraSceneObj = scene->Lookup(cameraEntity); result.transform.forward = scene->GetWorldTransform(cameraSceneObj); result.transform.inverse = result.transform.forward.GetInverse(); CameraId cameraId = cameraSystem->Lookup(cameraEntity); result.projection = cameraSystem->GetData(cameraId); result.projection.SetAspectRatio(targetFramebuffer.GetWidth(), targetFramebuffer.GetHeight()); return result; } } unsigned int Renderer::PopulateCommandList(const Optional<CameraParameters>& editorCamera, const Framebuffer& targetFramebuffer) { KOKKO_PROFILE_FUNCTION(); const float mainViewportMinObjectSize = 50.0f; const float shadowViewportMinObjectSize = 30.0f; // Get camera transforms CameraParameters cameraParameters = GetCameraParameters(editorCamera, targetFramebuffer); Mat4x4fBijection cameraTransforms = cameraParameters.transform; ProjectionParameters projectionParams = cameraParameters.projection; Mat4x4f cameraProjection = projectionParams.GetProjectionMatrix(true); Mat4x4fBijection cullingTransform; if (lockCullingCamera) cullingTransform = lockCullingCameraTransform; else { cullingTransform = cameraTransforms; lockCullingCameraTransform = cameraTransforms; } Vec3f cameraPos = (cameraTransforms.forward * Vec4f(0.0f, 0.0f, 0.0f, 1.0f)).xyz(); int shadowSide = CascadedShadowMap::GetShadowCascadeResolution(); unsigned int shadowCascadeCount = CascadedShadowMap::GetCascadeCount(); Vec2i shadowCascadeSize(shadowSide, shadowSide); Vec2i shadowTextureSize(shadowSide * shadowCascadeCount, shadowSide); Mat4x4fBijection cascadeViewTransforms[CascadedShadowMap::MaxCascadeCount]; ProjectionParameters lightProjections[CascadedShadowMap::MaxCascadeCount]; // Update skybox parameters { SkyboxUniformBlock skyboxUniforms; skyboxUniforms.transform = cameraProjection * cameraTransforms.inverse * Mat4x4f::Translate(cameraPos); device->BindBuffer(RenderBufferTarget::UniformBuffer, skyboxUniformBufferId); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, sizeof(SkyboxUniformBlock), &skyboxUniforms); } // Reset the used viewport count viewportCount = 0; // Update directional light viewports lightManager->GetDirectionalLights(lightResultArray); ViewportUniformBlock viewportUniforms; for (size_t i = 0, count = lightResultArray.GetCount(); i < count; ++i) { LightId id = lightResultArray[i]; if (lightManager->GetShadowCasting(id) && viewportCount + shadowCascadeCount + 1 <= MaxViewportCount) { Mat3x3f orientation = lightManager->GetOrientation(id); Vec3f lightDir = orientation * Vec3f(0.0f, 0.0f, -1.0f); CascadedShadowMap::CalculateCascadeFrusta(lightDir, cameraTransforms.forward, projectionParams, cascadeViewTransforms, lightProjections); for (unsigned int cascade = 0; cascade < shadowCascadeCount; ++cascade) { unsigned int vpIdx = viewportCount; viewportCount += 1; bool reverseDepth = true; const Mat4x4f& forwardTransform = cascadeViewTransforms[cascade].forward; const Mat4x4f& inverseTransform = cascadeViewTransforms[cascade].inverse; RenderViewport& vp = viewportData[vpIdx]; vp.position = (forwardTransform * Vec4f(0.0f, 0.0f, 0.0f, 1.0f)).xyz(); vp.forward = (forwardTransform * Vec4f(0.0f, 0.0f, -1.0f, 0.0f)).xyz(); vp.farMinusNear = lightProjections[cascade].orthographicFar - lightProjections[cascade].orthographicNear; vp.minusNear = -lightProjections[cascade].orthographicNear; vp.objectMinScreenSizePx = shadowViewportMinObjectSize; vp.view.forward = forwardTransform; vp.view.inverse = inverseTransform; vp.projection = lightProjections[cascade].GetProjectionMatrix(reverseDepth); vp.viewProjection = vp.projection * vp.view.inverse; vp.viewportRectangle.size = shadowCascadeSize; vp.viewportRectangle.position = Vec2i(cascade * shadowSide, 0); vp.frustum.Update(lightProjections[cascade], forwardTransform); viewportUniforms.VP = vp.viewProjection; viewportUniforms.V = vp.view.inverse; viewportUniforms.P = vp.projection; device->BindBuffer(RenderBufferTarget::UniformBuffer, vp.uniformBlockObject); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, sizeof(ViewportUniformBlock), &viewportUniforms); } } } lightResultArray.Clear(); unsigned int numShadowViewports = viewportCount; { // Add the fullscreen viewport unsigned int vpIdx = viewportCount; viewportCount += 1; bool reverseDepth = true; Rectanglei viewportRect{ 0, 0, targetFramebuffer.GetWidth(), targetFramebuffer.GetHeight() }; RenderViewport& vp = viewportData[vpIdx]; vp.position = (cameraTransforms.forward * Vec4f(0.0f, 0.0f, 0.0f, 1.0f)).xyz(); vp.forward = (cameraTransforms.forward * Vec4f(0.0f, 0.0f, -1.0f, 0.0f)).xyz(); vp.farMinusNear = projectionParams.perspectiveFar - projectionParams.perspectiveNear; vp.minusNear = -projectionParams.perspectiveNear; vp.objectMinScreenSizePx = mainViewportMinObjectSize; vp.view.forward = cameraTransforms.forward; vp.view.inverse = cameraTransforms.inverse; vp.projection = cameraProjection; vp.viewProjection = vp.projection * vp.view.inverse; vp.viewportRectangle = viewportRect; vp.frustum.Update(projectionParams, cullingTransform.forward); viewportUniforms.VP = vp.viewProjection; viewportUniforms.V = vp.view.inverse; viewportUniforms.P = vp.projection; device->BindBuffer(RenderBufferTarget::UniformBuffer, vp.uniformBlockObject); device->SetBufferSubData(RenderBufferTarget::UniformBuffer, 0, sizeof(ViewportUniformBlock), &viewportUniforms); this->viewportIndexFullscreen = vpIdx; } const FrustumPlanes& fullscreenFrustum = viewportData[viewportIndexFullscreen].frustum; RenderPass g_pass = RenderPass::OpaqueGeometry; RenderPass l_pass = RenderPass::OpaqueLighting; RenderPass s_pass = RenderPass::Skybox; RenderPass t_pass = RenderPass::Transparent; RenderPass p_pass = RenderPass::PostProcess; using ctrl = RenderControlType; // Before light shadow viewport // Set depth test on commandList.AddControl(0, g_pass, 0, ctrl::DepthTestEnable); // Set depth test function commandList.AddControl(0, g_pass, 1, ctrl::DepthTestFunction, static_cast<unsigned int>(RenderDepthCompareFunc::Greater)); // Enable depth writing commandList.AddControl(0, g_pass, 2, ctrl::DepthWriteEnable); // Set face culling on commandList.AddControl(0, g_pass, 3, ctrl::CullFaceEnable); // Set face culling to cull back faces commandList.AddControl(0, g_pass, 4, ctrl::CullFaceBack); commandList.AddControl(0, g_pass, 5, ctrl::ScissorTestDisable); { // Set clear depth float depth = 0.0f; unsigned int* intDepthPtr = reinterpret_cast<unsigned int*>(&depth); commandList.AddControl(0, g_pass, 6, ctrl::ClearDepth, *intDepthPtr); } // Disable blending commandList.AddControl(0, g_pass, 7, ctrl::BlendingDisable); if (numShadowViewports > 0) { { // Bind shadow framebuffer before any shadow cascade draws RenderCommandData::BindFramebufferData data; data.target = RenderFramebufferTarget::Framebuffer; data.framebuffer = framebufferShadow.GetFramebufferId(); commandList.AddControl(0, g_pass, 8, ctrl::BindFramebuffer, sizeof(data), &data); } { // Set viewport size to full framebuffer size before clearing RenderCommandData::ViewportData data; data.x = 0; data.y = 0; data.w = framebufferShadow.GetWidth(); data.h = framebufferShadow.GetHeight(); commandList.AddControl(0, g_pass, 9, ctrl::Viewport, sizeof(data), &data); } // Clear shadow framebuffer RenderFramebufferTarget::Framebuffer { RenderCommandData::ClearMask clearMask{ false, true, false }; commandList.AddControl(0, g_pass, 10, ctrl::Clear, sizeof(clearMask), &clearMask); } // Enable sRGB conversion for framebuffer commandList.AddControl(0, g_pass, 11, ctrl::FramebufferSrgbEnable); // For each shadow viewport for (unsigned int vpIdx = 0; vpIdx < numShadowViewports; ++vpIdx) { const RenderViewport& viewport = viewportData[vpIdx]; // Set viewport size RenderCommandData::ViewportData data; data.x = viewport.viewportRectangle.position.x; data.y = viewport.viewportRectangle.position.y; data.w = viewport.viewportRectangle.size.x; data.h = viewport.viewportRectangle.size.y; commandList.AddControl(vpIdx, g_pass, 12, ctrl::Viewport, sizeof(data), &data); } } // Before fullscreen viewport // PASS: OPAQUE GEOMETRY unsigned int fsvp = viewportIndexFullscreen; // Set depth test function for reverse depth buffer commandList.AddControl(0, g_pass, 1, ctrl::DepthTestFunction, static_cast<unsigned int>(RenderDepthCompareFunc::Greater)); { // Set clear color RenderCommandData::ClearColorData data{ 0.0f, 0.0f, 0.0f, 0.0f }; commandList.AddControl(fsvp, g_pass, 0, ctrl::ClearColor, sizeof(data), &data); } { const RenderViewport& viewport = viewportData[viewportIndexFullscreen]; // Set viewport size RenderCommandData::ViewportData data; data.x = viewport.viewportRectangle.position.x; data.y = viewport.viewportRectangle.position.y; data.w = viewport.viewportRectangle.size.x; data.h = viewport.viewportRectangle.size.y; commandList.AddControl(fsvp, g_pass, 1, ctrl::Viewport, sizeof(data), &data); } { // Bind geometry framebuffer RenderCommandData::BindFramebufferData data; data.target = RenderFramebufferTarget::Framebuffer; data.framebuffer = framebufferGbuffer.GetFramebufferId(); commandList.AddControl(fsvp, g_pass, 2, ctrl::BindFramebuffer, sizeof(data), &data); } // Clear currently bound RenderFramebufferTarget::Framebuffer { RenderCommandData::ClearMask clearMask{ true, true, false }; commandList.AddControl(fsvp, g_pass, 3, ctrl::Clear, sizeof(clearMask), &clearMask); } // PASS: OPAQUE LIGHTING // Draw lighting pass commandList.AddDrawWithCallback(fsvp, l_pass, 0.0f, deferredLightingCallback); // PASS: SKYBOX commandList.AddControl(fsvp, s_pass, 0, ctrl::DepthTestEnable); commandList.AddControl(fsvp, s_pass, 1, ctrl::DepthTestFunction, static_cast<unsigned int>(RenderDepthCompareFunc::Equal)); commandList.AddControl(fsvp, s_pass, 2, ctrl::DepthWriteDisable); { const RenderViewport& viewport = viewportData[viewportIndexFullscreen]; // Set viewport size RenderCommandData::ViewportData data; data.x = viewport.viewportRectangle.position.x; data.y = viewport.viewportRectangle.position.y; data.w = viewport.viewportRectangle.size.x; data.h = viewport.viewportRectangle.size.y; commandList.AddControl(fsvp, s_pass, 3, ctrl::Viewport, sizeof(data), &data); } commandList.AddDrawWithCallback(fsvp, s_pass, 0.0f, skyboxRenderCallback); // PASS: TRANSPARENT // Before transparent objects commandList.AddControl(fsvp, t_pass, 0, ctrl::DepthTestFunction, static_cast<unsigned int>(RenderDepthCompareFunc::Greater)); commandList.AddControl(fsvp, t_pass, 1, ctrl::BlendingEnable); { // Set mix blending RenderCommandData::BlendFunctionData data; data.srcFactor = RenderBlendFactor::SrcAlpha; data.dstFactor = RenderBlendFactor::OneMinusSrcAlpha; commandList.AddControl(fsvp, t_pass, 2, ctrl::BlendFunction, sizeof(data), &data); } // PASS: POST PROCESS // Draw HDR tonemapping pass commandList.AddDrawWithCallback(fsvp, p_pass, 0.0f, postProcessCallback); // Create draw commands for render objects in scene unsigned int visRequired = BitPack::CalculateRequired(data.count); objectVisibility.Resize(visRequired * viewportCount); const unsigned int compareTrIdx = static_cast<unsigned int>(TransparencyType::AlphaTest); BitPack* vis[MaxViewportCount]; for (size_t vpIdx = 0; vpIdx < viewportCount; ++vpIdx) { vis[vpIdx] = objectVisibility.GetData() + visRequired * vpIdx; const FrustumPlanes& frustum = viewportData[vpIdx].frustum; const Mat4x4f& viewProjection = viewportData[vpIdx].viewProjection; const Vec2i viewPortSize = viewportData[vpIdx].viewportRectangle.size; float minSize = viewportData[vpIdx].objectMinScreenSizePx / (viewPortSize.x * viewPortSize.y); Intersect::FrustumAABBMinSize(frustum, viewProjection, minSize, data.count, data.bounds, vis[vpIdx]); } unsigned int objectDrawCount = 0; for (unsigned int i = 1; i < data.count; ++i) { Vec3f objPos = (data.transform[i] * Vec4f(0.0f, 0.0f, 0.0f, 1.0f)).xyz(); // Test visibility in shadow viewports for (unsigned int vpIdx = 0, count = numShadowViewports; vpIdx < count; ++vpIdx) { if (BitPack::Get(vis[vpIdx], i) && static_cast<unsigned int>(data.order[i].transparency) <= compareTrIdx) { const RenderViewport& vp = viewportData[vpIdx]; float depth = CalculateDepth(objPos, vp.position, vp.forward, vp.farMinusNear, vp.minusNear); commandList.AddDraw(vpIdx, RenderPass::OpaqueGeometry, depth, shadowMaterial, i); objectDrawCount += 1; } } // Test visibility in fullscreen viewport if (BitPack::Get(vis[fsvp], i)) { const RenderOrderData& o = data.order[i]; const RenderViewport& vp = viewportData[fsvp]; float depth = CalculateDepth(objPos, vp.position, vp.forward, vp.farMinusNear, vp.minusNear); RenderPass pass = static_cast<RenderPass>(o.transparency); commandList.AddDraw(fsvp, pass, depth, o.material, i); objectDrawCount += 1; } } for (size_t i = 0, count = customRenderers.GetCount(); i < count; ++i) { if (customRenderers[i] != nullptr) { CustomRenderer::CommandParams params; params.fullscreenViewport = this->viewportIndexFullscreen; params.commandList = &commandList; params.callbackId = static_cast<unsigned int>(i + 1); params.scene = scene; customRenderers[i]->AddRenderCommands(params); } } commandList.Sort(); return objectDrawCount; } void Renderer::ReallocateRenderObjects(unsigned int required) { if (required <= data.allocated) return; required = static_cast<unsigned int>(Math::UpperPowerOfTwo(required)); // Reserve same amount in entity map entityMap.Reserve(required); InstanceData newData; unsigned int bytes = required * (sizeof(Entity) + sizeof(MeshId) + sizeof(RenderOrderData) + sizeof(BoundingBox) + sizeof(Mat4x4f)); newData.buffer = this->allocator->Allocate(bytes, "Renderer InstanceData buffer"); newData.count = data.count; newData.allocated = required; newData.entity = static_cast<Entity*>(newData.buffer); newData.mesh = reinterpret_cast<MeshId*>(newData.entity + required); newData.order = reinterpret_cast<RenderOrderData*>(newData.mesh + required); newData.bounds = reinterpret_cast<BoundingBox*>(newData.order + required); newData.transform = reinterpret_cast<Mat4x4f*>(newData.bounds + required); if (data.buffer != nullptr) { std::memcpy(newData.entity, data.entity, data.count * sizeof(Entity)); std::memcpy(newData.mesh, data.mesh, data.count * sizeof(MeshId)); std::memcpy(newData.order, data.order, data.count * sizeof(RenderOrderData)); std::memcpy(newData.bounds, data.bounds, data.count * sizeof(BoundingBox)); std::memcpy(newData.transform, data.transform, data.count * sizeof(Mat4x4f)); this->allocator->Deallocate(data.buffer); } data = newData; } RenderObjectId Renderer::AddRenderObject(Entity entity) { RenderObjectId id; this->AddRenderObject(1, &entity, &id); return id; } void Renderer::AddRenderObject(unsigned int count, const Entity* entities, RenderObjectId* renderObjectIdsOut) { if (data.count + count > data.allocated) this->ReallocateRenderObjects(data.count + count); for (unsigned int i = 0; i < count; ++i) { unsigned int id = data.count + i; Entity e = entities[i]; auto mapPair = entityMap.Insert(e.id); mapPair->second.i = id; data.entity[id] = e; data.mesh[id] = MeshId::Null; data.order[id] = RenderOrderData{}; data.bounds[id] = BoundingBox(); data.transform[id] = Mat4x4f(); renderObjectIdsOut[i].i = id; } data.count += count; } void Renderer::RemoveRenderObject(RenderObjectId id) { assert(id != RenderObjectId::Null); assert(id.i < data.count); // Remove from entity map Entity entity = data.entity[id.i]; auto* pair = entityMap.Lookup(entity.id); if (pair != nullptr) entityMap.Remove(pair); if (data.count > 2 && id.i + 1 < data.count) // We need to swap another object { unsigned int swapIdx = data.count - 1; // Update the swapped objects id in the entity map auto* swapKv = entityMap.Lookup(data.entity[swapIdx].id); if (swapKv != nullptr) swapKv->second = id; data.entity[id.i] = data.entity[swapIdx]; data.mesh[id.i] = data.mesh[swapIdx]; data.order[id.i] = data.order[swapIdx]; data.bounds[id.i] = data.bounds[swapIdx]; data.transform[id.i] = data.transform[swapIdx]; } --data.count; } void Renderer::RemoveAll() { entityMap.Clear(); data.count = 1; } unsigned int Renderer::AddCustomRenderer(CustomRenderer* customRenderer) { for (size_t i = 0, count = customRenderers.GetCount(); i < count; ++i) { if (customRenderers[i] == nullptr) { customRenderers[i] = customRenderer; return static_cast<unsigned int>(i + 1); } } customRenderers.PushBack(customRenderer); return static_cast<unsigned int>(customRenderers.GetCount()); } void Renderer::RemoveCustomRenderer(unsigned int callbackId) { if (callbackId == customRenderers.GetCount()) { customRenderers.PopBack(); } else if (callbackId < customRenderers.GetCount() && callbackId > 0) { customRenderers[callbackId - 1] = nullptr; } } void Renderer::NotifyUpdatedTransforms(size_t count, const Entity* entities, const Mat4x4f* transforms) { for (unsigned int entityIdx = 0; entityIdx < count; ++entityIdx) { Entity entity = entities[entityIdx]; RenderObjectId obj = this->Lookup(entity); if (obj != RenderObjectId::Null) { unsigned int dataIdx = obj.i; // Recalculate bounding box MeshId meshId = data.mesh[dataIdx]; if (meshId != MeshId::Null) { const BoundingBox* bounds = meshManager->GetBoundingBox(meshId); data.bounds[dataIdx] = bounds->Transform(transforms[entityIdx]); } // Set world transform data.transform[dataIdx] = transforms[entityIdx]; } } } void Renderer::DebugRender(DebugVectorRenderer* vectorRenderer) { KOKKO_PROFILE_FUNCTION(); Color color(1.0f, 1.0f, 1.0f, 1.0f); for (unsigned int idx = 1; idx < data.count; ++idx) { Vec3f pos = data.bounds[idx].center; Vec3f scale = data.bounds[idx].extents * 2.0f; Mat4x4f transform = Mat4x4f::Translate(pos) * Mat4x4f::Scale(scale); vectorRenderer->DrawWireCube(transform, color); } }
32.985746
141
0.74321
[ "mesh", "geometry", "render", "object", "model", "transform" ]
e7f75dc68c7aabbee21f01c21511dda1b19bb918
13,570
hpp
C++
include/render_graph/frontend/render_graph.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
29
2021-11-19T11:28:22.000Z
2022-03-29T00:26:51.000Z
include/render_graph/frontend/render_graph.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
null
null
null
include/render_graph/frontend/render_graph.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
1
2022-03-05T08:14:40.000Z
2022-03-05T08:14:40.000Z
#pragma once #include <EASTL/unique_ptr.h> #include <EASTL/vector.h> #include "render_graph/frontend/blackboard.hpp" #include "render_graph/frontend/resource_node.hpp" #include "render_graph/frontend/resource_edge.hpp" #include "render_graph/frontend/pass_node.hpp" #define RG_MAX_FRAME_IN_FLIGHT 3 namespace skr { namespace render_graph { class RUNTIME_API RenderGraphProfiler { public: virtual ~RenderGraphProfiler() = default; virtual void on_acquire_executor(class RenderGraph&, class RenderGraphFrameExecutor&) {} virtual void on_cmd_begin(class RenderGraph&, class RenderGraphFrameExecutor&) {} virtual void on_cmd_end(class RenderGraph&, class RenderGraphFrameExecutor&) {} virtual void on_pass_begin(class RenderGraph&, class RenderGraphFrameExecutor&, class PassNode& pass) {} virtual void on_pass_end(class RenderGraph&, class RenderGraphFrameExecutor&, class PassNode& pass) {} virtual void before_commit(class RenderGraph&, class RenderGraphFrameExecutor&) {} virtual void after_commit(class RenderGraph&, class RenderGraphFrameExecutor&) {} }; class RUNTIME_API RenderGraph { public: friend class RenderGraphViz; class RUNTIME_API RenderGraphBuilder { public: friend class RenderGraph; friend class RenderGraphBackend; RenderGraphBuilder& frontend_only() SKR_NOEXCEPT; RenderGraphBuilder& backend_api(ECGPUBackend backend) SKR_NOEXCEPT; RenderGraphBuilder& with_device(CGPUDeviceId device) SKR_NOEXCEPT; RenderGraphBuilder& with_gfx_queue(CGPUQueueId queue) SKR_NOEXCEPT; RenderGraphBuilder& enable_memory_aliasing() SKR_NOEXCEPT; protected: bool memory_aliasing = false; bool no_backend; ECGPUBackend api; CGPUDeviceId device; CGPUQueueId gfx_queue; }; using RenderGraphSetupFunction = eastl::function<void(class RenderGraph::RenderGraphBuilder&)>; static RenderGraph* create(const RenderGraphSetupFunction& setup) SKR_NOEXCEPT; static void destroy(RenderGraph* g) SKR_NOEXCEPT; class RUNTIME_API RenderPassBuilder { public: friend class RenderGraph; RenderPassBuilder& set_name(const char* name) SKR_NOEXCEPT; // textures RenderPassBuilder& read(uint32_t set, uint32_t binding, TextureSRVHandle handle) SKR_NOEXCEPT; RenderPassBuilder& read(const char8_t* name, TextureSRVHandle handle) SKR_NOEXCEPT; RenderPassBuilder& write(uint32_t mrt_index, TextureRTVHandle handle, ECGPULoadAction load_action = CGPU_LOAD_ACTION_CLEAR, ECGPUStoreAction store_action = CGPU_STORE_ACTION_STORE) SKR_NOEXCEPT; RenderPassBuilder& set_depth_stencil(TextureDSVHandle handle, ECGPULoadAction dload_action = CGPU_LOAD_ACTION_CLEAR, ECGPUStoreAction dstore_action = CGPU_STORE_ACTION_STORE, ECGPULoadAction sload_action = CGPU_LOAD_ACTION_CLEAR, ECGPUStoreAction sstore_action = CGPU_STORE_ACTION_STORE) SKR_NOEXCEPT; // buffers RenderPassBuilder& read(const char8_t* name, BufferHandle handle) SKR_NOEXCEPT; RenderPassBuilder& read(uint32_t set, uint32_t binding, BufferHandle handle) SKR_NOEXCEPT; RenderPassBuilder& write(uint32_t set, uint32_t binding, BufferHandle handle) SKR_NOEXCEPT; RenderPassBuilder& write(const char8_t* name, BufferHandle handle) SKR_NOEXCEPT; RenderPassBuilder& use_buffer(PipelineBufferHandle buffer, ECGPUResourceState requested_state) SKR_NOEXCEPT; RenderPassBuilder& set_pipeline(CGPURenderPipelineId pipeline) SKR_NOEXCEPT; RenderPassBuilder& set_root_signature(CGPURootSignatureId signature) SKR_NOEXCEPT; protected: RenderPassBuilder(RenderGraph& graph, RenderPassNode& pass) SKR_NOEXCEPT; RenderGraph& graph; RenderPassNode& node; }; using RenderPassSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::RenderPassBuilder&)>; PassHandle add_render_pass(const RenderPassSetupFunction& setup, const RenderPassExecuteFunction& executor) SKR_NOEXCEPT; class RUNTIME_API ComputePassBuilder { public: friend class RenderGraph; ComputePassBuilder& set_name(const char* name) SKR_NOEXCEPT; ComputePassBuilder& read(uint32_t set, uint32_t binding, TextureSRVHandle handle) SKR_NOEXCEPT; ComputePassBuilder& read(const char8_t* name, TextureSRVHandle handle) SKR_NOEXCEPT; ComputePassBuilder& readwrite(uint32_t set, uint32_t binding, TextureUAVHandle handle) SKR_NOEXCEPT; ComputePassBuilder& readwrite(const char8_t* name, TextureUAVHandle handle) SKR_NOEXCEPT; ComputePassBuilder& read(uint32_t set, uint32_t binding, BufferHandle handle) SKR_NOEXCEPT; ComputePassBuilder& read(const char8_t* name, BufferHandle handle) SKR_NOEXCEPT; ComputePassBuilder& readwrite(uint32_t set, uint32_t binding, BufferHandle handle) SKR_NOEXCEPT; ComputePassBuilder& readwrite(const char8_t* name, BufferHandle handle) SKR_NOEXCEPT; ComputePassBuilder& set_pipeline(CGPUComputePipelineId pipeline) SKR_NOEXCEPT; ComputePassBuilder& set_root_signature(CGPURootSignatureId signature) SKR_NOEXCEPT; protected: ComputePassBuilder(RenderGraph& graph, ComputePassNode& pass) SKR_NOEXCEPT; RenderGraph& graph; ComputePassNode& node; }; using ComputePassSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::ComputePassBuilder&)>; PassHandle add_compute_pass(const ComputePassSetupFunction& setup, const ComputePassExecuteFunction& executor) SKR_NOEXCEPT; class RUNTIME_API CopyPassBuilder { public: friend class RenderGraph; CopyPassBuilder& set_name(const char* name) SKR_NOEXCEPT; CopyPassBuilder& texture_to_texture(TextureSubresourceHandle src, TextureSubresourceHandle dst) SKR_NOEXCEPT; CopyPassBuilder& buffer_to_buffer(BufferRangeHandle src, BufferRangeHandle dst) SKR_NOEXCEPT; protected: CopyPassBuilder(RenderGraph& graph, CopyPassNode& pass) noexcept; RenderGraph& graph; CopyPassNode& node; }; using CopyPassSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::CopyPassBuilder&)>; PassHandle add_copy_pass(const CopyPassSetupFunction& setup) SKR_NOEXCEPT; class RUNTIME_API PresentPassBuilder { public: friend class RenderGraph; PresentPassBuilder& set_name(const char* name) SKR_NOEXCEPT; PresentPassBuilder& swapchain(CGPUSwapChainId chain, uint32_t idnex) SKR_NOEXCEPT; PresentPassBuilder& texture(TextureHandle texture, bool is_backbuffer = true) SKR_NOEXCEPT; protected: PresentPassBuilder(RenderGraph& graph, PresentPassNode& present) noexcept; RenderGraph& graph; PresentPassNode& node; }; using PresentPassSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::PresentPassBuilder&)>; PassHandle add_present_pass(const PresentPassSetupFunction& setup) SKR_NOEXCEPT; class RUNTIME_API BufferBuilder { public: friend class RenderGraph; BufferBuilder& set_name(const char* name) SKR_NOEXCEPT; BufferBuilder& import(CGPUBufferId buffer, ECGPUResourceState init_state) SKR_NOEXCEPT; BufferBuilder& owns_memory() SKR_NOEXCEPT; BufferBuilder& structured(uint64_t first_element, uint64_t element_count, uint64_t element_stride) SKR_NOEXCEPT; BufferBuilder& size(uint64_t size) SKR_NOEXCEPT; BufferBuilder& with_flags(CGPUBufferCreationFlags flags) SKR_NOEXCEPT; BufferBuilder& memory_usage(ECGPUMemoryUsage mem_usage) SKR_NOEXCEPT; BufferBuilder& allow_shader_readwrite() SKR_NOEXCEPT; BufferBuilder& allow_shader_read() SKR_NOEXCEPT; BufferBuilder& as_upload_buffer() SKR_NOEXCEPT; BufferBuilder& as_vertex_buffer() SKR_NOEXCEPT; BufferBuilder& as_index_buffer() SKR_NOEXCEPT; BufferBuilder& prefer_on_device() SKR_NOEXCEPT; BufferBuilder& prefer_on_host() SKR_NOEXCEPT; protected: BufferBuilder(RenderGraph& graph, BufferNode& node) SKR_NOEXCEPT; RenderGraph& graph; BufferNode& node; }; using BufferSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::BufferBuilder&)>; BufferHandle create_buffer(const BufferSetupFunction& setup) SKR_NOEXCEPT; inline BufferHandle get_buffer(const char* name) SKR_NOEXCEPT; const ECGPUResourceState get_lastest_state(const BufferNode* buffer, const PassNode* pending_pass) const SKR_NOEXCEPT; class RUNTIME_API TextureBuilder { public: friend class RenderGraph; TextureBuilder& set_name(const char* name) SKR_NOEXCEPT; TextureBuilder& import(CGPUTextureId texture, ECGPUResourceState init_state) SKR_NOEXCEPT; TextureBuilder& extent(uint32_t width, uint32_t height, uint32_t depth = 1) SKR_NOEXCEPT; TextureBuilder& format(ECGPUFormat format) SKR_NOEXCEPT; TextureBuilder& array(uint32_t size) SKR_NOEXCEPT; TextureBuilder& sample_count(ECGPUSampleCount count) SKR_NOEXCEPT; TextureBuilder& allow_render_target() SKR_NOEXCEPT; TextureBuilder& allow_depth_stencil() SKR_NOEXCEPT; TextureBuilder& allow_readwrite() SKR_NOEXCEPT; TextureBuilder& owns_memory() SKR_NOEXCEPT; TextureBuilder& allow_lone() SKR_NOEXCEPT; protected: TextureBuilder(RenderGraph& graph, TextureNode& node) SKR_NOEXCEPT; RenderGraph& graph; TextureNode& node; CGPUTextureId imported = nullptr; }; using TextureSetupFunction = eastl::function<void(RenderGraph&, class RenderGraph::TextureBuilder&)>; TextureHandle create_texture(const TextureSetupFunction& setup) SKR_NOEXCEPT; TextureHandle get_texture(const char* name) SKR_NOEXCEPT; const ECGPUResourceState get_lastest_state(const TextureNode* texture, const PassNode* pending_pass) const SKR_NOEXCEPT; bool compile() SKR_NOEXCEPT; virtual uint64_t execute(RenderGraphProfiler* profiler = nullptr) SKR_NOEXCEPT; virtual CGPUDeviceId get_backend_device() SKR_NOEXCEPT { return nullptr; } virtual CGPUQueueId get_gfx_queue() SKR_NOEXCEPT { return nullptr; } virtual uint32_t collect_garbage(uint64_t critical_frame) SKR_NOEXCEPT { return collect_texture_garbage(critical_frame) + collect_buffer_garbage(critical_frame); } virtual uint32_t collect_texture_garbage(uint64_t critical_frame) SKR_NOEXCEPT { return 0; } virtual uint32_t collect_buffer_garbage(uint64_t critical_frame) SKR_NOEXCEPT { return 0; } inline BufferNode* resolve(BufferHandle hdl) SKR_NOEXCEPT { return static_cast<BufferNode*>(graph->node_at(hdl)); } inline TextureNode* resolve(TextureHandle hdl) SKR_NOEXCEPT { return static_cast<TextureNode*>(graph->node_at(hdl)); } inline PassNode* resolve(PassHandle hdl) SKR_NOEXCEPT { return static_cast<PassNode*>(graph->node_at(hdl)); } inline uint64_t get_frame_index() const SKR_NOEXCEPT { return frame_index; } inline bool enable_memory_aliasing(bool enabled) SKR_NOEXCEPT { aliasing_enabled = enabled; return aliasing_enabled; } protected: uint32_t foreach_textures(eastl::function<void(TextureNode*)> texture) SKR_NOEXCEPT; uint32_t foreach_writer_passes(TextureHandle texture, eastl::function<void(PassNode* writer, TextureNode* tex, RenderGraphEdge* edge)>) const SKR_NOEXCEPT; uint32_t foreach_reader_passes(TextureHandle texture, eastl::function<void(PassNode* reader, TextureNode* tex, RenderGraphEdge* edge)>) const SKR_NOEXCEPT; uint32_t foreach_writer_passes(BufferHandle buffer, eastl::function<void(PassNode* writer, BufferNode* buf, RenderGraphEdge* edge)>) const SKR_NOEXCEPT; uint32_t foreach_reader_passes(BufferHandle buffer, eastl::function<void(PassNode* reader, BufferNode* buf, RenderGraphEdge* edge)>) const SKR_NOEXCEPT; virtual void initialize() SKR_NOEXCEPT; virtual void finalize() SKR_NOEXCEPT; RenderGraph(const RenderGraphBuilder& builder) SKR_NOEXCEPT; virtual ~RenderGraph() SKR_NOEXCEPT = default; bool aliasing_enabled; uint64_t frame_index = 0; Blackboard blackboard; eastl::unique_ptr<DependencyGraph> graph = eastl::unique_ptr<DependencyGraph>(DependencyGraph::Create()); eastl::vector<PassNode*> passes; eastl::vector<ResourceNode*> resources; eastl::vector<PassNode*> culled_passes; eastl::vector<ResourceNode*> culled_resources; }; using RenderGraphSetupFunction = RenderGraph::RenderGraphSetupFunction; using RenderGraphBuilder = RenderGraph::RenderGraphBuilder; using RenderPassSetupFunction = RenderGraph::RenderPassSetupFunction; using RenderPassBuilder = RenderGraph::RenderPassBuilder; using ComputePassSetupFunction = RenderGraph::ComputePassSetupFunction; using ComputePassBuilder = RenderGraph::ComputePassBuilder; using CopyPassBuilder = RenderGraph::CopyPassBuilder; using PresentPassSetupFunction = RenderGraph::PresentPassSetupFunction; using PresentPassBuilder = RenderGraph::PresentPassBuilder; using TextureSetupFunction = RenderGraph::TextureSetupFunction; using TextureBuilder = RenderGraph::TextureBuilder; using BufferSetupFunction = RenderGraph::BufferSetupFunction; using BufferBuilder = RenderGraph::BufferBuilder; class RUNTIME_API RenderGraphViz { public: static void write_graphviz(RenderGraph& graph, const char* outf) SKR_NOEXCEPT; }; } // namespace render_graph } // namespace skr
50.634328
128
0.767428
[ "vector" ]
e7fb147090b1df121d76eafebf8006db5b1277e6
8,057
cpp
C++
src/main_gui.cpp
eme64/map-editor
36e34e19ddddf96bb585c44ca7758bea152d560c
[ "MIT" ]
null
null
null
src/main_gui.cpp
eme64/map-editor
36e34e19ddddf96bb585c44ca7758bea152d560c
[ "MIT" ]
null
null
null
src/main_gui.cpp
eme64/map-editor
36e34e19ddddf96bb585c44ca7758bea152d560c
[ "MIT" ]
null
null
null
#include "main_gui.hpp" std::vector<std::string> split(const std::string &s, const char separator =',') { std::vector<std::string> res; std::istringstream f(s); std::string tmp; while (getline(f, tmp, separator)) { res.push_back(tmp); } if(s.size()>0 && s[s.size()-1]==separator) {res.push_back("");} return res; } void MapArea::load(const std::string& fileName) { std::cout << "**LOAD**"<< fileName <<"\n"; std::ifstream myfile; myfile.open(fileName); if(!myfile.is_open()) { std::cout << "File cound not be opened! - abort load.\n"; return; } std::stringstream mystream; mystream << myfile.rdbuf(); myfile.close(); std::string str = mystream.str(); std::vector<std::string> lines = split(str, '\n'); int state = 0; // 1: palette, 2: map, 3: cells, 4: datalayer int line = 0; int lastId = -1; // for cells and objects while(line < lines.size()) { std::string &l = lines[line]; if(l.size()==0){line++;continue;} switch(l[0]) { case '#': { // comment - ignore } break; case '@': { // tag - pick state if(l.compare("@palette")==0) { state = 1; paletteArea_->clear(); } else if(l.compare("@map")==0) { paletteArea_->repopulate(); state = 2; } else if(l.compare("@cells")==0) { state = 3; updateLayers(); dataLayerArea_->repopulate(); } else if(l.compare("@datalayer")==0) { state = 4; dataLayerArea_->clear(); dataLayers_.clear(); } else if(l.compare("@objects")==0) { state = 5; resetObjects(); } else { std::cout << "WARNING: did not know " << l << "\n"; return; } } break; default: { switch(state) { case 0: { std::cout << "Before start: " << l << "\n"; break;} case 1: { // palette std::vector<std::string> parts = split(l,','); int id = std::atoi(parts[0].c_str()); std::string name = parts[1]; float r = std::stof(parts[2]); float g = std::stof(parts[3]); float b = std::stof(parts[4]); float a = std::stof(parts[5]); paletteArea_->addItem(id, name, evp::Color(r,g,b,a)); break;} case 2: { // map std::vector<std::string> parts = split(l,','); size_t nc = std::atoi(parts[0].c_str()); float sx = std::stof(parts[1]); float sy = std::stof(parts[2]); vmap->reconfigure(nc,sx,sy); break;} case 3: { // cells if(l[0]=='*') { // push corner: std::vector<std::string> parts = split(l.substr(1),','); float xx = std::stof(parts[0]); float yy = std::stof(parts[1]); auto &c = vmap->cells[lastId]; c.corners.push_back(evp::Point(xx,yy)); } else if(l[0]=='-') { // neighbor list: std::vector<std::string> parts = split(l.substr(1),','); auto &c = vmap->cells[lastId]; for(auto &n : parts) { c.neighbors.push_back(std::atoi(n.c_str())); } } else if(l[0]=='&') { std::vector<std::string> parts = split(l.substr(1),','); int lid = std::atoi(parts[0].c_str()); std::string value = parts[1]; auto &c = vmap->cells[lastId]; dataLayers_[lid][lastId] = value; } else { // init info: std::vector<std::string> parts = split(l,','); lastId = std::atoi(parts[0].c_str()); int pid = std::atoi(parts[1].c_str()); int nc = std::atoi(parts[2].c_str()); int nn = std::atoi(parts[3].c_str()); float xx = std::stof(parts[4]); float yy = std::stof(parts[5]); auto &c = vmap->cells[lastId]; c.info.paletteId = pid; c.info.colFac = 1 - ((float)rand()/(RAND_MAX))*0.2; c.corners.clear(); c.corners.reserve(nc); c.neighbors.clear(); c.neighbors.reserve(nn); c.pos.x = xx; c.pos.y = yy; } break;} case 4: { // datalayer std::vector<std::string> parts = split(l,','); int id = std::atoi(parts[0].c_str()); std::string name = parts[1]; float r = std::stof(parts[2]); float g = std::stof(parts[3]); float b = std::stof(parts[4]); float a = std::stof(parts[5]); int isShow = std::atoi(parts[6].c_str()); int isEdit = std::atoi(parts[7].c_str()); std::string value = parts[8]; dataLayerArea_->addItem(id, name, evp::Color(r,g,b,a),isShow,isEdit,value); break;} case 5: { // objects if(l[0]=='-') { std::vector<std::string> parts = split(l.substr(1),','); Object* o = objectListArea_->object(lastId); std::string key = parts[0]; std::string val = parts[1]; o->dict[key] = val; } else { std::vector<std::string> parts = split(l,','); int id = std::atoi(parts[0].c_str()); lastId = id; std::string name = parts[1]; float r = std::stof(parts[2]); float g = std::stof(parts[3]); float b = std::stof(parts[4]); float a = std::stof(parts[5]); float x = std::stof(parts[6]); float y = std::stof(parts[7]); objectListArea_->addItem(id,name,evp::Color(r,g,b,a),x,y); } break;} default: { std::cout << "Default state: " << l << "\n"; break;} } } } line++; } mapColorize();// update map colors } void PaletteArea::save(std::ofstream &myfile) { myfile << "@palette\n"; myfile << "#id,name,r,g,b,a\n"; for(auto it : pname) { myfile << it.first <<","<<it.second<<","; evp::Color c = pcolor[it.first]; myfile << c.r << "," << c.g << "," << c.b << "," << c.a << "\n"; } } void DataLayerArea::save(std::ofstream &myfile) { myfile << "@datalayer\n"; myfile << "#id,name,r,g,b,a,isShow,isEdit,defaultValue\n"; for(auto it : lname) { myfile << it.first <<","<<it.second<<","; evp::Color c = lcolor[it.first]; myfile << c.r << "," << c.g << "," << c.b << "," << c.a << ","; myfile << (int)lshow[it.first] << ","; myfile << (int)ledit[it.first] << ","; myfile << lvalue[it.first] << "\n"; } } void ObjectListArea::save(std::ofstream &myfile) { myfile << "@objects\n"; myfile << "#id,namer,g,b,a,x,y\n"; myfile << "#-key,value\n"; for(auto it : objects_) { Object* o = it.second; myfile << it.first <<","<<o->name<<","; evp::Color c = o->color; myfile << c.r << "," << c.g << "," << c.b << "," << c.a << ","; myfile << o->x << ","; myfile << o->y << "\n"; for(std::pair<std::string,std::string> it : o->dict) { myfile << "-" << it.first << "," << it.second << "\n"; } } } void MapArea::save(const std::string& fileName) { std::cout << "**SAVE**"<< fileName <<"\n"; std::ofstream myfile; myfile.open(fileName); paletteArea_->save(myfile); // ------------------------- begin map myfile << "@map\n"; myfile << "#num_cells,spread_x,spread_y\n"; myfile << vmap->num_cells << ","; myfile << vmap->spread_x << ","; myfile << vmap->spread_y << "\n"; dataLayerArea_->save(myfile); myfile << "@cells\n"; myfile << "#id,paletteId,n_corners,n_neighbors,posx,posy\n"; myfile << "# *cornerx,cornery\n"; myfile << "# -neighborlist\n"; myfile << "# &datalayerId,value\n"; for(size_t i = 0; i<vmap->num_cells; i++) { auto &c = vmap->cells[i]; myfile << i << "," << c.info.paletteId << ","; myfile << c.corners.size() << "," << c.neighbors.size() << ","; myfile << c.pos.x << "," << c.pos.y << "\n"; for(int k=0;k<c.corners.size();k++) { myfile << "*" << c.corners[k].x << "," << c.corners[k].y << "\n"; } myfile << "-"; for(int k=0;k<c.neighbors.size();k++) { if(k>0){myfile << ",";} myfile << c.neighbors[k]; } myfile << "\n"; for(auto &it : dataLayers_) { if(it.second[i].size() > 0) { myfile << "&" << it.first << "," << it.second[i] << "\n"; } } } objectListArea_->save(myfile); // ------------------------- close myfile.close(); }
29.512821
81
0.506144
[ "object", "vector" ]
e7fc904dbb22215f67d7da88b4c9091634161054
27,141
cpp
C++
src/ConnectionSTREAM/ConnectionSTREAM.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
src/ConnectionSTREAM/ConnectionSTREAM.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
src/ConnectionSTREAM/ConnectionSTREAM.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
/** @file ConnectionSTREAM.cpp @author Lime Microsystems @brief Implementation of STREAM board connection. */ #include "ConnectionSTREAM.h" #include "ErrorReporting.h" #include <cstring> #include <iostream> #include "Si5351C.h" #include <thread> #include <chrono> using namespace std; #define USB_TIMEOUT 1000 #define HW_LDIGIRED L"DigiRed" #define HW_LDIGIGREEN L"DigiGreen" #define HW_LSTREAMER L"Stream" #define HW_DIGIRED "DigiRed" #define HW_DIGIGREEN "DigiGreen" #define HW_STREAMER "Stream" #define CTR_W_REQCODE 0xC1 #define CTR_W_VALUE 0x0000 #define CTR_W_INDEX 0x0000 #define CTR_R_REQCODE 0xC0 #define CTR_R_VALUE 0x0000 #define CTR_R_INDEX 0x0000 using namespace lime; /** @brief Initializes port type and object necessary to communicate to usb device. */ ConnectionSTREAM::ConnectionSTREAM(void *arg, const unsigned index, const int vid, const int pid) { m_hardwareName = ""; isConnected = false; #ifndef __unix__ USBDevicePrimary = (CCyUSBDevice *)arg; OutCtrEndPt = NULL; InCtrEndPt = NULL; InCtrlEndPt3 = NULL; OutCtrlEndPt3 = NULL; #else dev_handle = 0; devs = 0; ctx = (libusb_context *)arg; #endif if (this->Open(index, vid, pid) != 0) std::cerr << GetLastErrorMessage() << std::endl; DeviceInfo info = this->GetDeviceInfo(); //expected version numbers based on HW number std::string expectedFirmware, expectedGateware = "1"; if (info.hardwareVersion == "1") expectedFirmware = "5"; else if (info.hardwareVersion == "2") expectedFirmware = "0"; else std::cerr << "Unknown hardware version " << info.hardwareVersion << std::endl; //check and warn about firmware mismatch problems if (info.firmwareVersion != expectedFirmware) std::cerr << std::endl << "########################################################" << std::endl << "## !!! Warning: firmware version mismatch !!!" << std::endl << "## Expected firmware version " << expectedFirmware << ", but found version " << info.firmwareVersion << std::endl << "## Follow the FW and FPGA upgrade instructions:" << std::endl << "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl << "########################################################" << std::endl << std::endl; //check and warn about gateware mismatch problems if (info.gatewareVersion != expectedGateware) std::cerr << std::endl << "########################################################" << std::endl << "## !!! Warning: gateware version mismatch !!!" << std::endl << "## Expected gateware version " << expectedGateware << ", but found version " << info.gatewareVersion << std::endl << "## Follow the FW and FPGA upgrade instructions:" << std::endl << "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl << "########################################################" << std::endl << std::endl; //must configure synthesizer before using LimeSDR if (info.deviceName == GetDeviceName(LMS_DEV_LIMESDR)) { std::shared_ptr<Si5351C> si5351module(new Si5351C()); si5351module->Initialize(this); si5351module->SetPLL(0, 25000000, 0); si5351module->SetPLL(1, 25000000, 0); si5351module->SetClock(0, 27000000, true, false); si5351module->SetClock(1, 27000000, true, false); for (int i = 2; i < 8; ++i) si5351module->SetClock(i, 27000000, false, false); Si5351C::Status status = si5351module->ConfigureClocks(); if (status != Si5351C::SUCCESS) { std::cerr << "Warning: Failed to configure Si5351C" << std::endl; return; } status = si5351module->UploadConfiguration(); if (status != Si5351C::SUCCESS) std::cerr << "Warning: Failed to upload Si5351C configuration" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(10)); //some settle time } } /** @brief Closes connection to chip and deallocates used memory. */ ConnectionSTREAM::~ConnectionSTREAM() { mStreamService.reset(); Close(); } /** @brief Tries to open connected USB device and find communication endpoints. @return Returns 0-Success, other-EndPoints not found or device didn't connect. */ int ConnectionSTREAM::Open(const unsigned index, const int vid, const int pid) { #ifndef __unix__ wstring m_hardwareDesc = L""; if( index < USBDevicePrimary->DeviceCount()) { if(USBDevicePrimary->Open(index)) { m_hardwareDesc = USBDevicePrimary->Product; unsigned int pos; //determine connected board type pos = m_hardwareDesc.find(HW_LDIGIRED, 0); if( pos != wstring::npos ) m_hardwareName = HW_DIGIRED; else if (m_hardwareDesc.find(HW_LSTREAMER, 0) != wstring::npos) m_hardwareName = HW_STREAMER; else m_hardwareName = HW_STREAMER; if (InCtrlEndPt3) { delete InCtrlEndPt3; InCtrlEndPt3 = NULL; } InCtrlEndPt3 = new CCyControlEndPoint(*USBDevicePrimary->ControlEndPt); if (OutCtrlEndPt3) { delete OutCtrlEndPt3; OutCtrlEndPt3 = NULL; } OutCtrlEndPt3 = new CCyControlEndPoint(*USBDevicePrimary->ControlEndPt); InCtrlEndPt3->ReqCode = CTR_R_REQCODE; InCtrlEndPt3->Value = CTR_R_VALUE; InCtrlEndPt3->Index = CTR_R_INDEX; OutCtrlEndPt3->ReqCode = CTR_W_REQCODE; OutCtrlEndPt3->Value = CTR_W_VALUE; OutCtrlEndPt3->Index = CTR_W_INDEX; for (int i=0; i<USBDevicePrimary->EndPointCount(); i++) if(USBDevicePrimary->EndPoints[i]->Address == 0x01) { OutEndPt = USBDevicePrimary->EndPoints[i]; long len = OutEndPt->MaxPktSize * 64; OutEndPt->SetXferSize(len); break; } for (int i=0; i<USBDevicePrimary->EndPointCount(); i++) if(USBDevicePrimary->EndPoints[i]->Address == 0x81) { InEndPt = USBDevicePrimary->EndPoints[i]; long len = InEndPt->MaxPktSize * 64; InEndPt->SetXferSize(len); break; } isConnected = true; return 0; } //successfully opened device } //if has devices return ReportError("No matching devices found"); #else if( vid == 1204) { if(pid == 34323) { m_hardwareName = HW_DIGIGREEN; } else if(pid == 241) { m_hardwareName = HW_DIGIRED; } } dev_handle = libusb_open_device_with_vid_pid(ctx, vid, pid); if(dev_handle == nullptr) return ReportError("libusb_open failed"); if(libusb_kernel_driver_active(dev_handle, 0) == 1) //find out if kernel driver is attached { printf("Kernel Driver Active\n"); if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it printf("Kernel Driver Detached!\n"); } int r = libusb_claim_interface(dev_handle, 0); //claim interface 0 (the first) of device if(r < 0) { printf("Cannot Claim Interface\n"); return ReportError("Cannot claim interface - %s", libusb_strerror(libusb_error(r))); } printf("Claimed Interface\n"); isConnected = true; return 0; #endif } /** @brief Closes communication to device. */ void ConnectionSTREAM::Close() { #ifndef __unix__ USBDevicePrimary->Close(); InEndPt = NULL; OutEndPt = NULL; if (InCtrlEndPt3) { delete InCtrlEndPt3; InCtrlEndPt3 = NULL; } if (OutCtrlEndPt3) { delete OutCtrlEndPt3; OutCtrlEndPt3 = NULL; } #else if(dev_handle != 0) { libusb_release_interface(dev_handle, 0); libusb_close(dev_handle); dev_handle = 0; } #endif isConnected = false; } /** @brief Returns connection status @return 1-connection open, 0-connection closed. */ bool ConnectionSTREAM::IsOpen() { #ifndef __unix__ return USBDevicePrimary->IsOpen() && isConnected; #else return isConnected; #endif } /** @brief Sends given data buffer to chip through USB port. @param buffer data buffer, must not be longer than 64 bytes. @param length given buffer size. @param timeout_ms timeout limit for operation in milliseconds @return number of bytes sent. */ int ConnectionSTREAM::Write(const unsigned char *buffer, const int length, int timeout_ms) { std::lock_guard<std::mutex> lock(mExtraUsbMutex); long len = length; if(IsOpen()) { unsigned char* wbuffer = new unsigned char[length]; memcpy(wbuffer, buffer, length); if(m_hardwareName == HW_DIGIRED || m_hardwareName == HW_STREAMER) { #ifndef __unix__ if(OutCtrlEndPt3) OutCtrlEndPt3->Write(wbuffer, len); else len = 0; #else len = libusb_control_transfer(dev_handle, LIBUSB_REQUEST_TYPE_VENDOR,CTR_W_REQCODE ,CTR_W_VALUE, CTR_W_INDEX, wbuffer, length, USB_TIMEOUT); #endif } else { #ifndef __unix__ if(OutCtrEndPt) OutCtrEndPt->XferData(wbuffer, len); else len = 0; #else int actual = 0; libusb_bulk_transfer(dev_handle, 0x01, wbuffer, len, &actual, USB_TIMEOUT); len = actual; #endif } delete wbuffer; } else return 0; return len; } /** @brief Reads data coming from the chip through USB port. @param buffer pointer to array where received data will be copied, array must be big enough to fit received data. @param length number of bytes to read from chip. @param timeout_ms timeout limit for operation in milliseconds @return number of bytes received. */ int ConnectionSTREAM::Read(unsigned char *buffer, const int length, int timeout_ms) { std::lock_guard<std::mutex> lock(mExtraUsbMutex); long len = length; if(IsOpen()) { if(m_hardwareName == HW_DIGIRED || m_hardwareName == HW_STREAMER) { #ifndef __unix__ if(InCtrlEndPt3) InCtrlEndPt3->Read(buffer, len); else len = 0; #else len = libusb_control_transfer(dev_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN ,CTR_R_REQCODE ,CTR_R_VALUE, CTR_R_INDEX, buffer, len, USB_TIMEOUT); #endif } else { #ifndef __unix__ if(InCtrEndPt) InCtrEndPt->XferData(buffer, len); else len = 0; #else int actual = 0; libusb_bulk_transfer(dev_handle, 0x81, buffer, len, &actual, USB_TIMEOUT); len = actual; #endif } } return len; } #ifdef __unix__ /** @brief Function for handling libusb callbacks */ void callback_libusbtransfer(libusb_transfer *trans) { USBTransferContext *context = reinterpret_cast<USBTransferContext*>(trans->user_data); switch(trans->status) { case LIBUSB_TRANSFER_CANCELLED: //printf("Transfer %i canceled\n", context->id); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; //context->reset(); break; case LIBUSB_TRANSFER_COMPLETED: //if(trans->actual_length == context->bytesExpected) { context->bytesXfered = trans->actual_length; context->done.store(true); } break; case LIBUSB_TRANSFER_ERROR: printf("TRANSFER ERRRO\n"); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; break; case LIBUSB_TRANSFER_TIMED_OUT: //printf("transfer timed out %i\n", context->id); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; break; case LIBUSB_TRANSFER_OVERFLOW: printf("transfer overflow\n"); break; case LIBUSB_TRANSFER_STALL: printf("transfer stalled\n"); break; case LIBUSB_TRANSFER_NO_DEVICE: printf("transfer no device\n"); break; } context->transferLock.unlock(); context->cv.notify_one(); } #endif /** @brief Starts asynchronous data reading from board @param *buffer buffer where to store received data @param length number of bytes to read @return handle of transfer context */ int ConnectionSTREAM::BeginDataReading(char *buffer, long length) { int i = 0; bool contextFound = false; //find not used context for(i = 0; i<USB_MAX_CONTEXTS; i++) { if(!contexts[i].used) { contextFound = true; break; } } if(!contextFound) { printf("No contexts left for reading data\n"); return -1; } contexts[i].used = true; #ifndef __unix__ if(InEndPt) contexts[i].context = InEndPt->BeginDataXfer((unsigned char*)buffer, length, contexts[i].inOvLap); return i; #else unsigned int Timeout = 500; libusb_transfer *tr = contexts[i].transfer; libusb_fill_bulk_transfer(tr, dev_handle, 0x81, (unsigned char*)buffer, length, callback_libusbtransfer, &contexts[i], Timeout); contexts[i].done = false; contexts[i].bytesXfered = 0; contexts[i].bytesExpected = length; int status = libusb_submit_transfer(tr); if(status != 0) { printf("ERROR BEGIN DATA READING %s\n", libusb_error_name(status)); contexts[i].used = false; return -1; } else contexts[i].transferLock.lock(); #endif return i; } /** @brief Waits for asynchronous data reception @param contextHandle handle of which context data to wait @param timeout_ms number of miliseconds to wait @return 1-data received, 0-data not received */ int ConnectionSTREAM::WaitForReading(int contextHandle, unsigned int timeout_ms) { if(contextHandle >= 0 && contexts[contextHandle].used == true) { int status = 0; #ifndef __unix__ if(InEndPt) status = InEndPt->WaitForXfer(contexts[contextHandle].inOvLap, timeout_ms); return status; #else auto t1 = chrono::high_resolution_clock::now(); auto t2 = chrono::high_resolution_clock::now(); std::unique_lock<std::mutex> lck(contexts[contextHandle].transferLock); while(contexts[contextHandle].done.load() == false && std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() < timeout_ms) { //blocking not to waste CPU contexts[contextHandle].cv.wait(lck); t2 = chrono::high_resolution_clock::now(); } return contexts[contextHandle].done.load() == true; #endif } else return 0; } /** @brief Finishes asynchronous data reading from board @param buffer array where to store received data @param length number of bytes to read, function changes this value to number of bytes actually received @param contextHandle handle of which context to finish @return false failure, true number of bytes received */ int ConnectionSTREAM::FinishDataReading(char *buffer, long &length, int contextHandle) { if(contextHandle >= 0 && contexts[contextHandle].used == true) { #ifndef __unix__ int status = 0; if(InEndPt) status = InEndPt->FinishDataXfer((unsigned char*)buffer, length, contexts[contextHandle].inOvLap, contexts[contextHandle].context); contexts[contextHandle].used = false; contexts[contextHandle].reset(); return length; #else length = contexts[contextHandle].bytesXfered; contexts[contextHandle].used = false; contexts[contextHandle].reset(); return length; #endif } else return 0; } int ConnectionSTREAM::ReadDataBlocking(char *buffer, long &length, int timeout_ms) { #ifndef __unix__ return InEndPt->XferData((unsigned char*)buffer, length); #else return 0; #endif } /** @brief Aborts reading operations */ void ConnectionSTREAM::AbortReading() { #ifndef __unix__ InEndPt->Abort(); #else for(int i=0; i<USB_MAX_CONTEXTS; ++i) { if(contexts[i].used) libusb_cancel_transfer( contexts[i].transfer ); } #endif } /** @brief Starts asynchronous data Sending to board @param *buffer buffer to send @param length number of bytes to send @return handle of transfer context */ int ConnectionSTREAM::BeginDataSending(const char *buffer, long length) { int i = 0; //find not used context bool contextFound = false; for(i = 0; i<USB_MAX_CONTEXTS; i++) { if(!contextsToSend[i].used) { contextFound = true; break; } } if(!contextFound) return -1; contextsToSend[i].used = true; #ifndef __unix__ if(OutEndPt) contextsToSend[i].context = OutEndPt->BeginDataXfer((unsigned char*)buffer, length, contextsToSend[i].inOvLap); return i; #else unsigned int Timeout = 500; libusb_transfer *tr = contextsToSend[i].transfer; libusb_fill_bulk_transfer(tr, dev_handle, 0x1, (unsigned char*)buffer, length, callback_libusbtransfer, &contextsToSend[i], Timeout); contextsToSend[i].done = false; contextsToSend[i].bytesXfered = 0; contextsToSend[i].bytesExpected = length; int status = libusb_submit_transfer(tr); if(status != 0) { printf("ERROR BEGIN DATA SENDING %s\n", libusb_error_name(status)); contextsToSend[i].used = false; return -1; } else contextsToSend[i].transferLock.lock(); #endif return i; } /** @brief Waits for asynchronous data sending @param contextHandle handle of which context data to wait @param timeout_ms number of miliseconds to wait @return 1-data received, 0-data not received */ int ConnectionSTREAM::WaitForSending(int contextHandle, unsigned int timeout_ms) { if( contextsToSend[contextHandle].used == true ) { #ifndef __unix__ int status = 0; if(OutEndPt) status = OutEndPt->WaitForXfer(contextsToSend[contextHandle].inOvLap, timeout_ms); return status; #else auto t1 = chrono::high_resolution_clock::now(); auto t2 = chrono::high_resolution_clock::now(); std::unique_lock<std::mutex> lck(contextsToSend[contextHandle].transferLock); while(contextsToSend[contextHandle].done.load() == false && std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() < timeout_ms) { //blocking not to waste CPU contextsToSend[contextHandle].cv.wait(lck); t2 = chrono::high_resolution_clock::now(); } return contextsToSend[contextHandle].done == true; #endif } else return 0; } /** @brief Finishes asynchronous data sending to board @param buffer array where to store received data @param length number of bytes to read, function changes this value to number of bytes acctually received @param contextHandle handle of which context to finish @return false failure, true number of bytes sent */ int ConnectionSTREAM::FinishDataSending(const char *buffer, long &length, int contextHandle) { if( contextsToSend[contextHandle].used == true) { #ifndef __unix__ if(OutEndPt) OutEndPt->FinishDataXfer((unsigned char*)buffer, length, contextsToSend[contextHandle].inOvLap, contextsToSend[contextHandle].context); contextsToSend[contextHandle].used = false; contextsToSend[contextHandle].reset(); return length; #else length = contextsToSend[contextHandle].bytesXfered; contextsToSend[contextHandle].used = false; contextsToSend[contextHandle].reset(); return length; #endif } else return 0; } /** @brief Aborts sending operations */ void ConnectionSTREAM::AbortSending() { #ifndef __unix__ OutEndPt->Abort(); #else for (int i = 0; i<USB_MAX_CONTEXTS; ++i) { if(contextsToSend[i].used) libusb_cancel_transfer(contextsToSend[i].transfer); } #endif } /** @brief Configures Stream board FPGA clocks to Limelight interface @param tx Rx/Tx selection @param InterfaceClk_Hz Limelight interface frequency @param phaseShift_deg IQ phase shift in degrees @return 0-success, other-failure */ int ConnectionSTREAM::ConfigureFPGA_PLL(unsigned int pllIndex, const double interfaceClk_Hz, const double phaseShift_deg) { eLMS_DEV boardType = GetDeviceInfo().deviceName == GetDeviceName(LMS_DEV_QSPARK) ? LMS_DEV_QSPARK : LMS_DEV_UNKNOWN; const uint16_t busyAddr = 0x0021; if(IsOpen() == false) return ReportError(ENODEV, "ConnectionSTREAM: configure FPGA PLL, device not connected"); uint16_t drct_clk_ctrl_0005 = 0; ReadRegister(0x0005, drct_clk_ctrl_0005); if(interfaceClk_Hz < 5e6) { //enable direct clocking WriteRegister(0x0005, drct_clk_ctrl_0005 | (1 << pllIndex)); uint16_t drct_clk_ctrl_0006; ReadRegister(0x0006, drct_clk_ctrl_0006); drct_clk_ctrl_0006 = drct_clk_ctrl_0006 & ~0x3FF; const int cnt_ind = 1 << 5; const int clk_ind = pllIndex; drct_clk_ctrl_0006 = drct_clk_ctrl_0006 | cnt_ind | clk_ind; WriteRegister(0x0006, drct_clk_ctrl_0006); const uint16_t phase_reg_sel_addr = 0x0004; float inputClock_Hz = interfaceClk_Hz; const float oversampleClock_Hz = 100e6; const int registerChainSize = 128; const float phaseShift_deg = 90; const float oversampleClock_ns = 1e9 / oversampleClock_Hz; const float phaseStep_deg = 360 * oversampleClock_ns*(1e-9) / (1 / inputClock_Hz); uint16_t phase_reg_select = (phaseShift_deg / phaseStep_deg)+0.5; const float actualPhaseShift_deg = 360 * inputClock_Hz / (1 / (phase_reg_select * oversampleClock_ns*1e-9)); #ifndef NDEBUG printf("reg value : %i\n", phase_reg_select); printf("input clock: %f\n", inputClock_Hz); printf("phase : %.2f/%.2f\n", phaseShift_deg, actualPhaseShift_deg); #endif if(WriteRegister(phase_reg_sel_addr, phase_reg_select) != 0) return ReportError(EIO, "ConnectionSTREAM: configure FPGA PLL, failed to write registers"); const uint16_t LOAD_PH_REG = 1 << 10; WriteRegister(0x0006, drct_clk_ctrl_0006 | LOAD_PH_REG); WriteRegister(0x0006, drct_clk_ctrl_0006); return 0; } //if interface frequency >= 5MHz, configure PLLs WriteRegister(0x0005, drct_clk_ctrl_0005 & ~(1 << pllIndex)); //select FPGA index pllIndex = pllIndex & 0x1F; uint16_t reg23val = 0; if(ReadRegister(0x0003, reg23val) != 0) return ReportError(ENODEV, "ConnectionSTREAM: configure FPGA PLL, failed to read register"); const uint16_t PLLCFG_START = 0x1; const uint16_t PHCFG_START = 0x2; const uint16_t PLLRST_START = 0x4; const uint16_t PHCFG_UPDN = 1 << 13; reg23val &= 0x1F << 3; //clear PLL index reg23val &= ~PLLCFG_START; //clear PLLCFG_START reg23val &= ~PHCFG_START; //clear PHCFG reg23val &= ~PLLRST_START; //clear PLL reset reg23val &= ~PHCFG_UPDN; //clear PHCFG_UpDn reg23val |= pllIndex << 3; uint16_t statusReg; bool done = false; uint8_t errorCode = 0; vector<uint32_t> addrs; vector<uint32_t> values; addrs.push_back(0x0023); values.push_back(reg23val); //PLL_IND addrs.push_back(0x0023); values.push_back(reg23val | PLLRST_START); //PLLRST_START WriteRegisters(addrs.data(), values.data(), values.size()); if(boardType == LMS_DEV_QSPARK) do //wait for reset to activate { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "ConnectionSTREAM: error resetting PLL"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PLLRST_START); //configure FPGA PLLs const float vcoLimits_MHz[2] = { 600, 1300 }; int M, C; const short bufSize = 64; float fOut_MHz = interfaceClk_Hz / 1e6; float coef = 0.8*vcoLimits_MHz[1] / fOut_MHz; M = C = (int)coef; int chigh = (((int)coef) / 2) + ((int)(coef) % 2); int clow = ((int)coef) / 2; addrs.clear(); values.clear(); if(interfaceClk_Hz*M/1e6 > vcoLimits_MHz[0] && interfaceClk_Hz*M/1e6 < vcoLimits_MHz[1]) { //bypass N addrs.push_back(0x0026); values.push_back(0x0001 | (M % 2 ? 0x8 : 0)); addrs.push_back(0x0027); values.push_back(0x5550 | (C % 2 ? 0xA : 0)); //bypass c7-c1 addrs.push_back(0x0028); values.push_back(0x5555); //bypass c15-c8 addrs.push_back(0x002A); values.push_back(0x0101); //N_high_cnt, N_low_cnt addrs.push_back(0x002B); values.push_back(chigh << 8 | clow); //M_high_cnt, M_low_cnt for(int i = 0; i <= 1; ++i) { addrs.push_back(0x002E + i); values.push_back(chigh << 8 | clow); // ci_high_cnt, ci_low_cnt } float Fstep_us = 1 / (8 * fOut_MHz*C); float Fstep_deg = (360 * Fstep_us) / (1 / fOut_MHz); short nSteps = phaseShift_deg / Fstep_deg; addrs.push_back(0x0024); values.push_back(nSteps); addrs.push_back(0x0023); int cnt_ind = 0x3 & 0x1F; reg23val = reg23val | PHCFG_UPDN | (cnt_ind << 8); values.push_back(reg23val); //PHCFG_UpDn, CNT_IND addrs.push_back(0x0023); values.push_back(reg23val | PLLCFG_START); //PLLCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "ConnectionSTREAM: configure FPGA PLL, failed to write registers"); if(boardType == LMS_DEV_QSPARK) do //wait for config to activate { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "ConnectionSTREAM: error configuring PLLCFG"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PLLCFG_START); //PLLCFG_START addrs.push_back(0x0023); values.push_back(reg23val | PHCFG_START); //PHCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "ConnectionSTREAM: configure FPGA PLL, failed to write registers"); if(boardType == LMS_DEV_QSPARK) do { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "ConnectionSTREAM: error configuring PHCFG"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PHCFG_START); //PHCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "ConnectionSTREAM: configure FPGA PLL, failed to write registers"); return 0; } return ReportError(ERANGE, "ConnectionSTREAM: configure FPGA PLL, desired frequency out of range"); }
32.387828
170
0.645813
[ "object", "vector" ]
e7fde27ec5aededbc9da5a2d8729b9a5e6fc6d21
2,034
cpp
C++
lib/cpp/kmp/main.cpp
palash24/algorithms
0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859
[ "MIT" ]
113
2016-09-13T13:39:08.000Z
2021-12-26T09:02:18.000Z
lib/cpp/kmp/main.cpp
palash24/algorithms
0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859
[ "MIT" ]
null
null
null
lib/cpp/kmp/main.cpp
palash24/algorithms
0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859
[ "MIT" ]
49
2016-08-27T07:55:25.000Z
2022-03-17T15:54:18.000Z
#include <vector> #include <iterator> #include <cassert> #include <iostream> // // Copy wrapper around std::advance // template<typename Iterator, typename Distance> Iterator offset(Iterator it, Distance dist) { std::advance(it, dist); return it; } // // Generic KMP iterator based algorithm. Returns a table F where each F[i] // represents the longest proper suffix of S[0...i] that is also a prefix of // S[0...i] where S = [begin, end). // template<typename Iterator> std::vector<int> kmp(Iterator begin, Iterator end) { // Setup table and base case. std::vector<int> F(std::distance(begin, end)); F[0] = 0; // Setup iterator and track the index/distance we are from start of // sequence. Iterator it = next(begin); int i = 1; while (it != end) { int j = F[i - 1]; Iterator jIt = offset(begin, j); while (j > 0 && *jIt != *it) { j = F[j - 1]; jIt = offset(begin, j); } if (*jIt == *it) { j++; } F[i] = j; it++; i++; } return F; } // // Returns indexes in T where full occurences of P begin. // std::vector<size_t> find(const std::string& P, const std::string& T, char separator = '#') { std::string S = P + std::string(1, separator) + T; std::vector<int> F = kmp(S.begin(), S.end()); std::vector<size_t> index; for (size_t i = 0; i < F.size(); i++) { if (F[i] == static_cast<int>(P.size())) { index.push_back(i - 2 * P.size()); } } return index; } int main() { assert(find("a", "a") == std::vector<size_t>({0})); assert(find("sda", "sadasda") == std::vector<size_t>({4})); assert(find("rishi", "rishrisrishirishirishrishiririshi") == std::vector<size_t>({7, 12, 21, 28})); assert(find("aa", "aaaa") == std::vector<size_t>({0, 1, 2})); assert(find("AABA", "AABAACAADAABAABA") == std::vector<size_t>({0, 9, 12})); assert(find("TEST", "THIS IS A TEST TEXT") == std::vector<size_t>({10})); std::cout << "Tests pass!" << std::endl; return 0; }
23.651163
78
0.573255
[ "vector" ]
f012f6a4c9e8c673c2ff39c5e89cb9b1fc9e3844
956
cpp
C++
Section 1.1/Greedy Gift Givers/gift1.cpp
memset0x3f/usaco
9b3029e33afa441b823ac2c75eabb0ccdae70b0d
[ "MIT" ]
14
2016-05-12T12:19:33.000Z
2021-12-12T02:39:54.000Z
Section 1.1/Greedy Gift Givers/gift1.cpp
akommula/usaco
9b3029e33afa441b823ac2c75eabb0ccdae70b0d
[ "MIT" ]
null
null
null
Section 1.1/Greedy Gift Givers/gift1.cpp
akommula/usaco
9b3029e33afa441b823ac2c75eabb0ccdae70b0d
[ "MIT" ]
18
2017-04-23T01:29:44.000Z
2022-03-20T03:45:53.000Z
/* ID: cloudzf2 PROG: gift1 LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <unordered_map> #include <cstring> #include <vector> using namespace std; int main(int argc, const char * argv[]) { ifstream fin ("gift1.in"); ofstream fout ("gift1.out"); int np, money, ng; fin >> np; unordered_map<string, int> m; vector<string> name(np); for (int i = 0; i < np; i++) { fin >> name[i]; m[name[i]] = 0; } string giver, givee; for (int i = 0; i < np; i++) { fin >> giver; fin >> money >> ng; m[giver] -= money; if (ng == 0) continue; int tmp = money / ng; for (int j = 0; j < ng; j++) { fin >> givee; m[givee] += tmp; money -= tmp; } m[giver] += money; } for (int i = 0; i < np; i++) { fout << name[i] << " " << m[name[i]] <<endl; } return 0; }
20.782609
52
0.471757
[ "vector" ]
f0181349bcbc68fb16c06015e63f9f784888dcdd
6,304
cpp
C++
FileFormats/Blend/ftBlend.cpp
snailrose/FileTools
c2d904806464d00518e28724e1828730f4f93340
[ "MIT" ]
null
null
null
FileFormats/Blend/ftBlend.cpp
snailrose/FileTools
c2d904806464d00518e28724e1828730f4f93340
[ "MIT" ]
null
null
null
FileFormats/Blend/ftBlend.cpp
snailrose/FileTools
c2d904806464d00518e28724e1828730f4f93340
[ "MIT" ]
null
null
null
/* ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "ftBlend.h" #include "ftStreams.h" #include "ftTable.h" const SKuint32 GLOB = FT_TYPEID('G', 'L', 'O', 'B'); struct ftIdDB { const SKuint16 code; ftList ftBlend::*ptr; const SKsize integrityCheck; }; const ftIdDB ftData[] = { { FT_TYPEID2('S', 'C'), &ftBlend::m_scene, sizeof(Blender::Scene), }, { FT_TYPEID2('L', 'I'), &ftBlend::m_library, sizeof(Blender::Library), }, { FT_TYPEID2('O', 'B'), &ftBlend::m_object, sizeof(Blender::Object), }, { FT_TYPEID2('M', 'E'), &ftBlend::m_mesh, sizeof(Blender::Mesh), }, { FT_TYPEID2('C', 'U'), &ftBlend::m_curve, sizeof(Blender::Curve), }, { FT_TYPEID2('M', 'B'), &ftBlend::m_mball, sizeof(Blender::MetaBall), }, { FT_TYPEID2('M', 'A'), &ftBlend::m_mat, sizeof(Blender::Material), }, { FT_TYPEID2('T', 'E'), &ftBlend::m_tex, sizeof(Blender::Tex), }, { FT_TYPEID2('I', 'M'), &ftBlend::m_image, sizeof(Blender::Image), }, { FT_TYPEID2('L', 'T'), &ftBlend::m_latt, sizeof(Blender::Lattice), }, { FT_TYPEID2('L', 'A'), &ftBlend::m_lamp, sizeof(Blender::Lamp), }, { FT_TYPEID2('C', 'A'), &ftBlend::m_camera, sizeof(Blender::Camera), }, { FT_TYPEID2('I', 'P'), &ftBlend::m_ipo, sizeof(Blender::Ipo), }, { FT_TYPEID2('K', 'E'), &ftBlend::m_key, sizeof(Blender::Key), }, { FT_TYPEID2('W', 'O'), &ftBlend::m_world, sizeof(Blender::World), }, { FT_TYPEID2('S', 'N'), &ftBlend::m_screen, sizeof(Blender::bScreen), }, { FT_TYPEID2('P', 'Y'), &ftBlend::m_script, sizeof(Blender::Script), }, { FT_TYPEID2('V', 'F'), &ftBlend::m_vfont, sizeof(Blender::VFont), }, { FT_TYPEID2('T', 'X'), &ftBlend::m_text, sizeof(Blender::Text), }, { FT_TYPEID2('S', 'O'), &ftBlend::m_sound, sizeof(Blender::bSound), }, { FT_TYPEID2('G', 'R'), &ftBlend::m_group, SK_NPOS, // Id struct ? }, { FT_TYPEID2('A', 'R'), &ftBlend::m_armature, sizeof(Blender::bArmature), }, { FT_TYPEID2('A', 'C'), &ftBlend::m_action, sizeof(Blender::bAction), }, { FT_TYPEID2('N', 'T'), &ftBlend::m_nodetree, sizeof(Blender::bNodeTree), }, { FT_TYPEID2('B', 'R'), &ftBlend::m_brush, sizeof(Blender::Brush), }, { FT_TYPEID2('P', 'A'), &ftBlend::m_particle, SK_NPOS, // Id struct ? }, { FT_TYPEID2('G', 'D'), &ftBlend::m_gpencil, SK_NPOS, // Id struct ? }, { FT_TYPEID2('W', 'M'), &ftBlend::m_wm, sizeof(Blender::wmWindowManager), }, { 0, nullptr, SK_NPOS, }, }; ftBlend::ftBlend() : ftFile("BLENDER"), m_fg() { } ftBlend::~ftBlend() = default; int ftBlend::notifyDataRead(void* pointer, const SKsize sizeInBytes, const ftChunk& chunk) { if (!pointer) return 0; if (chunk.code == GLOB) { if (sizeInBytes == sizeof(Blender::FileGlobal)) { m_fg = (Blender::FileGlobal*)pointer; return ftFlags::FS_OK; } // it's not safe to cast this data return ftFlags::FS_INTEGRITY_FAIL; } if (chunk.code <= 0xFFFF) { int i = 0; while (ftData[i].code != 0) { if (ftData[i].code == chunk.code) { if (ftData[i].integrityCheck == SK_NPOS) break; if (ftData[i].integrityCheck == sizeInBytes) { (this->*ftData[i].ptr).pushBack(pointer); return ftFlags::FS_OK; } return ftFlags::FS_INTEGRITY_FAIL; } ++i; } } // Ok here just means it was not processed return ftFlags::FS_OK; } int ftBlend::serializeData(skStream* stream) { for (ftMemoryChunk* node = (ftMemoryChunk*)m_chunks.first; node; node = node->next) { if (node->newTypeId > m_memory->getNumberOfTypes()) continue; if (!node->memoryBlock) continue; void* wd = node->memoryBlock; ftChunk ch{}; ch.code = node->chunk.code; ch.count = node->chunk.count; ch.length = node->chunk.length; ch.structId = node->newTypeId; ch.address = (SKsize)wd; stream->write(&ch, sizeof(ftChunk)); stream->write(wd, ch.length); } return ftFlags::FS_OK; } int ftBlend::save(const char* path, const int mode) { m_memoryVersion = m_fileVersion; return ftFile::save(path, mode); } #include "bfBlender.inl" void* ftBlend::getTables(void) { return (void*)bfBlenderTable; } SKsize ftBlend::getTableSize(void) { return bfBlenderLen; }
22.676259
90
0.509042
[ "mesh", "object" ]
f01cb073940637721e3a911db95784d4248e565b
1,099
hpp
C++
src/imgui/imguiWrapper/dropDown.hpp
sousajo-cc/cash_overflow
2bad3b403b4fcd04d72b2ae871ec55756a387b0e
[ "Unlicense" ]
2
2021-11-02T18:06:43.000Z
2021-11-05T19:07:47.000Z
src/imgui/imguiWrapper/dropDown.hpp
sousajo-cc/cash_overflow
2bad3b403b4fcd04d72b2ae871ec55756a387b0e
[ "Unlicense" ]
34
2021-11-03T09:55:41.000Z
2021-12-17T11:14:52.000Z
src/imgui/imguiWrapper/dropDown.hpp
sousajf1/cash_overflow
2bad3b403b4fcd04d72b2ae871ec55756a387b0e
[ "Unlicense" ]
null
null
null
#ifndef CASH_OVERFLOW_DROPDOWN_HPP #define CASH_OVERFLOW_DROPDOWN_HPP #include <imgui.h> #include <vector> #include <string> #include <iostream> namespace cash_overflow::gui { class DropDown { public: DropDown(std::vector<std::string> options, std::string currentSelectedCategoryType) : options_(std::move(options)), currentSelectedItem(std::move(currentSelectedCategoryType)) { } std::string draw() { if (ImGui::BeginCombo("##combo", currentSelectedItem.c_str())) { for (auto const &option : options_) { bool isSelected = (currentSelectedItem == option); if (ImGui::Selectable(option.c_str(), isSelected)) { currentSelectedItem = option.c_str(); } if (isSelected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } return currentSelectedItem; } private: std::vector<std::string> options_; std::string currentSelectedItem; }; }// namespace cash_overflow::gui #endif// CASH_OVERFLOW_DROPDOWN_HPP
26.804878
147
0.626934
[ "vector" ]
f01d8a64ce6d8933e9fee5b6015e6688dba2ae8f
2,299
cpp
C++
aashishgahlawat/codeforces/B/611-B/611-B-32078711.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/B/611-B/611-B-32078711.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/B/611-B/611-B-32078711.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
#include<iostream> #include<math.h> #include<algorithm> #include<bitset> #include<deque> #include<map> #include<queue> #include<set> #include<stack> #include<string> #include<cstring> #include<vector> #include<string.h> #include<stdlib.h> #include<stdio.h> using namespace std; unsigned long long d[60]; int main() { unsigned long long a,b,ans=0; cin>>a>>b; d[0]=1; for(int i=1;i<=60;i++) { d[i]=d[i-1]*2; } for(int i=60;i>=1;i--) { for(int j=i-2;j>=0;j--) { unsigned long long c=d[i]-1-d[j]; if(c<=b && c>=a) { ans++; } } } cout<<ans; return 0; } /* #include <iostream> #include <bits/stdc++.h> #include <math.h> #define endl '\n' #define ll long long int #define pb push_back #define mp make_pair using namespace std; void fillPowOfTwo(); long long int powOfTwo[61]; long long int OnesDP[61]; int result[61]; long long int startPoint,endPoint; void calculate(); int findIfAny(long long int x); int findStart(long long startPoint){ for(int i=1;i<=60;i++){ if(powOfTwo[i]>startPoint) return i; } return 0; } int findEnd(long long int endPoint){ for(int i=1;i<=60;i++){ if(powOfTwo[i]>endPoint) return i; } return 0; } int main() { ios_base::sync_with_stdio(false); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); // aashish gahlawat fillPowOfTwo(); cin>>startPoint>>endPoint; calculate(); for(int i=1;i<=60;i++) cout<<result[i]<<" "; int i=findStart(startPoint); int j=findEnd(endPoint); int final=result[j-1]- result[i-1]; cout<<endl<<final; cout<<endl<<i<<" "<<result[i]<<" start"<<" "<<j<<" "<<result[j]<<" end"; return 0; } void fillPowOfTwo(){ for(int i=1;i<=60;i++){ powOfTwo[i]=pow(2,i); OnesDP[i]=powOfTwo[i]-1; } } void calculate(){ long long int current; for(int i=1;i<=60;i++){ int ans=0; for(int j=1;j<=i;j++){ current=OnesDP[i] - powOfTwo[j]; if(current>0){ ans+=findIfAny(current); } } result[i]+=ans+result[i-1]; } } int findIfAny(long long int number){ int currentZeros=0; while(number!=0){ if(number%2==0) currentZeros++; if(currentZeros>1) return 0; number/=2; } if(currentZeros==1) return 1; return 0; } */
19.483051
73
0.589387
[ "vector" ]
f024bf67c405f6e3f3bece434716bd8dee1ffe4f
7,121
cpp
C++
iris/iris/base/Light.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/iris/base/Light.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/iris/base/Light.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
#include "base\Light.h" #include "base\Scene.h" #include "base\Director.h" #include "base\Transform.h" #include "platform\PlatformGL.h" #include "base\Camera.h" #include "base\Transform.h" #include "base\Shader.h" #include "math\Matrix4x4.h" IRIS_BEGIN Light::Light() : m_lightType(LightType::DIRECTIONAL_LIGHT) , m_color(Color::WHITE) , m_range(1.0f) , m_intensity(1.0f) , m_spotAngle(20.0f) , m_spotAngleInner(25.0f) , m_spotAngleOuter(30.0f) , m_ambientStrength(0.05f) , m_specularStrength(32.0f) , m_specularColor(Color::WHITE) //, m_projectionMatrix(Matrix4x4::IDENTITY) { m_name = "light_component"; } Light::~Light() { } Light *Light::create() { Light *light = new (std::nothrow) Light(); if(light) { light->awake(); light->autorelease(); return light; } SAFE_DELETE(light); return nullptr; } Light *Light::createWithType(LightType p_lightType) { Light *light = new (std::nothrow) Light(); if(light && light->initWithType(p_lightType)) { light->awake(); light->autorelease(); return light; } SAFE_DELETE(light); return nullptr; } bool Light::initWithType(LightType p_lightType) { setLightType(p_lightType); //m_projectionMatrix = setOrthographicFrustum(-10.0f, 10.0f, -10.0f, 10.0f, 1.0f, 100.0f); return true; } void Light::onEnable() { Component::onEnable(); // We always make sure that this light is added to our scene's light component list Scene* currentScene = IRIS_DIRECTOR.getCurrentScene(); //if(currentScene) //{ // currentScene->addLightObject(m_gameObject); //} } void Light::onDisable() { Component::onDisable(); // We always make sure that this light is added to our scene's light component list Scene* currentScene = IRIS_DIRECTOR.getCurrentScene(); //if(currentScene) //{ // currentScene->removeLightObject(m_gameObject); //} } LightType Light::getLightType() const { return m_lightType; } void Light::setLightType(LightType p_lightType) { m_lightType = p_lightType; } Color Light::getColor() const { return m_color; } void Light::setColor(Color p_color) { m_color = p_color; } float Light::getRange() const { return m_range; } void Light::setRange(float p_range) { m_range = p_range; } float Light::getSpotAngle() const { return m_spotAngle; } void Light::setSpotAngle(float p_spotAngle) { m_spotAngle = p_spotAngle; m_spotAngleInner = m_spotAngle; m_spotAngleOuter = m_spotAngleInner + 5.0f; } float Light::getSpotAngleInner() const { return m_spotAngleInner; } void Light::setSpotAngleInner(float p_spotAngleInner) { m_spotAngleInner = p_spotAngleInner; } float Light::getSpotAngleOuter() const { return m_spotAngleOuter; } void Light::setSpotAngleOuter(float p_spotAngleOuter) { m_spotAngleOuter = p_spotAngleOuter; } float Light::getIntensity() const { return m_intensity; } void Light::setIntensity(float p_intensity) { m_intensity = p_intensity; } float Light::getAmbientStrength() const { return m_ambientStrength; } void Light::setAmbientStrength(float p_ambientStrength) { m_ambientStrength = p_ambientStrength; } float Light::getSpecularStrength() const { return m_specularStrength; } void Light::setSpecularStrength(float p_specularStrength) { m_specularStrength = p_specularStrength; } Color Light::getSpecularColor() const { return m_specularColor; } void Light::setSpecularColor(Color p_specularColor) { m_specularColor = p_specularColor; } void Light::bindLight(ShaderLightId p_shaderLightId) { #if defined(_USE_EGL) unsigned int lightType = (unsigned int)m_lightType; glUniform1i(p_shaderLightId.type, lightType); //Matrix4x4 viewMatrix = Matrix4x4::IDENTITY; //glUniformMatrix4fv(p_shaderLightId.viewMatrix, 1, false, viewMatrix.get()); //Matrix4x4 projectionMatrix = Matrix4x4::IDENTITY; //glUniformMatrix4fv(p_shaderLightId.projectionMatrix, 1, false, projectionMatrix.get()); //Matrix4x4 lightSpaceMatrix = Matrix4x4::IDENTITY; //glUniformMatrix4fv(p_shaderLightId.lightSpaceMatrix, 1, false, m_lightSpaceMVP.get()); // TODO: Visiting camera? might as well change it to main camera? //Camera* mainCamera = IRIS_DIRECTOR.getCurrentScene()->m_visitingCamera; Camera* mainCamera = NULL; if(mainCamera) { //Matrix4x4 viewMatrix = m_viewMatrix.invert(); //glUniformMatrix4fv(p_shaderLightId.viewMatrix, 1, false, viewMatrix.get()); //Matrix4x4 projectionMatrix = m_projectionMatrix; //glUniformMatrix4fv(p_shaderLightId.projectionMatrix, 1, false, projectionMatrix.get()); //Matrix4x4 biasMatrix = Matrix4x4( // 0.5f, 0.0f, 0.0f, 0.0f, // 0.0f, 0.5f, 0.0f, 0.0f, // 0.0f, 0.0f, 0.5f, 0.0f, // 0.0f, 0.0f, 0.0f, 1.0f //); //Matrix4x4 mvp = biasMatrix * viewMatrix * projectionMatrix; //glUniformMatrix4fv(p_shaderLightId.lightSpaceMatrix, 1, false, mvp.get()); } //else //{ // Matrix4x4 identityMatrix = Matrix4x4::IDENTITY; // glUniformMatrix4fv(shader->m_viewMatrixId, 1, false, identityMatrix.get()); // glUniformMatrix4fv(shader->m_projectionMatrixId, 1, false, identityMatrix.get()); // glUniformMatrix4fv(shader->m_mvpId, 1, false, identityMatrix.get()); // glUniform3fv(shader->m_cameraPositionId, 1, (Vector3f::FORWARD * -10.0f).get()); //} Vector3f position = m_transform->getPosition(); glUniform3fv(p_shaderLightId.position, 1, position.get()); Vector3f direction = m_transform->getLocalModelMatrix().getForward(); glUniform3fv(p_shaderLightId.direction, 1, direction.get()); glUniform4fv(p_shaderLightId.color, 1, m_color.get()); glUniform1f(p_shaderLightId.range, m_range); glUniform1f(p_shaderLightId.intensity, m_intensity); glUniform1f(p_shaderLightId.ambientStrength, m_ambientStrength); glUniform4fv(p_shaderLightId.specularColor, 1, m_specularColor.get()); glUniform1f(p_shaderLightId.specularStrength, m_specularStrength); glUniform1f(p_shaderLightId.spotAngleInner, m_spotAngleInner); glUniform1f(p_shaderLightId.spotAngleOuter, m_spotAngleOuter); #endif } //Matrix4x4 Light::setOrthographicFrustum(float p_left, float p_right, float p_bottom, float p_top, float p_near, float p_far) //{ // Matrix4x4 frustumMatrix; // frustumMatrix[0] = 2.0f / (p_right - p_left); // frustumMatrix[3] = -(p_right + p_left) / (p_right - p_left); // frustumMatrix[5] = 2.0f / (p_top - p_bottom); // frustumMatrix[7] = -(p_top + p_bottom) / (p_top - p_bottom); // frustumMatrix[10] = -2.0f / (p_far - p_near); // frustumMatrix[11] = -(p_far + p_near) / (p_far - p_near); // return frustumMatrix; //} IRIS_END
25.800725
127
0.670552
[ "transform" ]
f02f055927c64e2bb6526ade4ef941141cedeee8
1,191
cpp
C++
src/com/devsda/gargantua/codechef/OctoberCoofOff/2.cpp
devvsda/gargantua
9e41f87d5c73920611bafdfa15047639cb322809
[ "MIT" ]
null
null
null
src/com/devsda/gargantua/codechef/OctoberCoofOff/2.cpp
devvsda/gargantua
9e41f87d5c73920611bafdfa15047639cb322809
[ "MIT" ]
null
null
null
src/com/devsda/gargantua/codechef/OctoberCoofOff/2.cpp
devvsda/gargantua
9e41f87d5c73920611bafdfa15047639cb322809
[ "MIT" ]
null
null
null
//#include<iostream> //#include<vector> //#include<string> #include<stdio.h> using namespace std; int numOfDigits(int val) { int count = 0; while(val) { val /= 10; count++; } return count; } int isMultiple(int val) { int count = 0; while( (val%10 == 0)) { val = val/10; count++; } return count; } main() { int T; int L; int R; long long int answer = 0; long long int currentAnswer; int num; int iter; int newVal; scanf("%d", &T); while(T--) { scanf("%d %d", &L, &R); answer = 0; int i = L; while(i <= R) { num = numOfDigits(i); iter = 10*num - i; newVal = (i+iter-1); if( newVal <= R ) { answer += ( (( (newVal%1000000007)*(newVal+1) ) - ( (i-1)*(i%1000000007) ) )/2)*num; i = newVal+1; } else { answer += ( (((R%1000000007)*(R+1)) - ((i-1)*(i%1000000007)))/2)*num; i = R+1; } } printf("%lld\n", answer); } return 0; }
20.186441
101
0.402183
[ "vector" ]
f031ef1fa55b06d9080dad8e8a1026acd31fb02c
9,969
cpp
C++
src/api/utils/curl/CurlUtils.cpp
bphun/Spotify-Connect-CLI
e389cb50d6e1c35975b36926104a9373d630aa21
[ "MIT" ]
null
null
null
src/api/utils/curl/CurlUtils.cpp
bphun/Spotify-Connect-CLI
e389cb50d6e1c35975b36926104a9373d630aa21
[ "MIT" ]
null
null
null
src/api/utils/curl/CurlUtils.cpp
bphun/Spotify-Connect-CLI
e389cb50d6e1c35975b36926104a9373d630aa21
[ "MIT" ]
null
null
null
#include "CurlUtils.h" CurlUtils::CurlUtils() { curl = curl_easy_init(); } size_t CurlUtils::writeCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } /** * Replaces all instances of a string to a specified string * * @param str String that will be operated on * @param from String that will be removed and replaced with desired string * @param to String replaced with replaced * @return A New string with instances of the undesired pattern are replaced with the specified string * */ std::string CurlUtils::replaceAll(std::string& str, const std::string from, const std::string to) { size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } return str; } /** * Configures a CURL object for communication with the client's remote key file server * * @param curl A CURL object which needs to have options inserted to allow for communcations with the remote key file server * */ void CurlUtils::addKeyServerConfig(CURL* curl) { curl_easy_setopt(curl, CURLOPT_CAINFO, caCertPath); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); isKeyServerRequest = true; } /** * Runs either GET, POST, PUT, or DELETE request with the specifed endpoint, options, URL, and JSON body (usually for POST requests) * * @param request Type of CURL request (GET, POST, PUT, DELETE) * @param endpoint endpoint of the specified URL where the desired data is located * @param options The desired options that you would like to send to the host. Defaults to an empty map * @param authorizationToken The token used by Spotify to authenticate a request. Defaults to an empty string * @param body Data that is sent to the host. Defaults an empty string * @param baseURL URL (Excluding endpoint) that the request will be made to. Defaults to "https://api.spotify.com" * * @return A JSON containing data returned from the request * * @throws CurlException * @throws SpotifyException * */ nlohmann::json CurlUtils::runRequest(std::string request, std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body, std::string baseURL) { #ifdef CLIENT_DEBUG curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); #endif if (!curl) { throw CurlException("Could not initialize cURL"); } std::string url = baseURL + endpoint; if (!options.empty()) { url += "?"; for (auto option : options) { url += option.first + "=" + option.second + "&"; } replaceAll(url, " ", "%20"); } // printf("%s\n", url.c_str()); std::string readBuffer; if (request == "POST") { curl_easy_setopt(curl, CURLOPT_POST, 1L); } curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, request.c_str()); if (!authorizationToken.empty()) { std::string authHeader = "Authorization: Bearer " + authorizationToken; headers = curl_slist_append(headers, authHeader.c_str()); std::string contentLengthHeader = "Content-Length: 0"; headers = curl_slist_append(headers, contentLengthHeader.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); } if (!body.empty()) { curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str()); } // delete headers; int responseCode = curl_easy_perform(curl); if (responseCode != CURLE_OK) { curl = curl_easy_init(); throw CurlException(responseCode); } long statusCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode); // printf("%ld\n", statusCode); if (statusCode < 200 || statusCode > 204) { curl = curl_easy_init(); // printf("%ld\n", statusCode); throw CurlException(statusCode, readBuffer); } curl_easy_cleanup(curl); if (readBuffer.empty()) { curl = curl_easy_init(); return nlohmann::json(); } isKeyServerRequest = false; curl = curl_easy_init(); return nlohmann::json::parse(readBuffer); } /** * Runs a GET request to the Spotify Web API with the specified endpoint * * @param endpoint The endpoint that the request is made to * @param options The desired options that you would like to send to the host. Defaults to an empty map * @param authorizationToken The token used by Spotify to authenticate a request. Defaults to an empty string * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::GET(std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body) { return runRequest("GET", endpoint, options, authorizationToken, body/*, endpoint.find("/static/") == std::string::npos ? "https://api.spotify.com" : "https://localhost:3000"*/); } /** * Runs a GET request to the Spotify Web API, or any desired http server, with the specified endpoint * * @param endpoint The endpoint that the request is made to * @param baseURL The URL that the request is made to * @param options The desired options that you would like to send to the host. Defaults to an empty map * @param authorizationToken The token used by Spotify to authenticate a request. Defaults to an empty string * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::GET(std::string endpoint, std::string baseURL, std::map<std::string, std::string> options, std::string authorizationToken, std::string body) { return runRequest("GET", endpoint, options, authorizationToken, body, baseURL); } /** * Runs a POST request to the Spotify Web API, or any desired http server, with the specified endpoint and body * * @param endpoint The endpoint that the request is made to * @param baseURL URL (Excluding endpoint) that the request will be made to * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::POST(std::string endpoint, std::string baseURL, std::string body) { return runRequest("POST", endpoint, std::map<std::string, std::string>(), "", body, baseURL); } /** * Runs a POST request to the Spotify Web API, or any desired http server, with the specified endpoint and body * * @param endpoint The endpoint that the request is made to * @param options The desired options that you would like to send to the host. Defaults to an empty map * @param authorizationToken The token used by Spotify to authenticate a request. Defaults to an empty string * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::POST(std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body) { return runRequest("POST", endpoint, options, authorizationToken, body); } /** * Runs a POST request to the Spotify Web API, or any desired http server, with the specified endpoint and body * * @param endpoint The endpoint that the request is made to * @param options The desired options that you would like to send to the host * @param authorizationToken The token used by Spotify to authenticate a request * @param body Data that is sent to the host. Defaults an empty string * @param baseURL URL (Excluding endpoint) that the request will be made to * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::POST(std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body, std::string baseURL) { return runRequest("POST", endpoint, options, authorizationToken, body, baseURL); } /** * Runs a PUT request to the Spotify Web API with the specified endpoint and body * * @param endpoint The endpoint that the request is made to * @param options The desired options that you would like to send to the host * @param authorizationToken The token used by Spotify to authenticate a request * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::PUT(std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body) { return runRequest("PUT", endpoint, options, authorizationToken, body); } /** * Runs a DELETE request to the Spotify Web API with the specified endpoint * * @param endpoint The endpoint that the request is made to * @param options The desired options that you would like to send to the host * @param authorizationToken The token used by Spotify to authenticate a request * @param body Data that is sent to the host. Defaults an empty string * * @return A JSON containing data returned from the request * */ nlohmann::json CurlUtils::DELETE(std::string endpoint, std::map<std::string, std::string> options, std::string authorizationToken, std::string body) { return runRequest("DELETE", endpoint, options, authorizationToken, body); } /** * Adds a header to the current instance of cURL, which will then be cleared once * the cURL request is executed. * * @param headerName Name of the header that will be inserted into the upcoming cURL request * @param headerValue Value of the header that will be inserted into the upcoming cURL request. */ void CurlUtils::addHeader(std::string headerName, std::string headerValue) { std::string header = headerName + ": " + headerValue; headers = curl_slist_append(headers, header.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); }
39.559524
197
0.735279
[ "object" ]
f03221f8f28fe978924781c6eb37be66e0839a03
4,905
cpp
C++
examples/ex3/main.cpp
adrianpp/rltk
01bf98fc6abe085d5ffe7beee6f375ef9070101b
[ "MIT" ]
263
2016-03-15T07:39:48.000Z
2022-03-15T10:44:05.000Z
examples/ex3/main.cpp
adrianpp/rltk
01bf98fc6abe085d5ffe7beee6f375ef9070101b
[ "MIT" ]
14
2016-11-04T13:04:25.000Z
2020-01-04T16:06:25.000Z
examples/ex3/main.cpp
adrianpp/rltk
01bf98fc6abe085d5ffe7beee6f375ef9070101b
[ "MIT" ]
30
2016-07-12T10:50:56.000Z
2022-03-02T17:31:49.000Z
/* RLTK (RogueLike Tool Kit) 1.00 * Copyright (c) 2016-Present, Bracket Productions. * Licensed under the MIT license - see LICENSE file. * * Example 3: A wandering @ dude, this time using Bresenham's line functions to * plot his path through the world. We play around a bit, rendering the destination * and path as well as the simple "world" our little @ lives in. */ // You need to include the RLTK header #include "../../rltk/rltk.hpp" // We're using a deque to represent our path #include <deque> // For convenience, import the whole rltk namespace. You may not want to do this // in larger projects, to avoid naming collisions. using namespace rltk; using namespace rltk::colors; // For now, we always want our "dude" to be a yellow @ - so he's constexpr const vchar dude{'@', YELLOW, BLACK}; // We're also going to render our destination as a pink heart. Aww. const vchar destination{3, MAGENTA, BLACK}; // We'll also render our planned path ahead as a series of stars const vchar star{'*', GREEN, BLACK}; // The dude's location in X/Y terms int dude_x = 10; int dude_y = 10; // Where the dude would like to go; we'll start with him being happy where he is. int destination_x = 10; int destination_y = 10; // We'll store the path to the goal as a simple queue of x/y (represented as an std::pair of ints). // A queue naturally represents the task - each step, in order. A deque has the added property // of being iteratable - so we are using it. std::deque<std::pair<int,int>> path; // A default-defined random number generator. You can specify a seed to get // the same results each time, but for now we're keeping it simple. random_number_generator rng; // We want to keep the game running at a steady pace, rather than however // fast our super graphics card wants to go! To do this, we set a constant // duration for a "tick" and only process after that much time has elapsed. // Most roguelikes are turn-based and won't actually use this, but that's // for a later example when we get to input. // Note that this is faster than previous examples; I liked it better that way! constexpr double tick_duration = 5.0; double tick_time = 0.0; // Tick is called every frame. The parameter specifies how many ms have elapsed // since the last time it was called. void tick(double duration_ms) { // Rather than clearing the screen to black, we set it to all white dots. console->clear(vchar{'.', GREY, BLACK}); // Increase the tick time by the frame duration. If it has exceeded // the tick duration, then we move the @. tick_time += duration_ms; if (tick_time > tick_duration) { // If we're at our destination, we need a new one! if ((destination_x == dude_x && destination_y == dude_y) || path.empty()) { // We use the RNG to determine where we want to go destination_x = rng.roll_dice(1, console->term_width)-1; destination_y = rng.roll_dice(1, console->term_height)-1; // Now we use "line_func". The prototype for this is: // void line_func(int x1, int y1, const int x2, const int y2, std::function<void(int, int)> func); // What this means in practice is line_func(from_x, from_y, to_x, to_y, callback function for each step). // We'll use a lambda for the callback, to keep it inline and tight. line_func(dude_x, dude_y, destination_x, destination_y, [] (int nx, int ny) { // Simply add the next step to the path path.push_back(std::make_pair(nx,ny)); }); } else { // We aren't there yet, so we follow our path. We take the first element on the list, // and then use pop_back to remove it. // std::tie is a handy way to extract two parts of an std::pair (or tuple) in one fell swoop. std::tie(dude_x, dude_y) = path.front(); path.pop_front(); } // Important: we clear the tick count after the update. tick_time = 0.0; } // Clipping: keep the dude on the screen. Why are we doing this here, and not // after an update? For now, we aren't handling the concept of a map that is larger // than the screen - so if the window resizes, the @ gets clipped to a visible area. if (dude_x < 0) dude_x = 0; if (dude_x > console->term_width) dude_x = console->term_width; if (dude_y < 0) dude_y = 0; if (dude_y > console->term_height) dude_x = console->term_height; // Render our planned path. We're using auto and a range-for to avoid typing all // the iterator stuff for (auto step : path) { console->set_char(console->at(step.first, step.second), star); } // Render our destination console->set_char(console->at(destination_x, destination_y), destination); // Finally, we render the @ symbol. dude_x and dude_y are in terminal coordinates. console->set_char(console->at(dude_x, dude_y), dude); } // Your main function int main() { // Initialize with defaults. init(config_simple_px("../assets")); // Enter the main loop. "tick" is the function we wrote above. run(tick); return 0; }
40.204918
108
0.709072
[ "render" ]
f034f434b3f6d93d089bf3f5eea727a2ab5af36b
12,219
cpp
C++
src/aten/src/ATen/native/npu/frame/OpDynamicCmdHelper.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
src/aten/src/ATen/native/npu/frame/OpDynamicCmdHelper.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
src/aten/src/ATen/native/npu/frame/OpDynamicCmdHelper.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020 Huawei Technologies Co., Ltd // All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "OpDynamicCmdHelper.h" #include "ATen/native/npu/frame/FormatHelper.h" #include "ATen/native/npu/frame/OpParamMaker.h" #include "ATen/native/npu/frame/InferFormat.h" #include "ATen/native/npu/utils/CalcuOpUtil.h" namespace at { namespace native { namespace npu { aclTensorDesc* OpDynamicCmdHelper::CovertToAclInputDynamicCompileDesc(Tensor tensor, c10::optional<Tensor> cpu_tensor, string& dynamicKey, string descName, string forceDataType, shapeStrage strage) { ScalarType scalarDataType = tensor.scalar_type(); aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type(scalarDataType, forceDataType); auto npuDesc = tensor.storage().get_npu_desc(); auto res = CreateDynamicCompilelDims(npuDesc, strage, true); auto dims = std::get<0>(res); auto storageDims = std::get<1>(res); auto ranges = std::get<2>(res); dynamicKey += to_string(aclDataType) + "_" + to_string(npuDesc.origin_format_) + "_" + to_string(npuDesc.npu_format_) + "_"; dynamicKey += CreateShapeKey(dims, storageDims); IntArrayRef defaultDims(dims.data(), dims.size()); AclTensorDescMaker desc; auto aclDesc = desc.Create(aclDataType, defaultDims, npuDesc.origin_format_) .SetFormat(npuDesc.npu_format_) .SetShape(storageDims) .SetRange(ranges) .SetName(descName) .SetConstAttr(cpu_tensor) .Get(); return aclDesc; } aclTensorDesc* OpDynamicCmdHelper::CovertToAclInputConstDynamicCompileDesc(Tensor tensor, c10::optional<Tensor> cpu_tensor, string& dynamicKey, string descName, string forceDataType, shapeStrage strage) { ScalarType scalarDataType = tensor.scalar_type(); aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type(scalarDataType, forceDataType); auto npuDesc = tensor.storage().get_npu_desc(); auto dims = npuDesc.base_sizes_; auto storageDims = npuDesc.storage_sizes_; SmallVector<int64_t, N> dimList; for (int64_t i = 0; i < cpu_tensor.value().numel(); ++i) { dimList.emplace_back(cpu_tensor.value()[i].item().toInt()); } dynamicKey += to_string(aclDataType) + "_2_2_"; dynamicKey += CreateConstShapeKey(dimList, strage); AclTensorDescMaker desc; auto aclDesc = desc.Create(aclDataType, dims, ACL_FORMAT_ND) .SetFormat(ACL_FORMAT_ND) .SetShape(storageDims) .SetName(descName) .SetConstAttr(cpu_tensor) .Get(); return aclDesc; } aclTensorDesc* OpDynamicCmdHelper::CovertToAclOutputDynamicCompileDesc(const Tensor* tensorPtr, string forceDataType, shapeStrage strage, bool isDimZeroToOne) { aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type( tensorPtr->scalar_type(), forceDataType); auto npuDesc = tensorPtr->storage().get_npu_desc(); AclTensorDescMaker desc; auto res = CreateDynamicCompilelDims(npuDesc, strage, isDimZeroToOne); auto dims = std::get<0>(res); auto storageDims = std::get<1>(res); auto ranges = std::get<2>(res); IntArrayRef defaultDims(dims.data(), dims.size()); auto aclDesc = desc.Create(aclDataType, defaultDims, npuDesc.origin_format_) .SetFormat(npuDesc.npu_format_) .SetShape(storageDims) .SetRange(ranges) .Get(); return aclDesc; } std::tuple<SmallVector<int64_t, N>, SmallVector<int64_t, N>, SmallVector<int64_t, N>> OpDynamicCmdHelper::CreateDynamicCompilelDims(NPUStorageDesc npuDesc, shapeStrage strage, bool isDimZeroToOne) { size_t dimsSize = ((npuDesc.base_sizes_.size() == 0) && (isDimZeroToOne == true)) ? 1 : npuDesc.base_sizes_.size(); size_t storageSize = ((npuDesc.base_sizes_.size() == 0) && (isDimZeroToOne == true)) ? 1 : npuDesc.storage_sizes_.size(); SmallVector<int64_t, N> shape(dimsSize, -1); SmallVector<int64_t, N> storageShape(storageSize, -1); if (npuDesc.npu_format_ == ACL_FORMAT_NC1HWC0) { storageShape[storageSize - 1] = 16; } if (strage != FIXED_NONE) { ShapeStrageMaker(npuDesc, shape, storageShape, strage); } SmallVector<int64_t, N> range(dimsSize * 2); for (int64_t k = 0; k < dimsSize * 2; k += 2) { range[k] = 1; range[k + 1] = -1; } return std::tie(shape, storageShape, range); } void OpDynamicCmdHelper::ShapeStrageMaker( NPUStorageDesc npuDesc, SmallVector<int64_t, N>& shape, SmallVector<int64_t, N>& storageShape, shapeStrage strage) { auto dims = npuDesc.base_sizes_; auto storageDims = npuDesc.storage_sizes_; if (strage == FIXED_ALL) { shape = dims; storageShape = storageDims; } if (strage == FIXED_C) { if (npuDesc.origin_format_ == ACL_FORMAT_NCHW) { shape[1] = dims[1]; storageShape[1] = storageDims[1]; } if (npuDesc.npu_format_ == ACL_FORMAT_NC1HWC0) { storageShape[4] = storageDims[4]; } } } string OpDynamicCmdHelper::CreateConstShapeKey( SmallVector<int64_t, N> dimList, shapeStrage strage) { string shapeKey = ""; if (strage == FIXED_CONST_VALUE) { shapeKey = CreateShapeKey(dimList, dimList); } else if (strage == FIXED_CONST_DIM) { SmallVector<int64_t, N> dim = {dimList.size()}; shapeKey = CreateShapeKey(dim, dim); } else { std::stringstream msg; msg << __func__ << ":" << __FILE__ << ":" << __LINE__; TORCH_CHECK(0, msg.str() + ": const input not support the shapeStrage=" + to_string(strage)); } shapeKey += "_isConst;"; return shapeKey; } string OpDynamicCmdHelper::CreateShapeKey( SmallVector<int64_t, N> shape, SmallVector<int64_t, N> storageShape) { string shapeKey = ""; std::for_each(shape.begin(), shape.end(), [&](int64_t dim){shapeKey += to_string(dim) + ",";}); shapeKey += "_"; std::for_each(storageShape.begin(), storageShape.end(), [&](int64_t dim){shapeKey += to_string(dim) + ",";}); shapeKey += ";"; return shapeKey; } std::tuple<aclTensorDesc*, aclDataBuffer*, int64_t, aclFormat, aclTensorDesc*> OpDynamicCmdHelper::CovertNPUTensorWithZeroDimToDynamicAclInput(const Tensor& tensor, string descName) { aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type(tensor.scalar_type()); SmallVector<int64_t, 5> dims = {1}; SmallVector<int64_t, 5> storageDims = {1}; AclTensorDescMaker desc; auto aclDesc = desc.Create(aclDataType, dims, ACL_FORMAT_ND) .SetFormat(ACL_FORMAT_ND) .SetShape(storageDims) .SetName(descName) .Get(); SmallVector<int64_t, 5> compileDims = {-1}; SmallVector<int64_t, 5> compileStorageDims = {-1}; SmallVector<int64_t, 5> compileRange = {1, -1}; AclTensorDescMaker compileDesc; auto aclCompileDesc = compileDesc.Create(aclDataType, compileDims, ACL_FORMAT_ND) .SetFormat(ACL_FORMAT_ND) .SetShape(compileStorageDims) .SetName(descName) .SetRange(compileRange) .Get(); int64_t numel = prod_intlist(storageDims); AclTensorBufferMaker buffer(tensor, numel); auto aclBuff = buffer.Get(); int64_t storageDim = storageDims.size(); aclFormat storageFormate = ACL_FORMAT_ND; return std::tie(aclDesc, aclBuff, storageDim, storageFormate, aclCompileDesc); } std::tuple<aclTensorDesc*, aclDataBuffer*, int64_t, aclFormat, aclTensorDesc*> OpDynamicCmdHelper::CovertTensorWithZeroDimToDynamicAclInput(const Tensor& tensor, ScalarType type) { // 针对在host侧的tensor,需要做大量处理 ScalarType scalarDataType = type; if (!tensor.unsafeGetTensorImpl()->is_wrapped_number()) { scalarDataType = tensor.scalar_type(); } aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type(scalarDataType); Scalar expScalar = CalcuOpUtil::ConvertTensorToScalar(tensor); Tensor aclInput = CalcuOpUtil::CopyScalarToDevice(expScalar, scalarDataType); SmallVector<int64_t, 5> dims = {1}; SmallVector<int64_t, 5> storageDims = {1}; AclTensorDescMaker desc; auto aclDesc = desc.Create(aclDataType, dims, ACL_FORMAT_ND) .SetFormat(ACL_FORMAT_ND) .SetShape(storageDims) .Get(); SmallVector<int64_t, 5> compileDims = {-1}; SmallVector<int64_t, 5> compileStorageDims = {-1}; SmallVector<int64_t, 5> compileRange = {1, -1}; AclTensorDescMaker compileDesc; auto aclCompileDesc = compileDesc.Create(aclDataType, compileDims, ACL_FORMAT_ND) .SetFormat(ACL_FORMAT_ND) .SetShape(compileStorageDims) .SetRange(compileRange) .Get(); AclTensorBufferMaker buffer(aclInput); auto aclBuff = buffer.Get(); int64_t storageDim = 1; aclFormat storageFormate = ACL_FORMAT_ND; return std::tie(aclDesc, aclBuff, storageDim, storageFormate, aclCompileDesc); } const aclTensorDesc** OpDynamicCmdHelper::ConvertTensorWithZeroDimToOneDim(const aclTensorDesc** descs, int num) { for (int i = 0; i < num; i++) { aclTensorDesc* desc = const_cast<aclTensorDesc*>(descs[i]); int dims = (int)aclGetTensorDescNumDims(desc); if (dims == 0){ aclDataType dtype = aclGetTensorDescType(desc); aclFormat format = aclGetTensorDescFormat(desc); dims = 1; int storageDims = 1; std::vector<int64_t> desc_dims(dims, 1); std::vector<int64_t> storage_desc_dims(storageDims, 1); aclTensorDesc* new_desc = aclCreateTensorDesc(dtype, dims, desc_dims.data(), format); aclSetTensorFormat(new_desc, format); aclSetTensorShape(new_desc, storageDims, storage_desc_dims.data()); aclDestroyTensorDesc(descs[i]); descs[i] = new_desc; } } return descs; } std::tuple<string, int, const aclTensorDesc**, int, const aclTensorDesc**, const aclopAttr*> OpDynamicCmdHelper::CreateDynamicCompileParams(ExecuteParas& params) { if (params.opDynamicType != "") { return std::tie(params.opDynamicType, params.dynamicParam.input_num, params.dynamicParam.compile_input_desc, params.dynamicParam.output_num, params.dynamicParam.compile_output_desc, params.dynamicCompileAttr); } else { return std::tie(params.opType, params.paras.input_num, params.paras.input_desc, params.paras.output_num, params.paras.output_desc, params.attr); } } std::tuple<string, int, const aclTensorDesc**, const aclDataBuffer**, int, const aclTensorDesc**, aclDataBuffer**, const aclopAttr*> OpDynamicCmdHelper::CreateDynamicRunParams(ExecuteParas& params) { if (params.opDynamicType != "") { return std::tie(params.opDynamicType, params.dynamicParam.input_num, params.dynamicParam.input_desc, params.dynamicParam.input_data_buf, params.dynamicParam.output_num, params.dynamicParam.output_desc, params.dynamicParam.output_data_buf, params.dynamicRunAttr); } else { params.paras.input_desc = ConvertTensorWithZeroDimToOneDim(params.paras.input_desc, params.paras.input_num); params.paras.output_desc = ConvertTensorWithZeroDimToOneDim(params.paras.output_desc, params.paras.output_num); return std::tie(params.opType, params.paras.input_num, params.paras.input_desc, params.paras.input_data_buf, params.paras.output_num, params.paras.output_desc, params.paras.output_data_buf, params.attr); } } } // npu } // native } // at
36.693694
132
0.683526
[ "shape", "vector" ]
f03a3545a786fc57de904bab29054a8b765acf05
1,491
cpp
C++
convertSortedArrayToBST.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
convertSortedArrayToBST.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
null
null
null
convertSortedArrayToBST.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ // BINARY SEARCH class Solution { public: TreeNode *func(vector<int> &nums, int low, int high) { while (low <= high) { int mid = low + (high - low) / 2; TreeNode *root = new TreeNode(nums[mid], func(nums, low, mid - 1), func(nums, mid + 1, high)); // TreeNode *root = new TreeNode(nums[mid]); // root->left = func(nums, low, mid - 1); // root->right = func(nums, mid + 1, high); return root; } return nullptr; } TreeNode *sortedArrayToBST(vector<int> &nums) { return func(nums, 0, nums.size() - 1); } }; // FASTEST SOLUTION class Solution { public: TreeNode *sortedArrayToBST(vector<int> &nums) { if (nums.size() < 1) return NULL; int mid = (nums.size() / 2); TreeNode *root = new TreeNode(nums[mid]); vector<int> left(nums.begin(), nums.begin() + mid); vector<int> right(nums.begin() + mid + 1, nums.end()); root->left = sortedArrayToBST(left); root->right = sortedArrayToBST(right); return root; } };
25.706897
106
0.536553
[ "vector" ]
f03f228f7185d000ecd3e75ea88aab2996761b67
6,835
cpp
C++
hphp/runtime/vm/jit/mutation.cpp
renesugar/hiphop-php
4eb05b745fd3018a6d9e51464cae06a4465ee142
[ "PHP-3.01", "Zend-2.0" ]
2
2019-04-11T01:39:44.000Z
2019-11-21T16:06:13.000Z
hphp/runtime/vm/jit/mutation.cpp
rmasters/hiphop-php
218e4718a7b68bf49b9a98caad9bd5f1cb2abe31
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/mutation.cpp
rmasters/hiphop-php
218e4718a7b68bf49b9a98caad9bd5f1cb2abe31
[ "PHP-3.01", "Zend-2.0" ]
1
2019-04-11T01:39:45.000Z
2019-04-11T01:39:45.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/mutation.h" #include "hphp/runtime/vm/jit/guard-relaxation.h" #include "hphp/runtime/vm/jit/simplifier.h" #include "hphp/runtime/vm/jit/state-vector.h" namespace HPHP { namespace JIT { TRACE_SET_MOD(hhir); ////////////////////////////////////////////////////////////////////// void cloneToBlock(const BlockList& rpoBlocks, IRFactory& irFactory, Block::iterator const first, Block::iterator const last, Block* const target) { assert(isRPOSorted(rpoBlocks)); StateVector<SSATmp,SSATmp*> rewriteMap(irFactory, nullptr); auto rewriteSources = [&] (IRInstruction* inst) { for (int i = 0; i < inst->numSrcs(); ++i) { if (auto newTmp = rewriteMap[inst->src(i)]) { FTRACE(5, " rewrite: {} -> {}\n", inst->src(i)->toString(), newTmp->toString()); inst->setSrc(i, newTmp); } } }; auto targetIt = target->skipHeader(); for (auto it = first; it != last; ++it) { assert(!it->isControlFlow()); FTRACE(5, "cloneToBlock({}): {}\n", target->id(), it->toString()); auto const newInst = irFactory.cloneInstruction(&*it); if (auto const numDests = newInst->numDsts()) { for (int i = 0; i < numDests; ++i) { FTRACE(5, " add rewrite: {} -> {}\n", it->dst(i)->toString(), newInst->dst(i)->toString()); rewriteMap[it->dst(i)] = newInst->dst(i); } } target->insert(targetIt, newInst); targetIt = ++target->iteratorTo(newInst); } auto it = rpoIteratorTo(rpoBlocks, target); for (; it != rpoBlocks.end(); ++it) { FTRACE(5, "cloneToBlock: rewriting block {}\n", (*it)->id()); for (auto& inst : **it) { FTRACE(5, " rewriting {}\n", inst.toString()); rewriteSources(&inst); } } } void moveToBlock(Block::iterator const first, Block::iterator const last, Block* const target) { if (first == last) return; auto const srcBlock = first->block(); auto targetIt = target->skipHeader(); for (auto it = first; it != last;) { auto const inst = &*it; assert(!inst->isControlFlow()); FTRACE(5, "moveToBlock({}): {}\n", target->id(), inst->toString()); it = srcBlock->erase(it); target->insert(targetIt, inst); targetIt = ++target->iteratorTo(inst); } } namespace { /* * Given a load and the new type of that load's guard, update the type * of the load to match the relaxed type of the guard. */ void retypeLoad(IRInstruction* load, Type newType) { newType = load->is(LdLocAddr, LdStackAddr) ? newType.ptr() : newType; if (!newType.equals(load->typeParam())) { FTRACE(2, "retypeLoad changing type param of {} to {}\n", *load, newType); load->setTypeParam(newType); } } void visitLoad(IRInstruction* inst) { // Loads from locals and the stack are special: they get their type from a // guard instruction but have no direct reference to that guard. This block // only changes the load's type param; the loop afterwards will retype the // dest if needed. switch (inst->op()) { case LdLoc: case LdLocAddr: { auto const extra = inst->extra<LdLocData>(); auto valSrc = extra->valSrc; // Unknown value that's new in this trace, so there's no guard to find. if (!valSrc) break; // If valSrc is a FramePtr, the load is of the local's original value so // we just have to find its guard. Otherwise, we know that the type of // valSrc has already been updated appropriately. Type newType; if (valSrc->isA(Type::FramePtr)) { auto guard = guardForLocal(extra->locId, valSrc); if (!guard) break; newType = guard->typeParam(); } else { newType = valSrc->type(); } retypeLoad(inst, newType); break; } case LdStack: case LdStackAddr: { auto idx = inst->extra<StackOffset>()->offset; auto typeSrc = getStackValue(inst->src(0), idx).typeSrc; if (typeSrc->is(GuardStk, CheckStk, AssertStk)) { retypeLoad(inst, typeSrc->typeParam()); } break; } case LdRef: { auto inner = inst->src(0)->type().innerType(); auto param = inst->typeParam(); assert(inner.maybe(param)); // If the type of the src has been relaxed past the LdRef's type param, // update the type param. if (inner > param) { inst->setTypeParam(inner); } break; } default: break; } } void retypeDst(IRInstruction* inst, int num) { auto ssa = inst->dst(num); /* * The type of a tmp defined by DefLabel is the union of the types of the * tmps at each incoming Jmp. */ if (inst->op() == DefLabel) { Type type = Type::Bottom; inst->block()->forEachSrc(num, [&](IRInstruction*, SSATmp* tmp) { type = Type::unionOf(type, tmp->type()); }); ssa->setType(type); return; } ssa->setType(outputType(inst, num)); } void visitInstruction(IRInstruction* inst) { visitLoad(inst); for (int i = 0; i < inst->numDsts(); ++i) { auto const ssa = inst->dst(i); auto const oldType = ssa->type(); retypeDst(inst, i); if (!ssa->type().equals(oldType)) { FTRACE(5, "reflowTypes: retyped {} in {}\n", oldType.toString(), inst->toString()); } } assertOperandTypes(inst); } } void reflowTypes(Block* const changed, const BlockList& blocks) { assert(isRPOSorted(blocks)); auto it = rpoIteratorTo(blocks, changed); assert(it != blocks.end()); for (; it != blocks.end(); ++it) { FTRACE(5, "reflowTypes: visiting block {}\n", (*it)->id()); for (auto& inst : **it) visitInstruction(&inst); } } ////////////////////////////////////////////////////////////////////// }}
30.788288
78
0.549232
[ "vector" ]
f04643f0f92f82806d4add1872c0dcf4b912ee0d
2,584
cpp
C++
reflective-targets/workflow1/opencv.cpp
NorthernForce/DeepSpace-CV
7e259f7494765499b87ae4e24f255e08b1d0bfe1
[ "MIT" ]
null
null
null
reflective-targets/workflow1/opencv.cpp
NorthernForce/DeepSpace-CV
7e259f7494765499b87ae4e24f255e08b1d0bfe1
[ "MIT" ]
null
null
null
reflective-targets/workflow1/opencv.cpp
NorthernForce/DeepSpace-CV
7e259f7494765499b87ae4e24f255e08b1d0bfe1
[ "MIT" ]
null
null
null
// compile: g++ opencv.cpp -o opencv.o `pkg-config --cflags --libs opencv` #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> int main() { cv::VideoCapture cap(2); /* * Must run "opkg install v4l-utils" on the roborio * * Also, use -l to list the controls * - Valid exposures are "5, 10, 20, 39, 78, 156, 312, 625, 1250, 2500, 5000, 10000, 20000" */ system("v4l2-ctl -d 2 -c exposure_auto=1,exposure_absolute=10"); cv::Mat frame; cv::namedWindow("Plain", cv::WINDOW_AUTOSIZE); cv::Mat filtered; cv::namedWindow("Filtered", cv::WINDOW_AUTOSIZE); cv::Mat result; cv::namedWindow("Result", cv::WINDOW_AUTOSIZE); while (1) { cap >> frame; if (frame.empty()) break; imshow("Plain", frame); /* Remove noise -- we're only going for orange on the mask. */ cv::blur(frame, filtered, cv::Size(3, 3)); /* Use gray. */ cv::cvtColor(filtered, filtered, cv::COLOR_BGR2GRAY); /* Threshold. */ cv::threshold(filtered, filtered, 100, 255, cv::THRESH_BINARY); // /* Use HSV. */ // cv::cvtColor(filtered, filtered, cv::COLOR_BGR2HSV); // /* Try to threshold the tape. */ // cv::inRange(filtered, cv::Scalar(0, 0, 40), cv::Scalar(255, 255, 255), filtered); /* Get rid of spots. */ // cv::erode(filtered, filtered, cv::Mat(), cv::Point(-1, -1), 2); /* Find contours. */ std::vector<std::vector<cv::Point>> contours; cv::findContours(filtered, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE); /* Remove small contours. */ for (int i = 0; i < contours.size(); i++) { if (cv::contourArea(contours[i]) <= 1000) { contours.erase(contours.begin() + i); i--; } } /* Find rectangles */ std::vector<std::vector<cv::Point>> polygons; polygons.resize(contours.size()); for (int i = 0; i < contours.size(); i++) { cv::approxPolyDP(contours[i], polygons[i], 10, true); /* Maybe implement a little error detection. */ // if (polygons[i].size() > 5 || polygons[i].size() < 4) { // } } imshow("Filtered", filtered); result = frame; for (int i = 0; i < contours.size(); i++) { cv::drawContours(result, contours, i, cv::Scalar(0, 0, 255)); cv::line(result, polygons[i][0], polygons[i][polygons[i].size() - 1], cv::Scalar(0, 255, 0)); for (int x = 1; x < polygons[i].size(); x++) { cv::line(result, polygons[i][x], polygons[i][x - 1], cv::Scalar(0, 255, 0)); } } imshow("Result", result); if (char(cv::waitKey(10)) == 27) break; } }
26.10101
96
0.611068
[ "vector" ]
f0530831cc8f0b53f7633bf18af48462dceb816f
1,561
cpp
C++
src/ai/weapons/nemesis.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
8
2018-04-03T23:06:33.000Z
2021-12-28T18:04:19.000Z
src/ai/weapons/nemesis.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
null
null
null
src/ai/weapons/nemesis.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
1
2020-07-31T00:23:27.000Z
2020-07-31T00:23:27.000Z
#include "nemesis.h" #include "weapons.h" #include "../../ObjManager.h" #include "../../common/misc.h" #include "../../game.h" INITFUNC(AIRoutines) { ONTICK(OBJ_NEMESIS_SHOT, ai_nemesis_shot); ONTICK(OBJ_NEMESIS_SHOT_CURLY, ai_nemesis_shot); } /* void c------------------------------() {} */ void ai_nemesis_shot(Object *o) { if (run_shot(o, (o->shot.level != 2))) return; // smoke trails on level 1 if (o->shot.level == 0) { // observe, first smokecloud is on 3rd frame; // it goes BLUE, YELLOW, BLUE--that's when the first cloud appears. if ((++o->timer % 4) == 3) { int x, y, xi, yi; x = y = xi = yi = 0; switch(o->shot.dir) { case RIGHT: { x = o->Left(); y = o->CenterY(); xi = 0x200; yi = random(-0x200, 0x200); } break; case LEFT: { x = o->Right(); y = o->CenterY(); xi = -0x200; yi = random(-0x200, 0x200); } break; case UP: { x = o->CenterX(); y = o->Bottom(); xi = random(-0x200, 0x200); yi = -0x200; } break; case DOWN: { x = o->CenterX(); y = o->Top(); xi = random(-0x200, 0x200); yi = 0x200; } break; } x += o->xinertia; y += o->yinertia; Object *smoke = CreateObject(x, y, OBJ_SMOKE_CLOUD); smoke->xinertia = xi; smoke->yinertia = yi; smoke->PushBehind(o); if (o->timer2 == 0) { smoke->frame = 3; o->timer2 = 1; } else if (random(0, 1)) { smoke->frame = 1; } } } o->frame ^= 1; }
16.260417
69
0.493274
[ "object" ]
f05b460f255be93fb507500628a6d719e591b2eb
3,391
cc
C++
cpp/test/test_exact_transient_solution.cc
iiscsahoo/EnergyData
6230145b5df6b126eab11aea58a5cfaa11ad5ba1
[ "BSD-3-Clause" ]
13
2016-05-15T11:42:43.000Z
2021-04-27T19:33:04.000Z
cpp/test/test_exact_transient_solution.cc
iiscsahoo/EnergyData
6230145b5df6b126eab11aea58a5cfaa11ad5ba1
[ "BSD-3-Clause" ]
198
2016-01-27T16:46:59.000Z
2019-07-11T06:31:37.000Z
cpp/test/test_exact_transient_solution.cc
iiscsahoo/EnergyData
6230145b5df6b126eab11aea58a5cfaa11ad5ba1
[ "BSD-3-Clause" ]
6
2016-01-27T15:17:09.000Z
2020-06-15T02:06:50.000Z
/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE ExactTransientSolution #include "main.cc" #include <cap/energy_storage_device.h> #include <cap/mp_values.h> #include <deal.II/base/types.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <cmath> #include <iostream> #include <fstream> #include <numeric> namespace cap { void verification_problem(std::shared_ptr<cap::EnergyStorageDevice> dev) { // gold vs computed double const charge_current = 5e-3; double const charge_time = 0.01; double const time_step = 1e-4; double const epsilon = time_step * 1.0e-4; unsigned int pos = 0; double computed_voltage; // check that error less than 1e-3 % AND less than 1 microvolt double const percent_tolerance = 1e-3; double const tolerance = 1e-6; std::vector<double> gold_solution(10); gold_solution[0] = 1.725914356067658e-01; gold_solution[1] = 1.802025636145941e-01; gold_solution[2] = 1.859326352495181e-01; gold_solution[3] = 1.905978440188036e-01; gold_solution[4] = 1.946022119085378e-01; gold_solution[5] = 1.981601232287249e-01; gold_solution[6] = 2.013936650249285e-01; gold_solution[7] = 2.043807296399895e-01; gold_solution[8] = 2.071701713934283e-01; gold_solution[9] = 2.097979282542038e-01; for (double time = 0.0; time <= charge_time + epsilon; time += time_step) { dev->evolve_one_time_step_constant_current(time_step, charge_current); dev->get_voltage(computed_voltage); if ((std::abs(time + time_step - 1e-3) < 1e-7) || (std::abs(time + time_step - 2e-3) < 1e-7) || (std::abs(time + time_step - 3e-3) < 1e-7) || (std::abs(time + time_step - 4e-3) < 1e-7) || (std::abs(time + time_step - 5e-3) < 1e-7) || (std::abs(time + time_step - 6e-3) < 1e-7) || (std::abs(time + time_step - 7e-3) < 1e-7) || (std::abs(time + time_step - 8e-3) < 1e-7) || (std::abs(time + time_step - 9e-3) < 1e-7) || (std::abs(time + time_step - 10e-3) < 1e-7)) { BOOST_CHECK_CLOSE(computed_voltage, gold_solution[pos], percent_tolerance); BOOST_CHECK_SMALL(computed_voltage - gold_solution[pos], tolerance); ++pos; } } } } // end namespace cap BOOST_AUTO_TEST_CASE(test_exact_transient_solution) { // parse input file boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); boost::property_tree::ptree geometry_database; boost::property_tree::info_parser::read_info("read_mesh.info", geometry_database); device_database.put_child("geometry", geometry_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(device_database, boost::mpi::communicator()); cap::verification_problem(device); }
35.322917
78
0.672663
[ "geometry", "vector" ]
f05fe600e6c439ef357e87764ab79b1af07ec3af
302
hpp
C++
sw/paramallocator.hpp
lw0/dfaccto_sim
aa3aab87046383935f071dd4adcf0c2b44ce0e75
[ "MIT" ]
null
null
null
sw/paramallocator.hpp
lw0/dfaccto_sim
aa3aab87046383935f071dd4adcf0c2b44ce0e75
[ "MIT" ]
null
null
null
sw/paramallocator.hpp
lw0/dfaccto_sim
aa3aab87046383935f071dd4adcf0c2b44ce0e75
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "types.hpp" namespace sim { class ParamAllocator { public: ParamAllocator(); sim::SignalParam alloc(); void free(sim::SignalParam param); private: std::vector<sim::SignalParam> m_freeParams; sim::SignalParam m_nextParam; }; } // namespace sim
12.08
45
0.708609
[ "vector" ]
f06468d271562b7d45607a934ea8a936bf3978bb
1,171
cpp
C++
src/Pizza/Pizza.cpp
HugoPrat/Multi-process-threads-plazza-Cpp
ef97968a360e77ebeed69a96e44ed801c40e6509
[ "0BSD" ]
3
2019-12-01T10:18:12.000Z
2020-02-22T10:54:36.000Z
src/Pizza/Pizza.cpp
HugoPrat/Multi-process-threads-plazza-Cpp
ef97968a360e77ebeed69a96e44ed801c40e6509
[ "0BSD" ]
null
null
null
src/Pizza/Pizza.cpp
HugoPrat/Multi-process-threads-plazza-Cpp
ef97968a360e77ebeed69a96e44ed801c40e6509
[ "0BSD" ]
null
null
null
/* ** EPITECH PROJECT, 2019 ** CCP_plazza_2018 ** File description: ** Pizza */ #include "Pizza/Pizza.hpp" Pizza::Pizza(PizzaType type, PizzaSize size, float time) : _type(type), _size(size), _cooked_time(time), _cooking(false) { } Pizza::Pizza() {} Pizza::Pizza(const Pizza &a) { _type = a._type; _size = a._size; _timing = a._timing; _recipe = a._recipe; _cooked_time = a._cooked_time; _cooking = a._cooking; } Pizza Pizza::operator=(const Pizza &a) { Pizza tmp(a); return tmp; } short Pizza::getCookingTime() const { return _cooked_time; } PizzaType Pizza::getType() const { return _type; } PizzaSize Pizza::getSize() const { return _size; } std::vector<food> Pizza::getRecipe() const { return _recipe; } void Pizza::go_to_furnace() { std::unique_lock<std::mutex> l(this->m); _timing = std::chrono::steady_clock::now(); _cooking = true; } bool Pizza::isReady() { auto tmp = std::chrono::steady_clock::now(); if (!_cooking) return false; if (std::chrono::duration_cast<std::chrono::seconds>(tmp - _timing).count() >= _cooked_time) return true; return false; }
16.263889
96
0.642186
[ "vector" ]
f06574566bf257604f56f7d489a92720705bae5e
553
hpp
C++
src/connection.hpp
AndreJSON/holy-integraal
62d9e2ea954f8a31005c30fa87189234ddf6e142
[ "MIT" ]
null
null
null
src/connection.hpp
AndreJSON/holy-integraal
62d9e2ea954f8a31005c30fa87189234ddf6e142
[ "MIT" ]
null
null
null
src/connection.hpp
AndreJSON/holy-integraal
62d9e2ea954f8a31005c30fa87189234ddf6e142
[ "MIT" ]
null
null
null
#pragma once #include "area.hpp" /* * Connection is a special kind of area that only has two entry/exit points. One of them is blocked by a Guardian until it has been defeated. */ namespace qhi { class Connection : public Area { public: Connection(std::string desc); virtual ~Connection(); virtual std::string getDescription(int playerIQ) const override; virtual int getAreaType() const override; virtual std::vector<std::string> getMovementDirections() const override; virtual bool permittedDirection(int direction) const override; }; }
32.529412
140
0.755877
[ "vector" ]
f068ae124f163e18ce0f734df03df37432740b81
53,003
hpp
C++
atomics/PersonBehaviorRules.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
atomics/PersonBehaviorRules.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
atomics/PersonBehaviorRules.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2017, Cristina Ruiz Martin * Carleton University, Universidad de Valladolid * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Decision Maker in Cadmium * Choose between answer a communication request, send a communication or do an action * It is only valid for doing one task at a time * choose_com_channel auxiliary function. Only mobile, landline, email and beeper implemented */ #ifndef CADMIUM_DECISION_MAKER_HPP #define CADMIUM_DECISION_MAKER_HPP #include <cadmium/modeling/ports.hpp> #include <cadmium/modeling/message_bag.hpp> #include <limits> using namespace std; using namespace cadmium; #include "../data_structures/decision_maker_behaviour_struct_types_V2.hpp" #include "../data_structures/nep_model_enum_types.hpp" #include "../data_structures/communication.hpp" #include "../data_structures/struct_types.hpp" using namespace decision_maker_behaviour_structures; using namespace decision_maker_behaviour_enum_types; using namespace nep_model_enum_types; using namespace nep_structures; //Port definition struct PersonBehaviorRules_defs{ struct generatorIn : public in_port<Command> { }; struct requestIn : public in_port<Communication> { }; struct taskDeviceFinishedIn : public in_port<TaskDeviceFinished> { }; struct taskActionFinishedIn : public in_port<ActionFinished> { }; struct peopleInSameLocationIn : public in_port<PeopleClassifiedByLocation> { }; struct taskSendOutInperson: public out_port<CommandWithDevice> { }; struct taskSendOutDevice: public out_port<CommandWithDevice> { }; struct taskAnswerOutInperson: public out_port<Communication> { }; struct taskAnswerOutDevice: public out_port<Communication> { }; struct taskDoActionOut: public out_port<Action2Do> { }; }; //This is a meta-model, it should be overloaded for declaring the Id parameter template<typename TIME> class PersonBehaviorRules { using defs=PersonBehaviorRules_defs; // putting definitions in context public: enum Task{ANSWER, SEND, DO_ACTION, IDLE}; // state definition struct state_type{ //PARAMETERS DecisionMakerBehaviour behaviour; //DECISION VARIABLES vector<pair<DeviceId,Communication>> answerRequests; //DeviceId(My device + who is requesting) vector<Msg2Send> commands2Send; vector<Msg2Send> commands2SendDeviceNotAvailable; vector<ActionBehaviour> actions2Do; vector<tuple<DeviceId,Task,Communication,CommandWithDevice,Action2Do>> taskState; //MyDeviceId OR IDLE (in the case of DO_ACTION) vector<tuple<Confirmation,Msg2Send>> confirmationTrack; vector<DeviceType> devicesBusy; //Only the ones that cannot receive and send at the same time //OTHER VARIABLES bool makeNewDecision; bool newTaskChoosen; vector<tuple<DeviceId,Task,Communication,CommandWithDevice,Action2Do>> choosenTask; //MyDeviceId TIME advanceTime; //TRACKING VARIABLES vector<Command> commandsReceived; vector<ActionBehaviour> actionsDone; vector<Msg2Send> commandsSent; vector<DeviceType> devicesOutOfOrder; }; state_type state; //default constructor PersonBehaviorRules(string file_name_in) noexcept { const char * in = file_name_in.c_str(); state.behaviour.load(in); #ifdef DEBUG_MODE string debugname = string("DEBUG_DECISION_MAKER_PARAMETERS_")+state.behaviour.id+(string(".xml")); const char * out = debugname.c_str(); state.behaviour.save(out); #endif state.advanceTime = std::numeric_limits<TIME>::infinity(); state.makeNewDecision = true; state.newTaskChoosen = false; } // ports definition using input_ports=std::tuple<typename defs::peopleInSameLocationIn, typename defs::generatorIn, typename defs::requestIn, typename defs::taskDeviceFinishedIn, typename defs::taskActionFinishedIn>; using output_ports=std::tuple<typename defs::taskSendOutInperson, typename defs::taskSendOutDevice, typename defs::taskAnswerOutInperson, typename defs::taskAnswerOutDevice, typename defs:: taskDoActionOut>; // internal transition void internal_transition() { /***********************************************************************************/ /*If the choosen task is answer, delete the choosen task from answer answerRequests*/ /***********************************************************************************/ if(get<Task>(state.choosenTask[0]) == Task::ANSWER){ Communication requestAnswered = get<Communication>(state.choosenTask[0]); for(int i = 0; i < state.answerRequests.size(); i++){ if(requestAnswered == get<Communication>(state.answerRequests[i])) { state.answerRequests.erase(state.answerRequests.begin()+i); break; } } } /********************/ /* Update TaskState */ /********************/ switch(get<Task>(state.choosenTask[0])){ case Task::ANSWER: case Task::SEND: case Task::DO_ACTION: state.taskState.push_back(state.choosenTask[0]);break; default: assert(false && ("The internal should not arrive this point")); break; } /*******************/ /*Clear choosenTask*/ /*******************/ state.choosenTask.clear(); /*****************************/ /*Set make new decision false*/ /*****************************/ state.makeNewDecision = false; state.newTaskChoosen = false; /*********************/ /*Passivate the model*/ /*********************/ state.advanceTime = std::numeric_limits<TIME>::infinity(); } //external void external_transition(TIME e, typename make_message_bags<input_ports>::type mbs) { //cout << "EXTERNAL BEHAVIOUR RULES " << state.behaviour.id << " "; /***********************************************************/ /* Process the inputs. Update decision & tacking variables */ /***********************************************************/ //generatorIn for (const auto &x : get_messages<typename defs::generatorIn>(mbs)){ //cout << "generator in" << x << endl; /**Update commands2Send**/ vector<Msg2Send> newCommands2Send = extract_commnads_to_send_from_command(x, state.behaviour); for(int z = 0; z<newCommands2Send.size(); z++){ state.commands2Send.push_back(newCommands2Send[z]); } /**Update actions2Do**/ vector<ActionBehaviour> newActions2Do = extract_actions_to_do_from_command(x, state.behaviour); for(int z = 0; z<newActions2Do.size(); z++){ state.actions2Do.push_back(newActions2Do[z]); } } //requestIn (new request or request over) for (const auto &x : get_messages<typename defs::requestIn>(mbs)) { switch(x.type){ case MessageType::PHONE_MESSAGE: switch (x.msg_phone){ case PhoneMsgType::CALL_REQUEST: { /** Add answer request to list **/ state.answerRequests.push_back(make_pair(DeviceId(x.to.type, x.from.id), x)); /** if device cannot send and recieve at the same time, add to the list of busy devices*/ bool isdeviceBusy = is_device_busy(x.to.type, state.devicesBusy); if(isdeviceBusy) state.devicesBusy.push_back(x.to.type); } break; case PhoneMsgType::CALL_OVER: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; case PhoneMsgType::OUT_OF_ORDER: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; default:assert(false&&"This PhoneMsgType is not allowed in this model"); break; } break; case MessageType::TEXT_MESSAGE: switch (x.msg_text){ case TextMsgType::NEW: { /** Add answer request to list **/ state.answerRequests.push_back(make_pair(DeviceId(x.to.type, x.from.id), x)); /** if device cannot send and recieve at the same time, add to the list of busy devices*/ bool isdeviceBusy = is_device_busy(x.to.type, state.devicesBusy); if(isdeviceBusy) state.devicesBusy.push_back(x.to.type); } break; case TextMsgType::OUT_OF_ORDER: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; default:assert(false&&"This TextMsgType is not allowed in this model"); break; } break; case MessageType::RADIO_MESSAGE: switch (x.msg_radio){ case RadioMsgType::REQUEST: { /** Add answer request to list **/ state.answerRequests.push_back(make_pair(DeviceId(x.to.type, x.from.id), x)); /** if device cannot send and recieve at the same time, add to the list of busy devices*/ bool isdeviceBusy = is_device_busy(x.to.type, state.devicesBusy); if(isdeviceBusy) state.devicesBusy.push_back(x.to.type); } break; case RadioMsgType::COMMAND_TRANSMITTED: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; case RadioMsgType::INTERFERENCES: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; case RadioMsgType::OUT_OF_ORDER: /** Delete answer request over from the list **/ for(int j = 0; j < state.answerRequests.size(); j++){ if(state.answerRequests[j].first == DeviceId(x.to.type, x.from.id)){ state.answerRequests.erase(state.answerRequests.begin()+j); break; } } /** If device in the list of busy devices, remove from it**/ for(int j=0; j<state.devicesBusy.size(); j++){ if(x.to.type == state.devicesBusy[j]){ state.devicesBusy.erase(state.devicesBusy.begin()+j); break; } } break; default:assert(false&&"This RadioMsgType is not allowed in this model"); break; } break; default: assert(false && "MessageType to implement"); break; } } //taskDeviceFinishedIn for (const auto &x : get_messages<typename defs::taskDeviceFinishedIn>(mbs)){ //cout << "taskDeviceFinishedIn in" << x << endl; // cout << "BR - taskDeviceFinishedIn" << endl; /** Update the state of devices out of order **/ if(x.out_of_order){ for(int j = 0; j < state.behaviour.myDevices.size(); j++){ if(x.my_id.type == state.behaviour.myDevices[j].device){ state.behaviour.myDevices.erase(state.behaviour.myDevices.begin()+j); state.devicesOutOfOrder.push_back(x.my_id.type); break; } } } /** Process the command received/sent & update the commands2Send, actions2Do, confirmationTrack and other variables**/ // cout << "BR - taskDeviceFinishedIn - taskstate size: " << state.taskState.size() << endl; for(int j =0; j < state.taskState.size(); j++){ // cout << "x.my_id: " << x.my_id << " | DeviceId task state: " << get<DeviceId>(state.taskState[j]) << endl; if(x.my_id == get<DeviceId>(state.taskState[j])){ // cout << "BR entra en x.makeNewDecision == get DeviceIdTask" << endl; switch (get<Task>(state.taskState[j])){ case Task::ANSWER: // cout << "BR - taskDeviceFinishedIn ANSWER" << endl; if(x.command.command != string("-")){ // cout << "BR - taskDeviceFinishedIn ANSWER - command not -" << x.command.command << endl; /**Update commands2Send**/ vector<Msg2Send> newCommands2Send = extract_commnads_to_send_from_command(x.command, state.behaviour); for(int z = 0; z<newCommands2Send.size(); z++){ state.commands2Send.push_back(newCommands2Send[z]); } /**Update actions2Do**/ vector<ActionBehaviour> newActions2Do = extract_actions_to_do_from_command(x.command, state.behaviour); for(int z = 0; z<newActions2Do.size(); z++){ state.actions2Do.push_back(newActions2Do[z]); } /**Update confirmationTrack**/ for(int z = 0; z<state.confirmationTrack.size(); z++){ if(x.command.command == get<Confirmation>(state.confirmationTrack[z]).content && x.command.from == get<Confirmation>(state.confirmationTrack[z]).from){ state.confirmationTrack.erase(state.confirmationTrack.begin()+z); break; } } /**Track command received**/ state.commandsReceived.push_back(x.command); //cout << "new ammount of commnads to send: " << state.commands2Send.size() << endl; } break; case Task::SEND: //cout << "BR - taskDeviceFinishedIn SEND" << endl; if(x.command.command != string("-")){ // cout << "BR - taskDeviceFinishedIn SEND - command not -" << x.command.command << endl; Msg2Send auxCommandSent = extract_command_just_sent(x.command, state.commands2Send); // cout << auxCommandSent.to << " " << auxCommandSent.content << endl; /**Update commands2Send**/ // cout << state.commands2Send.size() << endl; for(int z = 0; z < state.commands2Send.size(); z++){ if(auxCommandSent.equal(state.commands2Send[z])){ // cout << auxCommandSent.equal(state.commands2Send[z]) << endl; state.commands2Send.erase(state.commands2Send.begin()+z); break; } } // cout << "new ammount of commnads to send: " << state.commands2Send.size() << endl; /**Update commandsSent**/ state.commandsSent.push_back(auxCommandSent); /**Update confirmationTrack**/ vector<Confirmation> auxConfirmations2Receive = auxCommandSent.confirmations; for(int z = 0; z < auxConfirmations2Receive.size(); z++){ state.confirmationTrack.push_back(make_tuple(auxConfirmations2Receive[z], auxCommandSent)); } } break; default: assert(false && "Task not defined for devices"); break; } /** Delete the task finished from current tasks **/ state.taskState.erase(state.taskState.begin()+j); //cout << "taskState size after procesing task finished: " << state.taskState.size() << endl; break; } } } //taskActionFinishedIn for (const auto &x : get_messages<typename defs::taskActionFinishedIn>(mbs)){ /** Update Location **/ state.behaviour.location = x.location; /** Extract action done **/ ActionBehaviour auxActionDone = extract_action_done_from_actions2Do(x.action_id, state.actions2Do); /** Add action done to actionsDone **/ state.actionsDone.push_back(auxActionDone); /** Delete action done from actions2Do **/ for(int j = 0; state.actions2Do.size(); j++){ if(state.actions2Do[j].equal(auxActionDone)){ state.actions2Do.erase(state.actions2Do.begin()+j); break; } } /** Add new Msg2Send from the action done to command2send**/ vector<Msg2Send> auxNewMsg2Send = auxActionDone.msg2send; for(int j = 0; auxNewMsg2Send.size(); j++){ state.commands2Send.push_back(auxNewMsg2Send[j]); } /** Delete the task finished from current tasks **/ //We are assuming that we can only do one task at a time for(int j =0; j < state.taskState.size(); j++){ if(get<Task>(state.taskState[j]) == Task::DO_ACTION){ state.taskState.erase(state.taskState.begin()+j); break; } } } //peopleInSameLocationIn for (const auto &x : get_messages<typename defs::peopleInSameLocationIn>(mbs)){ /**Update people in same location**/ state.behaviour.peopleSameLocation = x.ids; } /***********************************/ /* Update makeNewDecision variable */ /***********************************/ /**If I am not doing any task set make new decision = true **/ if(state.taskState.empty()) state.makeNewDecision = true; //cout << "make new decision: " << state.makeNewDecision << endl; /**************************************************/ /* If makeNewDecision = true, make a new decision */ /**************************************************/ tuple<DeviceId,Task,Communication,CommandWithDevice,Action2Do> newChoosenTask; if(state.makeNewDecision == true){ state.newTaskChoosen = false; state.choosenTask.clear(); for(int i = 0; i < state.behaviour.taskPrioritized.size(); i++){ vector<TaskPriorityType> taskWsamePriority = extract_task_with_priority_j((i+1), state.behaviour); for(int j = 0; j < taskWsamePriority.size(); j++){ switch(taskWsamePriority[j]){ case TaskPriorityType::ANSWER: /** Do Task AnswerDevice if any answer request **/ // cout << "chosing task answer" << endl; if(!state.answerRequests.empty()){ if(state.answerRequests.size() > 1){ vector<pair<DeviceId,Communication>> aux_answerRequests = state.answerRequests; switch(state.behaviour.answerPriority){ case AnswerPriorityType::DEVICE_PRIORITY: //Answer behaviour if the answer priority is based on devices first aux_answerRequests = extract_requests_with_same_device_priority(aux_answerRequests, state.behaviour); if(aux_answerRequests.size()>1){ aux_answerRequests = extract_requests_with_same_person_priority(aux_answerRequests, state.behaviour); if(aux_answerRequests.size()>1){ #ifdef DEBUG_MODE newChoosenTask = make_tuple(DeviceId(aux_answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; #else unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // seed variable is used to ensure a different set of results for each simulation srand (seed); int a = rand() % (aux_answerRequests.size()-1); newChoosenTask = make_tuple(DeviceId(aux_answerRequests[a].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[a].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; #endif }else{ newChoosenTask = make_tuple(DeviceId(aux_answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; } }else{ newChoosenTask = make_tuple(DeviceId(aux_answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; } break;//case DEVICE_PRIORITY case AnswerPriorityType::PERSON_PRIORITY: //Answer behaviour if the answer priority is based on persons first aux_answerRequests = extract_requests_with_same_person_priority(aux_answerRequests, state.behaviour); if(aux_answerRequests.size()>1){ aux_answerRequests = extract_requests_with_same_device_priority(aux_answerRequests, state.behaviour); if(aux_answerRequests.size()>1){ #ifdef DEBUG_MODE newChoosenTask = make_tuple(aux_answerRequests[0].first, Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; #else unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // seed variable is used to ensure a different set of results for each simulation srand (seed); int a = rand() % (aux_answerRequests.size()-1); newChoosenTask = make_tuple(DeviceId(aux_answerRequests[a].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[a].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; #endif }else{ newChoosenTask = make_tuple(DeviceId(aux_answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; } }else{ newChoosenTask = make_tuple(DeviceId(aux_answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, aux_answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; } break; //break PERSON_PRIORITY default: assert(false && "AnswerPriority not implemented"); break; } }else{ newChoosenTask = make_tuple(DeviceId(state.answerRequests[0].first.type, state.behaviour.id), Task::ANSWER, state.answerRequests[0].second,CommandWithDevice(),Action2Do()); state.newTaskChoosen = true; } } break;//break ANSWER case TaskPriorityType::SEND: /** Do Task SendCommand if any command to send **/ if(!state.commands2Send.empty()){ pair<DeviceType, DeviceType> com_chan; //from, to vector<Msg2Send> commandsWithSamePriority; Msg2Send commandSelected; switch(state.behaviour.sendPriority){ case SendPriorityType::RECEPTION_ORDER: //Send commands based on reception order while(!state.commands2Send.empty()){ com_chan = choose_com_channel(state.commands2Send[0], state.behaviour); if(com_chan.first != DeviceType::IDLE){ // cout << "SEND - RECEPTION ORDER NOT IDLE" << endl; bool isdeviceBusy = is_device_busy(com_chan.first, state.devicesBusy); if(!isdeviceBusy){ newChoosenTask = make_tuple(DeviceId(com_chan.first, state.behaviour.id),Task::SEND, Communication(),CommandWithDevice(DeviceId(com_chan.first, state.behaviour.id), DeviceId(com_chan.second, state.commands2Send[0].to), Command(state.behaviour.id, state.commands2Send[0].to, state.commands2Send[0].content)),Action2Do()); state.newTaskChoosen = true; }//if device is busy, I go to the next task answer or do action. I do not look for other commands to send. //if device is busy it means that, at least, I have an answer request. break;//break while }else{ //if device not working, I forguet about the compulsory channel restriction // cout << "SEND - RECEPTION ORDER IDLE" << endl; state.commands2SendDeviceNotAvailable.push_back(state.commands2Send[0]); if(!state.commands2Send[0].deviceCompulsory.empty()){ state.commands2Send[0].deviceCompulsory.clear(); state.commands2Send.push_back(state.commands2Send[0]); } state.commands2Send.erase(state.commands2Send.begin()); } } break;//Break send based on reception order case SendPriorityType::INVERSE_RECEPTION_ORDER://Send commands based on inverse reception order while(!state.commands2Send.empty()){ int a = state.commands2Send.size()-1; com_chan = choose_com_channel(state.commands2Send[a], state.behaviour); if(com_chan.first != DeviceType::IDLE){ bool isdeviceBusy = is_device_busy(com_chan.first, state.devicesBusy); if(!isdeviceBusy){ newChoosenTask = make_tuple(DeviceId(com_chan.first, state.behaviour.id),Task::SEND, Communication(), CommandWithDevice(DeviceId(com_chan.first, state.behaviour.id), DeviceId(com_chan.second, state.commands2Send[a].to), Command(state.behaviour.id, state.commands2Send[a].to, state.commands2Send[a].content)),Action2Do()); state.newTaskChoosen = true; } //if device is busy, I go to the next task answer or do action. I do not look for other commands to send //if device is busy it means that, at least, I have an answer request. break;//break while }else{//if device not working, I forguet about the compulsory channel restriction state.commands2SendDeviceNotAvailable.push_back(state.commands2Send[a]); if(!state.commands2Send[a].deviceCompulsory.empty()){ state.commands2Send[a].deviceCompulsory.clear(); state.commands2Send.insert(state.commands2Send.begin(),state.commands2Send[a]); } state.commands2Send.pop_back(); } } break;//break send commands inverse reception order case SendPriorityType::PRIORITY_LIST: while(!state.commands2Send.empty()){ commandsWithSamePriority = extract_commands_with_same_pripority(state.commands2Send, state.behaviour); if(commandsWithSamePriority.size()>1){ #ifdef DEBUG_MODE commandSelected = commandsWithSamePriority[0]; #else unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // seed variable is used to ensure a different set of results for each simulation srand (seed); int a = rand() % (commandsWithSamePriority.size()-1); commandSelected = commandsWithSamePriority[a]; #endif }else{ commandSelected = commandsWithSamePriority[0]; } com_chan = choose_com_channel(commandSelected, state.behaviour); if(com_chan.first != DeviceType::IDLE){ bool isdeviceBusy = is_device_busy(com_chan.first, state.devicesBusy); if(!isdeviceBusy){ newChoosenTask = make_tuple(DeviceId(com_chan.first, state.behaviour.id),Task::SEND, Communication(), CommandWithDevice(DeviceId(com_chan.first, state.behaviour.id), DeviceId(com_chan.second, commandSelected.to), Command(state.behaviour.id, commandSelected.to, commandSelected.content)),Action2Do()); state.newTaskChoosen = true; }//if device is busy, I go to the next task answer or do action. I do not look for other commands to send //if device is busy it means that, at least, I have an answer request. break; //break while }else{//if device not working, I forguet about the compulsory channel restriction for(int z= 0; z < state.commands2Send.size(); z++){ if(state.commands2Send[z].equal(commandSelected)){ state.commands2SendDeviceNotAvailable.push_back(state.commands2Send[z]); Msg2Send aux; if(!state.commands2Send[z].deviceCompulsory.empty()){ state.commands2Send[z].deviceCompulsory.clear(); aux = state.commands2Send[z]; } state.commands2Send.erase(state.commands2Send.begin()+z); if(aux.equal(state.commands2SendDeviceNotAvailable.back())) state.commands2Send.push_back(aux); break; //break for z } } } } break; //break send commands based on priority list default: assert(false && "Priority not implemented"); break; } } //TO_IMPLEMENT: if in person or phoneMultiple - selected all the people that I need to send the message through that channel break;//break SEND case TaskPriorityType::DO_ACTION: /** Do an action if any action to do **/ if(!state.actions2Do.empty()){ vector<ActionBehaviour> actionsWithSamePriority = extract_actions_with_same_pripority(state.actions2Do, state.behaviour); ActionBehaviour actionSelected; if(actionsWithSamePriority.size()>1){ #ifdef DEBUG_MODE actionSelected = actionsWithSamePriority[0]; #else unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // seed variable is used to ensure a different set of results for each simulation srand (seed); int a = rand() % (actionsWithSamePriority.size()-1); actionSelected = actionsWithSamePriority[a]; #endif }else{ actionSelected = actionsWithSamePriority[0]; } newChoosenTask = make_tuple(DeviceId(DeviceType::IDLE, state.behaviour.id), Task::DO_ACTION, Communication(), CommandWithDevice(), Action2Do(actionSelected.id, actionSelected.averageExectionTime, actionSelected.location)); state.newTaskChoosen = true; } break;//break DO_ACTION default: assert(false && "Task not implemented"); break; } if(state.newTaskChoosen == true) break; //break for j } if(state.newTaskChoosen == true) break; //break for i } } //*************************************************/ /*** Set advance time & update choosen task ******/ /*************************************************/ if(state.makeNewDecision == false){ state.advanceTime = std::numeric_limits<TIME>::infinity(); }else{ if(state.newTaskChoosen == true){ if(!state.choosenTask.empty()){ if(newChoosenTask == state.choosenTask[0]) state.advanceTime = state.advanceTime - e; }else{ state.choosenTask.push_back(newChoosenTask); state.advanceTime = TIME(state.behaviour.reactionTime); } }else{ state.advanceTime = std::numeric_limits<TIME>::infinity(); } } } // confluence transition void confluence_transition(TIME e, typename make_message_bags<input_ports>::type mbs) { cout << "**** CONFLUENCE PERSON BEHAVIOR RULES ************ " << state.behaviour.id << endl; internal_transition(); external_transition(TIME(), std::move(mbs)); } // output function typename make_message_bags<output_ports>::type output() const { //cout << "OUTPUT " << state.behaviour.id ; typename make_message_bags<output_ports>::type bags; switch(get<Task>(state.choosenTask[0])){ case Task::ANSWER: if(get<Communication>(state.choosenTask[0]).to.type == DeviceType::IN_PERSON){ get_messages<typename defs::taskAnswerOutInperson>(bags).push_back(get<Communication>(state.choosenTask[0])); }else{ get_messages<typename defs::taskAnswerOutDevice>(bags).push_back(get<Communication>(state.choosenTask[0])); } break; case Task::SEND: if(get<CommandWithDevice>(state.choosenTask[0]).from.type == DeviceType::IN_PERSON){ get_messages<typename defs::taskSendOutInperson>(bags).push_back(get<CommandWithDevice>(state.choosenTask[0])); }else{ get_messages<typename defs::taskSendOutDevice>(bags).push_back(get<CommandWithDevice>(state.choosenTask[0])); } break; case Task::DO_ACTION: get_messages<typename defs::taskDoActionOut>(bags).push_back(get<Action2Do>(state.choosenTask[0])); break; case Task::IDLE: break; default: assert(false && "the task state is not implemented or does not exists"); break; } //switch(get<Task>(state.choosenTask[0])){ // case Task::ANSWER: // cout << get<Communication>(state.choosenTask[0]); // break; // case Task::SEND: // cout << get<CommandWithDevice>(state.choosenTask[0]); // break; // case Task::DO_ACTION: // cout << get<Action2Do>(state.choosenTask[0]); break; // case Task::IDLE: break; // default: assert(false && "the task state is not implemented or does not exists"); break; //} return bags; } // time_advance function TIME time_advance() const { return state.advanceTime; } friend std::ostringstream& operator<<(std::ostringstream& os, const typename PersonBehaviorRules<TIME>::state_type& i) { os << "advanceTime: "<< i.advanceTime << " answerRequests: " << i.answerRequests.size() << " commands2Send " << i.commands2Send.size() << ": "; for (int j = 0; j < i.commands2Send.size(); j++){ os << i.commands2Send[j].to << " " << i.commands2Send[j].content << ";"; } return os; } /*****************************/ /**** AUXILIARY FUNCTIONS ****/ /*****************************/ bool is_device_busy(DeviceType device, const vector<DeviceType> & devicesBusy){ bool isBusy = false; for(int i=0; i<devicesBusy.size();i++){ if(device == devicesBusy[i]){ isBusy = true; break; } } return isBusy; } vector<Msg2Send> extract_commnads_to_send_from_command(const Command & command, const DecisionMakerBehaviour& behaviour){ vector<Msg2Send> auxcommands2Send; vector<Msg2Send> commands2Send; for(int i = 0; i<behaviour.msgBehaviour.size(); i++){ if(command.command == behaviour.msgBehaviour[i].content && command.from == behaviour.msgBehaviour[i].from){ auxcommands2Send = behaviour.msgBehaviour[i].msg2send; break; } } /** Decide if send or not the ones that are not compulsory **/ /** Send with 50% probability when they are not compulsory **/ for(int i = 0; i<auxcommands2Send.size(); i++){ if(auxcommands2Send[i].compulsory){ commands2Send.push_back(auxcommands2Send[i]); }else{ bool send; #ifdef SEND_NEVER_OPTIONAL send = false; #elif SEND_ALWAYS_OPTIONAL send = true; #else unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // seed variable is used to ensure a different set of results for each simulation srand (seed); int a = rand() % 1; (a == 0) ? send = false : send = true; #endif if(send) commands2Send.push_back(auxcommands2Send[i]); } } return commands2Send; } vector<ActionBehaviour> extract_actions_to_do_from_command(const Command & command, const DecisionMakerBehaviour& behaviour){ vector<string> auxActions2Do; vector<ActionBehaviour> actions2Do; for(int i = 0; i<behaviour.msgBehaviour.size(); i++){ if(command.command == behaviour.msgBehaviour[i].content && command.from == behaviour.msgBehaviour[i].from){ auxActions2Do = behaviour.msgBehaviour[i].actions2Do; break; } } for(int i = 0; i<auxActions2Do.size(); i++){ for(int j=0; j<behaviour.actionBehaviour.size(); j++){ if(auxActions2Do[i] == behaviour.actionBehaviour[j].id){ actions2Do.push_back(behaviour.actionBehaviour[j]); break; } } } return actions2Do; } Msg2Send extract_command_just_sent(const Command & command, const vector<Msg2Send> & commands2Send){ Msg2Send commandSent; for(int i = 0; i<commands2Send.size(); i++){ if(command.command == commands2Send[i].content && command.to == commands2Send[i].to){ commandSent = commands2Send[i]; break; } } return commandSent; } ActionBehaviour extract_action_done_from_actions2Do(string actionId, const vector<ActionBehaviour> & actions2Do){ ActionBehaviour actionDone; for(int i = 0; i<actions2Do.size(); i++){ if(actionId == actions2Do[i].id){ actionDone = actions2Do[i]; break; } } return actionDone; } vector<TaskPriorityType> extract_task_with_priority_j(int j, const DecisionMakerBehaviour& behaviour){ vector<TaskPriorityType> same_priority; for(int i = 0; i < behaviour.taskPrioritized.size();i++){ if(behaviour.taskPrioritized[i].priority == j) same_priority.push_back(behaviour.taskPrioritized[i].task); } return same_priority; } vector<pair<DeviceId,Communication>> const extract_requests_with_same_device_priority(const vector<pair<DeviceId,Communication>> & answerRequests, const DecisionMakerBehaviour& behaviour){ vector<pair<DeviceId,Communication>> same_priority; int highestPriority = 999; for(int i =0; i < behaviour.answerDevicePriority.size();i++){ //Devices with same priority level for(int z = 0; z < answerRequests.size(); z++){ if(answerRequests[z].first.type == behaviour.answerDevicePriority[i].device && behaviour.answerDevicePriority[i].priority < highestPriority) highestPriority = behaviour.answerDevicePriority[i].priority; if(highestPriority == 1) break; } } if(highestPriority < 999){ for(int i = 0; i < behaviour.answerDevicePriority.size(); i++){ for(int z = 0; z < answerRequests.size(); z++){ if(behaviour.answerDevicePriority[i].priority == highestPriority && answerRequests[z].first.type == behaviour.answerDevicePriority[i].device) same_priority.push_back(answerRequests[z]); } } }else{ same_priority = answerRequests; } return same_priority; } vector<pair<DeviceId,Communication>> const extract_requests_with_same_person_priority(const vector<pair<DeviceId,Communication>> & answerRequests, const DecisionMakerBehaviour& behaviour){ vector<pair<DeviceId,Communication>> same_priority; int highestPriority = 999; for(int i =0; i < behaviour.answerPersonPriority.size();i++){ //Person with same priority level for(int z = 0; z < answerRequests.size(); z++){ if(answerRequests[z].first.id == behaviour.answerPersonPriority[i].personId && behaviour.answerPersonPriority[i].priority < highestPriority) highestPriority = behaviour.answerPersonPriority[i].priority; if(highestPriority == 1) break; } } if(highestPriority < 999){ for(int i = 0; i < behaviour.answerPersonPriority.size(); i++){ for(int z = 0; z < answerRequests.size(); z++){ if(behaviour.answerPersonPriority[i].priority == highestPriority && answerRequests[z].first.id == behaviour.answerPersonPriority[i].personId) same_priority.push_back(answerRequests[z]); } } }else{ same_priority = answerRequests; } return same_priority; } pair<DeviceType, DeviceType> const choose_com_channel(const Msg2Send& command, const DecisionMakerBehaviour& behaviour){ pair<DeviceType, DeviceType> device_choosen; // from - to bool in_person_available = false; std::vector<DeviceType> devices_to; bool person_found = false; for(int i = 0; i<behaviour.peopleSameLocation.size();i++){ if(command.to == behaviour.peopleSameLocation[i]){ in_person_available = true; break; } } for(int i = 0; i<behaviour.communicationRelations.size(); i++){ if(command.to == behaviour.communicationRelations[i].personId){ devices_to = behaviour.communicationRelations[i].devices;//Retrieve the list of channels I can use with that person person_found = true; break; } } assert(command.deviceCompulsory.size() <= 1 && "Only one device compulsory is accepted" ); DeviceType compulsory; (command.deviceCompulsory.empty()) ? compulsory = DeviceType::IDLE : compulsory = command.deviceCompulsory[0]; if(compulsory != DeviceType::IDLE){ bool compulsoryDeviceAvailable = false; for(int i = 0; i<devices_to.size(); i++){ if(compulsory == devices_to[i]){ compulsoryDeviceAvailable = true; devices_to.clear(); devices_to.push_back(compulsory); break; } } if(compulsoryDeviceAvailable == false) devices_to.clear(); } if(in_person_available && compulsory == DeviceType::IDLE){ device_choosen = make_pair(DeviceType::IN_PERSON, DeviceType::IN_PERSON); }else{ if(person_found){ for(int i = 0; i < devices_to.size(); i++){ //choose the first one in the list that is available switch(devices_to[i]){ case DeviceType::MOBILEPHONE: case DeviceType::LANDLINEPHONE: for(int j = 0; j < behaviour.myDevices.size(); j++){ if(behaviour.myDevices[j].device == DeviceType::MOBILEPHONE || behaviour.myDevices[j].device == DeviceType::LANDLINEPHONE){ device_choosen = make_pair(behaviour.myDevices[j].device, devices_to[i]); i = devices_to.size(); break; } } break; case DeviceType::EMAIL: case DeviceType::BEEPER: case DeviceType::FAX: case DeviceType::SATELLITE_PHONE: case DeviceType::RADIOLOGICAL_GROUP_DEVICE: case DeviceType::PRIVATELINEPHONE: case DeviceType::RADIO_REMAN: case DeviceType::RADIO_REMER: case DeviceType::TRANKI_GC: case DeviceType::TRANKI_E: for(int j = 0; j < behaviour.myDevices.size(); j++){ if(behaviour.myDevices[j].device == devices_to[i]){ device_choosen = make_pair(behaviour.myDevices[j].device, devices_to[i]); i = devices_to.size(); break; } } break; default: assert(false && "DEVICE NOT IMPLEMENTED"); } } }else{ device_choosen = make_pair(DeviceType::IDLE, DeviceType::IDLE); } } return device_choosen; } vector<Msg2Send> const extract_commands_with_same_pripority(const vector<Msg2Send>& commands2Send, const DecisionMakerBehaviour& behaviour){ vector<Msg2Send> same_priority; int highestPriority = 999; for(int i =0; i < behaviour.sendCommandPriority.size();i++){ //Highest priority level for(int z = 0; z < commands2Send.size(); z++){ if(commands2Send[z].to == behaviour.sendCommandPriority[i].to && commands2Send[z].content == behaviour.sendCommandPriority[i].msg &&behaviour.sendCommandPriority[i].priority < highestPriority) highestPriority = behaviour.sendCommandPriority[i].priority; if(highestPriority == 1) break; } } if(highestPriority < 999){ for(int i = 0; i < behaviour.sendCommandPriority.size(); i++){ for(int z = 0; z < commands2Send.size(); z++){ if(behaviour.sendCommandPriority[i].priority == highestPriority && commands2Send[z].to == behaviour.sendCommandPriority[i].to && commands2Send[z].content == behaviour.sendCommandPriority[i].msg) same_priority.push_back(commands2Send[z]); } } }else{ same_priority = commands2Send; } return same_priority; } vector<ActionBehaviour> extract_actions_with_same_pripority(const vector<ActionBehaviour> actions2Do, const DecisionMakerBehaviour& behaviour){ //The actions are ordered in actionExecutionPriority based on priority vector<ActionBehaviour> actionsSamePriority; for(int i =0; i < behaviour.actionExecutionPriority.size();i++){ //Find action with highest priority for(int z = 0; z < actions2Do.size(); z++){ if(actions2Do[z].id == behaviour.actionExecutionPriority[i]){ actionsSamePriority.push_back(actions2Do[z]); break; //for z break; //for i } } } if(actionsSamePriority.empty()) actionsSamePriority = actions2Do; return actionsSamePriority; } }; #endif // CADMIUM_DECISION_MAKER_HPP
53.974542
350
0.56244
[ "vector", "model" ]
f06ba6ed95b6e6488a38de65f9f1bcec2a0a2e96
1,383
cpp
C++
leetcode/628.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
leetcode/628.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
leetcode/628.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
/* Maximum Product of Three Numbers Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. */ #include <vector> #include <iostream> #include <algorithm> #include <climits> using namespace std; class Solution { public: int maximumProduct(vector<int>& nums) { if (nums.size() == 3) return nums[0] * nums[1] * nums[2]; int len = nums.size(); int min1 = INT_MAX, min2 = INT_MAX; int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; for (auto i : nums){ if (i > max1) { max3 = max2; max2 = max1; max1 = i; } else if (i > max2){ max3 = max2; max2 = i; } else if (i > max3){ max3 = i; } if (i < min1){ min2 = min1; min1 = i; } else if (i < min2){ min2 = i; } } return max(min1 * min2 * max1, max1 * max2 * max3); } };
21.952381
103
0.503977
[ "vector" ]
f0730972eab9a31135c4a41e68cd384414cb60f2
4,185
cpp
C++
demo_graph1.cpp
igormcoelho/cycles
0864cacb0585fc4d55a49878e14b10acd1300059
[ "MIT" ]
1
2022-02-18T01:32:44.000Z
2022-02-18T01:32:44.000Z
demo_graph1.cpp
igormcoelho/cycles
0864cacb0585fc4d55a49878e14b10acd1300059
[ "MIT" ]
null
null
null
demo_graph1.cpp
igormcoelho/cycles
0864cacb0585fc4d55a49878e14b10acd1300059
[ "MIT" ]
null
null
null
#include <map> #include "Graph.hpp" #include "XNode.hpp" // #include <cycles/List.hpp> #include <cycles/Tree.hpp> #include <cycles/cycle_ptr.hpp> #include <cycles/nodes_exp.hpp> #include <cycles/utils.hpp> using std::string, std::vector, std::map; int main() { // graph - part 1 { std::cout << std::endl; std::cout << " -------- DEMO GRAPH1: SIMPLE GRAPH TESTING -------- " << std::endl; std::cout << std::endl; Graph g; g.vertex.push_back(Vertice { .label = "1" }); g.vertex.push_back(Vertice { .label = "2" }); // g.print(); // // Is this a "CyclicArena"? An arena that has different lifetimes per cycles, not the whole arena? vector<sptr<XNode>> all_nodes; // // register new node (through some factory "CyclicArena" method, get_new_node()?) all_nodes.push_back(sptr<XNode> { new XNode { 0 } }); all_nodes.push_back(sptr<XNode> { new XNode { 1 } }); all_nodes.push_back(sptr<XNode> { new XNode { 2 } }); all_nodes.push_back(sptr<XNode> { new XNode { 3 } }); all_nodes.push_back(sptr<XNode> { new XNode { 4 } }); all_nodes.push_back(sptr<XNode> { new XNode { 5 } }); all_nodes.push_back(sptr<XNode> { new XNode { 6 } }); // // DISPOSALS will only possible when this "main" node ref is dropped... // it means that real-time systems can take good care of these references, // and let the "internal world explode", when it's convenient // vector<List<XEdge<sptr<XNode>>>> cycles; List<XEdge<sptr<XNode>>> empty_list; cycles.push_back(empty_list); // 0 cycles.push_back(empty_list); // 1 vector<int> ref_cycles; ref_cycles.push_back(-1); // 0 ref_cycles.push_back(-1); // 1 ref_cycles.push_back(-1); // 2 // // create edge 1->2, where 1 is owner of 2 // // does 1 have a cycle already? if not create one (HEAD to 1) cycles[1].push_back(all_nodes[1]); ref_cycles[1] = 1; // OWNER is 1 // if FROM 1 to destination 2 not have cycle, just add 2 after position of node 1 in cycle 1 cycles[1].push_back(all_nodes[2]); ref_cycles[2] = 1; // OWNER is 1 // // create edge 2->3, where 2 is owner of 3 // // does 2 have a cycle already? Resp.: 1. So follow it, and put 3 from position of node 2 in cycle 1 // (just assuming last node is used here) cycles[1].push_back(all_nodes[3]); ref_cycles[3] = 1; // OWNER is 1 // // // create edge 3->6, where 3 is owner of 6 // // does 3 have a cycle already? Resp.: 1. So follow it, and put 6 from position of node 3 in cycle 1 // (just assuming last node is used here) cycles[1].push_back(all_nodes[6]); // List<XEdge<XNode>> l_A; l_A.push_back(XNode { 1 }); l_A.push_back(XNode { 2 }); l_A.push_back(XNode { 3 }); l_A.push_back(XEdge(XNode { 6 }, false)); // l_A.push_front(XEdge(6, false)); // l_A.push_front(3); // l_A.push_front(2); // l_A.push_front(1); std::cout << "X head to "; l_A.print(); std::cout << "A: " << l_A.head.get() << std::endl; // List<XEdge<XNode>> l_B; l_B.push_front(XNode { 6 }); l_B.push_front(XNode { 13 }); l_B.push_front(XNode { 12 }); l_B.push_front(XNode { 8 }); l_B.push_front(XNode { 7 }); l_B.push_front(XNode { 10 }); std::cout << "head to "; l_B.print(); std::cout << "B: " << l_B.head.get() << std::endl; // List<XEdge<XNode>> l_C; l_C.push_front(XEdge(XNode { 8 }, false)); l_C.push_front(XNode { 11 }); l_C.push_front(XNode { 7 }); std::cout << "head to "; l_C.print(); std::cout << "C: " << l_C.head.get() << std::endl; // List<XEdge<XNode>> l_D; l_D.push_front(XEdge(XNode { 7 }, false)); l_D.push_front(XNode { 3 }); std::cout << "head to "; l_D.print(); std::cout << "D: " << l_D.head.get() << std::endl; // List<XEdge<XNode>> l_E; l_E.push_front(XEdge(XNode { 3 }, false)); l_E.push_front(XNode { 4 }); l_E.push_front(XNode { 8 }); std::cout << "head to "; l_E.print(); std::cout << "E: " << l_E.head.get() << std::endl; // } std::cout << "FINISHED!" << std::endl; return 0; }
31.946565
104
0.58638
[ "vector" ]
7ec3ea9d289180febe9b484be20e47bf1e16d16b
12,957
cpp
C++
test/lisp/testCompiler.cpp
BowenFu/lisp.cpp
31082b607d11340f4ced4289d2dd2a42673d2708
[ "Apache-2.0" ]
null
null
null
test/lisp/testCompiler.cpp
BowenFu/lisp.cpp
31082b607d11340f4ced4289d2dd2a42673d2708
[ "Apache-2.0" ]
30
2021-08-24T14:33:09.000Z
2022-01-01T13:18:00.000Z
test/lisp/testCompiler.cpp
BowenFu/lisp.cpp
31082b607d11340f4ced4289d2dd2a42673d2708
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "lisp/compiler.h" #include "lisp/metaParser.h" #include "lisp/parser.h" #include <numeric> TEST(Compiler, number) { Compiler c{}; c.compile(ExprPtr{new Number{5.5}}); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "5.5\n"); } TEST(Compiler, string) { Compiler c{}; c.compile(ExprPtr{new String{"5.5 abcdefg"}}); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "\"5.5 abcdefg\"\n"); } TEST(Compiler, add) { Compiler c{}; ExprPtr num1{new Number{5.5}}; ExprPtr num2{new Number{1.1}}; ExprPtr num3{new Number{2.2}}; ExprPtr op{new Variable{"+"}}; ExprPtr add{new Application{op, {num1, num2, num3}}}; c.compile(add); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "8.8\n"); } TEST(Compiler, div) { Compiler c{}; ExprPtr num1{new Number{5.5}}; ExprPtr num2{new Number{1.1}}; ExprPtr op{new Variable{"/"}}; ExprPtr add{new Application{op, {num1, num2}}}; c.compile(add); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "5\n"); } TEST(Compiler, bool1) { Compiler c{}; c.compile(true_()); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "true\n"); } TEST(Compiler, bool3) { Compiler c{}; ExprPtr num1{new Number{5.5}}; ExprPtr num2{new Number{1.1}}; ExprPtr op1{new Variable{"<"}}; ExprPtr op2{new Variable{"not"}}; ExprPtr comp{new Application{op1, {num1, num2}}}; ExprPtr comp2{new Application{op2, {comp}}}; c.compile(comp2); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "true\n"); } TEST(Compiler, if) { Compiler c{}; ExprPtr num1{new Number{5.5}}; ExprPtr num2{new Number{1.1}}; ExprPtr op{new Variable{"<"}}; ExprPtr comp{new Application{op, {num1, num2}}}; ExprPtr min{new If{comp, num1, num2}}; c.compile(min); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "1.1\n"); } TEST(Compiler, definition) { Compiler c{}; ExprPtr num{new Number{5.5}}; auto const name = "num"; ExprPtr def{new Definition{name, num}}; c.compile(def); ExprPtr var{new Variable{name}}; c.compile(var); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "5.5\n"); } TEST(Compiler, lambda0) { Compiler c{}; ExprPtr num{new Number{5.5}}; std::shared_ptr<Sequence> seq{new Sequence{{num}}}; ExprPtr func{new Lambda{Params{std::make_pair(std::vector<std::string>{}, false)}, seq}}; auto const name = "getNum"; ExprPtr def{new Definition{name, func}}; c.compile(def); ExprPtr var{new Variable{name}}; c.compile(var); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "Closure getNum\n"); } TEST(Compiler, lambda1) { Compiler c{}; ExprPtr iVar{new Variable{"i"}}; std::shared_ptr<Sequence> seq{new Sequence{{iVar}}}; ExprPtr func{new Lambda{Params{std::make_pair(std::vector<std::string>{"i"}, false)}, seq}}; auto const name = "identity"; ExprPtr def{new Definition{name, func}}; c.compile(def); ExprPtr var{new Variable{name}}; c.compile(var); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "Closure identity\n"); } TEST(Compiler, lambda2) { Compiler c{}; ExprPtr num{new Number{5.5}}; ExprPtr iVar{new Variable{"i"}}; std::shared_ptr<Sequence> seq{new Sequence{{iVar}}}; ExprPtr func{new Lambda{Params{std::make_pair(std::vector<std::string>{"i"}, false)}, seq}}; auto const name = "identity"; ExprPtr def{new Definition{name, func}}; c.compile(def); ExprPtr var{new Variable{name}}; ExprPtr app{new Application{var, {num}}}; c.compile(app); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "5.5\n"); } TEST(Compiler, lambda3) { Compiler c{}; ExprPtr num{new Number{5.5}}; ExprPtr iVar{new Variable{"i"}}; ExprPtr plusVar{new Variable{"+"}}; ExprPtr doubleApp{new Application{plusVar, {iVar, iVar}}}; std::shared_ptr<Sequence> seq{new Sequence{{doubleApp}}}; ExprPtr func{new Lambda{Params{std::make_pair(std::vector<std::string>{"i"}, false)}, seq}}; auto const name = "double"; ExprPtr def{new Definition{name, func}}; c.compile(def); ExprPtr var{new Variable{name}}; ExprPtr app{new Application{var, {num}}}; c.compile(app); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "11\n"); } TEST(Compiler, Variadiclambda) { Compiler c{}; ExprPtr num{new Number{5.5}}; ExprPtr iVar{new Variable{"i"}}; std::shared_ptr<Sequence> seq{new Sequence{{iVar}}}; ExprPtr func{new Lambda{Params{std::make_pair(std::vector<std::string>{"i"}, true)}, seq}}; auto const name = "list"; ExprPtr def{new Definition{name, func}}; c.compile(def); ExprPtr var{new Variable{name}}; ExprPtr app{new Application{var, {num}}}; c.compile(app); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(5.5)\n"); } TEST(Compiler, consCar) { Compiler c{}; ExprPtr num{new Number{5.5}}; auto const name1 = "cons"; ExprPtr var1{new Variable{name1}}; ExprPtr app1{new Application{var1, {num, num}}}; auto const name2 = "cdr"; ExprPtr var2{new Variable{name2}}; ExprPtr app2{new Application{var2, {app1}}}; c.compile(app2); vm::ByteCode code = c.code(); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "5.5\n"); } auto sourceToBytecode(std::string const& source) { Lexer lex(source); MetaParser p(lex); Compiler c{}; while (!p.eof()) { auto e = parse(p.sexpr()); c.compile(e); } return c.code(); } TEST(Compiler, square) { std::string const source = "(define square (lambda (y) (* y y))) (square 7)"; auto code = sourceToBytecode(source); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "49\n"); } TEST(Compiler, factorial) { std::string const source = "(define factorial (lambda (y) (if (= y 0) 1 (* y (factorial (- y 1)))))) (factorial 5)"; auto code = sourceToBytecode(source); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "120\n"); } TEST(Compiler, rest) { std::string const source = "(define rest (lambda (_ . y) y)) (rest 1 2 3)"; auto code = sourceToBytecode(source); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(2 3)\n"); } TEST(Compiler, freeVars) { std::string const source = " (define (my-cons car cdr) (lambda (dispatch) (if (= dispatch 'my-car) car cdr))) ((my-cons 1 2) 'my-cdr)"; auto code = sourceToBytecode(source); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "2\n"); } TEST(Compiler, localBinding) { std::string const source = " (define (my-cons car cdr) (define x car) (define y cdr) (lambda (dispatch) (if (= dispatch 'my-car) x y))) ((my-cons 1 2) 'my-car)"; auto code = sourceToBytecode(source); code.instructions.push_back(vm::kPRINT); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "1\n"); } TEST(Compiler, print) { std::string const source = " (define (show-cons car cdr) (define x car) (define y cdr) (lambda (dispatch) (print (if (= dispatch 'show-car) x y)))) ((show-cons 1 2) 'show-car)"; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "1\n"); } TEST(Compiler, len) { std::string const source = "(define (len lst) (if (null? lst) 0 (+ 1 (len (cdr lst))))) (define (list . lst) lst) (print (len (list)))"; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "0\n"); } TEST(Compiler, listStar) { std::string const source = "(define list*" "(lambda args" "(define $f" "(lambda (xs)" "(if (cons? xs)" "(if (cons? (cdr xs))" "(cons (car xs) ($f (cdr xs)))" "(car xs))" "null)))" "($f args)" "))" "(print (list* 1 2))" ; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(1 . 2)\n"); } TEST(Compiler, unquote) { std::string const source = "(print `(1 `,(+ 1 ,(+ 2 3)) 4))"; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(1 ('quasiquote ('unquote ('+ 1 5))) 4)\n"); } TEST(Compiler, splicing1) { std::string const source = "(print `(,@`(1 2 3) 4 5))"; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(1 2 3 4 5)\n"); } TEST(Compiler, splicing2) { std::string const source = "(print `(1 ```,,@,,@`(+ 1 2) 4))"; auto code = sourceToBytecode(source); vm::VM vm{code}; testing::internal::CaptureStdout(); vm.run(); std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "(1 ('quasiquote ('quasiquote ('quasiquote ('unquote ('unquote-splicing ('unquote '+ 1 2)))))) 4)\n"); }
31.146635
181
0.607239
[ "vector" ]
7ecb83d90dff1f07ce55c61ac97f49abb06dd97a
11,826
cpp
C++
EWLS.cpp
David-Xiang/MaxClique
289800bc1271d2117bb6cee0faca592591bdece7
[ "MIT" ]
null
null
null
EWLS.cpp
David-Xiang/MaxClique
289800bc1271d2117bb6cee0faca592591bdece7
[ "MIT" ]
null
null
null
EWLS.cpp
David-Xiang/MaxClique
289800bc1271d2117bb6cee0faca592591bdece7
[ "MIT" ]
1
2019-02-02T15:42:08.000Z
2019-02-02T15:42:08.000Z
9/* NOTE: 1. We use EWLS to solve Minimal Vertex Cover of complement graph(补图) \bar G. MaxClique(G) = V(G) - MinimalVertexCover(\bar G) **Thus G[][] actually is \bar G.** 2.Weight of edges are stored in G[][]. Because G is an undirected graph thus the matrix G is always symmetric. 3.Please delete '#define _DEBUG' before submitting the code. Current Score: 149 */ #define _DEBUG // delete this line before submitting! #include <iostream> #include <cstdio> #include <cstring> #include <set> #include <list> #include <vector> #include <utility> #define ioOptimizer ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 760 #define INF (1 << 30) using namespace std; int N; int tabuAdd, tabuRemove; int G[MAXN][MAXN]; typedef set<int> Vertices; struct Edge{ int from, to; Edge(int f, int t){ from = f; to = t; } }; int cost(Vertices& C){ int ans = 0; for (int i = 0; i < N - 1; i++){ if (C.find(i) != C.end()) // i in C continue; for (int j = i + 1; j < N; j++){ if (C.find(j) != C.end()) // j in C continue; // both i and j are not in C ans += G[i][j]; } } return ans; } int dscore(Vertices& C, int v){ int ans = 0; for (int i = 0; i < N; i++){ if (C.find(i) == C.end()){ // i not in C, thus cost(C) will increase // if we remove v from C ans += G[v][i]; } } if (C.find(v) != C.end()){ // v in C, we have to reverse the sign of dscore ans = -ans; } return ans; } int score(Vertices& C, int u, int v){ #ifdef _DEBUG assert(C.find(u) != C.end()); assert(C.find(v) == C.end()); #endif return dscore(C, u) + dscore(C, v) + G[u][v]; // (u,v) is not an edge <=> G[u][v] = 0 } void copy(Vertices& src, Vertices& des){ // just shallow copy des.clear(); for (Vertices::iterator i = src.begin(); i != src.end(); i++) des.insert(*i); } #ifdef _DEBUG bool isSymmetric(int G[][MAXN], int n){ // used for DEBUG for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (G[i][j] != G[j][i]) return false; } } return true; } #endif #ifdef _DEBUG bool isClique(Vertices& C){ // used for DEBUG for (Vertices::iterator i = C.begin(); i != C.end(); i++){ for (Vertices:: iterator j = C.begin(); j != C.end(); j++){ if (*i == *j) continue; if (G[*i][*j] == 1) return false; } } return true; } #endif #ifdef _DEBUG bool isVertexCover(Vertices& C){ // used for DEBUG for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ if (G[i][j] == 0) // (i, j) is not an edge continue; bool find = false; // i or j must be in C for (Vertices::iterator k = C.begin(); k != C.end(); k++){ if (*k == i || *k == j){ find = true; break; } } if (!find) return false; } } return true; } #endif void remove(list<Edge>& L, list<Edge>::iterator unchecked, int v){ // remove all edges in L with endpoint v for(list<Edge>::iterator i = L.begin(); i != L.end(); ){ if ((*i).from == v || (*i).to == v){ if (unchecked == i) unchecked++; L.erase(i++); } else i++; } } void insert(list<Edge>& L, Vertices& C, int u){ // insert edges {(u, i) | i not in C} to L for(int i = 0; i < N; i++){ if (G[u][i] != 0 && C.find(i) == C.end()){ // (u, i) exists and i is not in C // always insert to the front of L L.push_front(Edge(u, i)); } } } void resize(Vertices& C, list<Edge>& L, int capacity){ while (C.size() > capacity){ // selects vertices with the highest dscore in C // TODO: breaking ties randomly int maxd = -INF; Vertices::iterator id; for (Vertices::iterator j = C.begin(); j != C.end(); j++){ int d = dscore(C, *j); if(d > maxd){ maxd = d; id = j; } } C.erase(id); // insert edges to L int u = *id; insert(L, C, u); } } void greedyVC(Vertices& C, list<Edge>& L, list<Edge>::iterator unchecked){ // use greedy algo to expand C to a vertex cover while(!L.empty()){ int maxcnt = 0; int id = -1; for (int i = 0; i < N; i++){ if (C.find(i) != C.end()) // i in C <=> i not in L continue; int cnt = 0; // count how many times i occurs in L for (list<Edge>::iterator j = L.begin(); j != L.end(); j++) if ((*j).from == i || (*j).to == i) cnt++; if (cnt > maxcnt){ maxcnt = cnt; id = i; } } remove(L, unchecked, id); C.insert(id); } } pair<int, int> ChooseSwapPair(Vertices& C, list<Edge>& L, list<Edge>::iterator unchecked){ // TODO: return random(s) int v; // check e(oldest) list<Edge>::iterator i = L.end(); i--; v = (*i).from; for (int u = 0; u < N && v != tabuAdd; u++){ if (C.find(u) != C.end() && u != tabuRemove && score(C, u, v) > 0) return make_pair(u, v); } v = (*i).to; for (int u = 0; u < N && v != tabuAdd; u++){ if (C.find(u) != C.end() && u != tabuRemove && score(C, u, v) > 0) return make_pair(u, v); } // search UL from old to young do{ unchecked--; v = (*unchecked).from; for (int u = 0; u < N && v != tabuAdd; u++){ if (C.find(u) != C.end() && u != tabuRemove && score(C, u, v) > 0) return make_pair(u, v); } v = (*unchecked).to; for (int u = 0; u < N && v != tabuAdd; u++){ if (C.find(u) != C.end() && u != tabuRemove && score(C, u, v) > 0) return make_pair(u, v); } }while(unchecked!=L.begin()); // swappair not found return make_pair(0, 0); } void EWLS(int delta, int maxSteps, Vertices& Cstar){ // init L and UL // UL ⊆ L is the set of those unchecked by ChooseSwapPair // in the current local search stage list<Edge> L; list<Edge>::iterator unchecked; for (int i = 0; i < N-1; i++) for (int j = i+1; j < N; j++) if (G[i][j] > 0) L.push_back(Edge(i, j)); unchecked = L.end(); // initialize C using greedy algo Vertices C; C.clear(); while(!L.empty()){ // vertex with the highest dscore is added to C // TODO: breaking ties randomly int maxd = -INF; int id = -1; for (int i = 0; i < N; i++){ if (C.find(i) != C.end()) // i already in C continue; int d = dscore(C, i); if (d > maxd){ maxd = d; id = i; } } remove(L, unchecked, id); C.insert(id); } copy(C, Cstar); // update Cstar #ifdef _DEBUG assert(isVertexCover(Cstar)); #endif int ub = int(C.size()); // update resize(C, L, ub-delta); // delete |delta| vertices from C for (int step = 0; step < maxSteps; step++){ #ifdef _DEBUG printf("round %d\n", step); #endif pair<int, int> p = ChooseSwapPair(C, L, unchecked); int u = p.first; int v = p.second; if (u == 0 || v == 0){ // this IF block corresponds to the ELSE block in Cai's Paper // update w(e) = w(e) + 1 for each e in L int randomL = (rand() % N); // pick random position of v for (list<Edge>::iterator i = L.begin(); i != L.end(); i++) { int from = (*i).from; int to = (*i).to; if (!randomL) v = (*i).from; // get v randomL--; G[from][to]++; G[to][from]++; } // TODO: random chooose u u = (*C.begin()); // v = (*L.begin()).from; } tabuAdd = u; tabuRemove = v; // update C by adding v and removing u C.erase(u); C.insert(v); // update L by adding edges(u, j) and removing edges(v, j) insert(L, C, u); remove(L, unchecked, v); if (C.size() + L.size() < ub){ ub = int(C.size() + L.size()); if (!L.empty()){ greedyVC(C, L, unchecked); } copy(C, Cstar); #ifdef _DEBUG printf("|Vertex Cover|: %d\n", int(Cstar.size())); assert(isVertexCover(Cstar)); #endif resize(C, L, ub-delta); // delete |delta| vertices from C } } #ifdef _DEBUG assert(isSymmetric(G, N)); #endif } void solve(int delta, int maxSteps){ int M; Vertices C; bool ans[MAXN]; while(scanf("%d%d", &N, &M) != EOF){ C.clear(); memset(ans, 0, sizeof(ans)); for(int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ if (i == j) continue; G[i][j] = 1; } } for(int i = 0; i < M; i++){ int u, v; scanf("%d%d", &u, &v); // index starts from 0 G[u-1][v-1] = 0; G[v-1][u-1] = 0; } EWLS(delta, maxSteps, C); printf("%d\n", int(N-C.size())); for (Vertices::iterator i = C.begin(); i != C.end(); i++){ ans[*i] = 1; } Vertices A; for (int i = 0; i < N; i++){ if (ans[i] == 0) A.insert(i); } #ifdef _DEBUG assert(isClique(A)); #endif for (Vertices::iterator i = A.begin(); i != A.end(); i++){ printf("%d ", (*i)+1); } printf("\n"); } } void solveFile(const char* path, int delta, int maxSteps){ int M; Vertices C; bool ans[MAXN]; freopen(path, "r", stdin); if(scanf("%d %d ", &N, &M) != EOF){ printf("N:%d M:%d\n", N, M); C.clear(); memset(ans, 0, sizeof(ans)); for(int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ if (i == j) continue; G[i][j] = 1; } } for(int i = 0; i < M; i++){ int u, v; scanf("%d %d ", &u, &v); // if (i < 5 || i > M - 5) // printf("%d %d\n", u, v); // index starts from 0 G[u-1][v-1] = 0; G[v-1][u-1] = 0; } EWLS(delta, maxSteps, C); printf("%d\n", int(N-C.size())); for (Vertices::iterator i = C.begin(); i != C.end(); i++){ ans[*i] = 1; } Vertices A; for (int i = 0; i < N; i++){ if (ans[i] == 0) A.insert(i); } #ifdef DEBUG assert(isClique(A)); #endif for (Vertices::iterator i = A.begin(); i != A.end(); i++){ printf("%d ", (*i)+1); } printf("\n"); } } int main(){ // try different params! // Openjudge // solve(10, 200); // Local test sample // const char* path = "/samples/frb30.txt"; // solveFile(path, 10, 200); return 0; }
26.048458
78
0.428378
[ "vector" ]
7ecc368db6f4a5c87667cc69e0f66e387f17bfcf
7,930
cpp
C++
src/lib/client/FavoritesController.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/lib/client/FavoritesController.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/lib/client/FavoritesController.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2021 Grant Erickson * 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. * */ /** * @file * This file implements an object for managing the client-side * observation and mutation of a collection of HLX favorites. * */ #include "FavoritesController.hpp" #include <memory> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdlib.h> #include <LogUtilities/LogUtilities.hpp> #include <OpenHLX/Client/CommandManager.hpp> #include <OpenHLX/Client/FavoritesControllerCommands.hpp> #include <OpenHLX/Client/FavoritesStateChangeNotifications.hpp> #include <OpenHLX/Model/FavoriteModel.hpp> #include <OpenHLX/Utilities/Assert.hpp> using namespace HLX::Common; using namespace HLX::Model; using namespace HLX::Utilities; using namespace Nuovations; namespace HLX { namespace Client { /** * @brief * This is the class default constructor. * */ FavoritesController :: FavoritesController(void) : Common::FavoritesControllerBasis(), Client::FavoritesControllerBasis(Common::FavoritesControllerBasis::mFavorites, Common::FavoritesControllerBasis::kFavoritesMax) { return; } /** * @brief * This is the class destructor. * */ FavoritesController :: ~FavoritesController(void) { return; } // MARK: Initializer(s) /** * @brief * This is the class initializer. * * This initializes the class with the specified command manager and * timeout. * * @param[in] aCommandManager A reference to the command manager * instance to initialize the controller * with. * @param[in] aTimeout The timeout to initialize the controller * with that will serve as the timeout for * future operations with the peer server. * * @retval kStatus_Success If successful. * @retval -EINVAL If an internal parameter was * invalid. * @retval -ENOMEM If memory could not be allocated. * @retval kError_NotInitialized The base class was not properly * initialized. * @retval kError_InitializationFailed If initialization otherwise failed. * */ Status FavoritesController :: Init(CommandManager &aCommandManager, const Timeout &aTimeout) { DeclareScopedFunctionTracer(lTracer); constexpr bool kRegister = true; Status lRetval = kStatus_Success; lRetval = Common::FavoritesControllerBasis::Init(); nlREQUIRE_SUCCESS(lRetval, done); lRetval = Client::FavoritesControllerBasis::Init(aCommandManager, aTimeout); nlREQUIRE_SUCCESS(lRetval, done); // This MUST come AFTER the base class initialization due to a // dependency on the command manager instance. lRetval = DoNotificationHandlers(kRegister); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } // MARK: Observer Methods /** * @brief * Get the favorite model associated with specified favorite * identifier. * * @param[in] aIdentifier An immutable reference to the favorite * model to obtain. * @param[out] aModel A reference to an immutable pointer * by which to return the favorite model. * * @retval kStatus_Success If successful. * @retval -ERANGE If the favorite identifier is smaller * or larger than supported. * */ Status FavoritesController :: GetFavorite(const IdentifierType &aIdentifier, const FavoriteModel *&aModel) const { Status lRetval = kStatus_Success; lRetval = ValidateIdentifier(aIdentifier); nlREQUIRE_SUCCESS(lRetval, done); lRetval = mFavorites.GetFavorite(aIdentifier, aModel); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } /** * @brief * Get the favorite identifier with the specified name. * * This attempts to lookup the favorite identifier for the favorite * with the specified name. * * @param[in] aName A pointer to a null-terminated * C string of the name of the * favorite to find an identifier * for. * @param[out] aFavoriteIdentifier A reference to storage by which * to return the identifier if * successful. * * @retval kStatus_Success If successful. * @retval -EINVAL If @a aName was null. * @retval -ENOENT No favorite could be found with the * specified name. * * @ingroup name * */ Status FavoritesController :: LookupIdentifier(const char *aName, IdentifierType &aFavoriteIdentifier) const { const FavoriteModel * lFavoriteModel; Status lRetval; lRetval = mFavorites.GetFavorite(aName, lFavoriteModel); nlEXPECT_SUCCESS(lRetval, done); lRetval = lFavoriteModel->GetIdentifier(aFavoriteIdentifier); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } // MARK: Mutator Methods // MARK: Name Mutator Commands /** * @brief * Set the favorite to the specified name. * * This attempts to set the favorite with the provided identifier to the * specified name on the peer HLX server controller. * * @param[in] aFavoriteIdentifier An immutable reference for the * favorite for which to set the * name. * @param[in] aName A pointer to the null-terminated * C string to set the favorite name * to. * * @retval kStatus_Success If successful. * @retval -EINVAL If @a aName was null. * @retval -ERANGE If the favorite identifier is * smaller or larger than supported. * @retval -ENOMEM If memory could not be allocated * for the command exchange or * exchange state. * * @ingroup name * */ Status FavoritesController :: SetName(const IdentifierType &aFavoriteIdentifier, const char *aName) { Command::ExchangeBasis::MutableCountedPointer lCommand; Status lRetval = kStatus_Success; nlREQUIRE_ACTION(aName != nullptr, done, lRetval = -EINVAL); lRetval = ValidateIdentifier(aFavoriteIdentifier); nlREQUIRE_SUCCESS(lRetval, done); lCommand.reset(new Command::Favorites::SetName()); nlREQUIRE_ACTION(lCommand, done, lRetval = -ENOMEM); lRetval = std::static_pointer_cast<Command::Favorites::SetName>(lCommand)->Init(aFavoriteIdentifier, aName); nlREQUIRE_SUCCESS(lRetval, done); lRetval = SendCommand(lCommand, Client::FavoritesControllerBasis::SetNameCompleteHandler, Client::FavoritesControllerBasis::CommandErrorHandler, static_cast<Client::FavoritesControllerBasis *>(this)); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } }; // namespace Client }; // namespace HLX
30.152091
112
0.626986
[ "object", "model" ]
7ed43b90744c1d0bb9e21748423113a2ff1e2e6e
2,705
cpp
C++
examples/OpenCV/main.cpp
guqiqi/EmbeddedSystem
5940b0303e08e1dd891fa61c3599f8437d227520
[ "MIT" ]
null
null
null
examples/OpenCV/main.cpp
guqiqi/EmbeddedSystem
5940b0303e08e1dd891fa61c3599f8437d227520
[ "MIT" ]
null
null
null
examples/OpenCV/main.cpp
guqiqi/EmbeddedSystem
5940b0303e08e1dd891fa61c3599f8437d227520
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #define PI 3.1415926 //Uncomment this line at run-time to skip GUI rendering #define _DEBUG using namespace cv; using namespace std; const string CAM_PATH="/dev/video0"; const string MAIN_WINDOW_NAME="Processed Image"; const string CANNY_WINDOW_NAME="Canny"; const int CANNY_LOWER_BOUND=50; const int CANNY_UPPER_BOUND=250; const int HOUGH_THRESHOLD=150; int main() { // VideoCapture capture(CAM_PATH); VideoCapture capture(0); //If this fails, try to open as a video camera, through the use of an integer param if (!capture.isOpened()) { cout << "-1"; capture.open(atoi(CAM_PATH.c_str())); } double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH); //the width of frames of the video double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT); //the height of frames of the video clog<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl; Mat image; while(true) { capture>>image; if(image.empty()) break; //Set the ROI for the image Rect roi(0,image.rows/3,image.cols,image.rows/3); Mat imgROI=image(roi); //Canny algorithm Mat contours; Canny(imgROI,contours,CANNY_LOWER_BOUND,CANNY_UPPER_BOUND); #ifdef _DEBUG imshow(CANNY_WINDOW_NAME,contours); #endif vector<Vec2f> lines; HoughLines(contours,lines,1,PI/180,HOUGH_THRESHOLD); Mat result(imgROI.size(),CV_8U,Scalar(255)); imgROI.copyTo(result); clog<<lines.size()<<endl; float maxRad=-2*PI; float minRad=2*PI; //Draw the lines and judge the slope for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it) { float rho=(*it)[0]; //First element is distance rho float theta=(*it)[1]; //Second element is angle theta //Filter to remove vertical and horizontal lines, //and atan(0.09) equals about 5 degrees. if((theta>0.09&&theta<1.48)||(theta>1.62&&theta<3.05)) { if(theta>maxRad) maxRad=theta; if(theta<minRad) minRad=theta; #ifdef _DEBUG //point of intersection of the line with first row Point pt1(rho/cos(theta),0); //point of intersection of the line with last row Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows); //Draw a line line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA); #endif } #ifdef _DEBUG clog<<"Line: ("<<rho<<","<<theta<<")\n"; #endif } #ifdef _DEBUG stringstream overlayedText; overlayedText<<"Lines: "<<lines.size(); putText(result,overlayedText.str(),Point(10,result.rows-10),2,0.8,Scalar(0,0,255),0); imshow(MAIN_WINDOW_NAME,result); #endif lines.clear(); waitKey(1); } return 0; }
25.046296
91
0.692421
[ "vector" ]
7ee9f5f8bfbdc1540b3e8667c3e7236ed70e6633
491
hpp
C++
include/translate.hpp
Chrisstewy111/fungameforios
8a4fd280e953b9aebfc0d8384d342e4e16e7bbb7
[ "Zlib" ]
null
null
null
include/translate.hpp
Chrisstewy111/fungameforios
8a4fd280e953b9aebfc0d8384d342e4e16e7bbb7
[ "Zlib" ]
null
null
null
include/translate.hpp
Chrisstewy111/fungameforios
8a4fd280e953b9aebfc0d8384d342e4e16e7bbb7
[ "Zlib" ]
null
null
null
#ifndef TRANS_HPP #define TRANS_HPP #include <allegro5/allegro.h> #include <vector> extern std::vector<std::string> pre_translated_strings; extern std::vector<ALLEGRO_USTR *> post_translated_strings; std::string get_language_name(int index); std::string get_language_friendly_name(int index); std::string get_all_glyphs(); void load_translation(const char *filename); void load_translation_tags(void); const char *_t(const char *tag); void destroy_translation(void); #endif // TRANS_HPP
25.842105
59
0.798371
[ "vector" ]
7efe1dc5c90dd250abce90c3525fa2196571a918
8,460
cpp
C++
src/dropdown.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
94
2021-04-23T03:31:15.000Z
2022-03-29T08:20:26.000Z
src/dropdown.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
64
2021-05-05T21:51:15.000Z
2022-02-08T17:06:52.000Z
src/dropdown.cpp
GhostatSpirit/hdrview
61596f8ba45554db23ae1b214354ab40da065638
[ "MIT" ]
3
2021-07-06T04:58:27.000Z
2022-02-08T16:53:48.000Z
// // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #include "dropdown.h" #include <cassert> #include <nanogui/icons.h> #include <nanogui/layout.h> #include <nanogui/opengl.h> #include <nanogui/popup.h> #include <nanogui/screen.h> #include <spdlog/spdlog.h> #include <spdlog/fmt/ostr.h> using std::string; using std::vector; NAMESPACE_BEGIN(nanogui) Dropdown::Dropdown(Widget *parent) : Button(parent), m_selected_index(0), m_selected_index_f(0.f) { set_flags(Flags::ToggleButton); m_popup = new PopupMenu(screen(), window()); m_popup->set_size(Vector2i(320, 250)); m_popup->set_visible(false); } Dropdown::Dropdown(Widget *parent, const vector<string> &items) : Dropdown(parent) { set_items(items); } Dropdown::Dropdown(Widget *parent, const vector<string> &items, const vector<string> &items_short) : Dropdown(parent) { set_items(items, items_short); } Vector2i Dropdown::preferred_size(NVGcontext *ctx) const { int font_size = m_font_size == -1 ? m_theme->m_button_font_size : m_font_size; // first turn off the checkmark to get consistent widths regardless of which item is selected // for (auto it : m_popup->children()) // if (auto i = dynamic_cast<PopupMenu::Item *>(it)) // i->set_checked(false); auto result = Vector2i(m_popup->preferred_size(ctx).x(), font_size + 5); // re-enabled checkmark // dynamic_cast<PopupMenu::Item *>(m_popup->child_at(m_selected_index))->set_checked(true); return result; } void Dropdown::set_selected_index(int idx) { if (m_items_short.empty()) return; m_selected_index = idx; m_selected_index_f = (float)m_selected_index; set_caption(m_items_short[idx]); for (auto it : m_popup->children()) if (auto i = dynamic_cast<PopupMenu::Item *>(it)) i->set_checked(false); dynamic_cast<PopupMenu::Item *>(m_popup->child_at(m_selected_index))->set_checked(true); } void Dropdown::set_items(const vector<string> &items, const vector<string> &items_short) { assert(items.size() == items_short.size()); m_items = items; m_items_short = items_short; if (m_selected_index < 0 || m_selected_index >= (int)items.size()) { m_selected_index = 0; m_selected_index_f = (float)m_selected_index; } while (m_popup->child_count() != 0) m_popup->remove_child_at(m_popup->child_count() - 1); int index = 0; for (const auto &str : items) { auto button = m_popup->add_item(str); // button->set_flags(Button::RadioButton); button->set_callback( [&, index, this] { set_selected_index(index); m_popup->set_visible(false); if (m_callback) m_callback(index); }); index++; } set_selected_index(m_selected_index); } bool Dropdown::scroll_event(const Vector2i &p, const Vector2f &rel) { if (!enabled()) return false; float speed = 0.1f; set_pushed(false); m_popup->set_visible(false); m_selected_index_f = std::clamp(m_selected_index_f + rel.y() * speed, 0.0f, items().size() - 1.f); m_selected_index = std::clamp((int)round(m_selected_index_f), 0, (int)(items().size() - 1)); set_caption(m_items_short[m_selected_index]); if (m_callback) m_callback(m_selected_index); return true; } bool Dropdown::mouse_button_event(const Vector2i &p, int button, bool down, int modifiers) { if (m_enabled) { if (button == GLFW_MOUSE_BUTTON_1 && down && !m_focused) request_focus(); Vector2i offset(-3, -m_selected_index * PopupMenu::menu_item_height - 4); Vector2i abs_pos = absolute_position() + offset; // prevent bottom of menu from getting clipped off screen if (abs_pos.y() + m_popup->size().y() >= screen()->height()) abs_pos.y() = absolute_position().y() - m_popup->size().y() + 2; // prevent top of menu from getting clipped off screen if (abs_pos.y() <= 1) abs_pos.y() = absolute_position().y() + size().y() - 2; m_popup->set_position(abs_pos); if (down) { if (m_popup->visible()) { m_popup->set_visible(false); return true; } else { m_popup->set_visible(true); // first turn focus off on all menu buttons for (auto it : m_popup->children()) it->mouse_enter_event(p - m_pos, false); // now turn focus on to just the button under the cursor if (auto w = m_popup->find_widget(screen()->mouse_pos() - m_popup->parent()->absolute_position())) w->mouse_enter_event(p + absolute_position() - w->absolute_position(), true); } } return true; } return Widget::mouse_button_event(p, button, down, modifiers); } void Dropdown::draw(NVGcontext *ctx) { set_pushed(m_popup->visible()); if (!m_enabled && m_pushed) m_pushed = false; Widget::draw(ctx); NVGcolor grad_top = m_theme->m_button_gradient_top_unfocused; NVGcolor grad_bot = m_theme->m_button_gradient_bot_unfocused; if (m_pushed || (m_mouse_focus && (m_flags & MenuButton))) { grad_top = m_theme->m_button_gradient_top_pushed; grad_bot = m_theme->m_button_gradient_bot_pushed; } else if (m_mouse_focus && m_enabled) { grad_top = m_theme->m_button_gradient_top_focused; grad_bot = m_theme->m_button_gradient_bot_focused; } nvgBeginPath(ctx); nvgRoundedRect(ctx, m_pos.x() + 1, m_pos.y() + 1.0f, m_size.x() - 2, m_size.y() - 2, m_theme->m_button_corner_radius - 1); if (m_background_color.w() != 0) { nvgFillColor(ctx, Color(m_background_color[0], m_background_color[1], m_background_color[2], 1.f)); nvgFill(ctx); if (m_pushed) { grad_top.a = grad_bot.a = 0.8f; } else { double v = 1 - m_background_color.w(); grad_top.a = grad_bot.a = m_enabled ? v : v * .5f + .5f; } } NVGpaint bg = nvgLinearGradient(ctx, m_pos.x(), m_pos.y(), m_pos.x(), m_pos.y() + m_size.y(), grad_top, grad_bot); nvgFillPaint(ctx, bg); nvgFill(ctx); nvgBeginPath(ctx); nvgStrokeWidth(ctx, 1.0f); nvgRoundedRect(ctx, m_pos.x() + 0.5f, m_pos.y() + (m_pushed ? 0.5f : 1.5f), m_size.x() - 1, m_size.y() - 1 - (m_pushed ? 0.0f : 1.0f), m_theme->m_button_corner_radius); nvgStrokeColor(ctx, m_theme->m_border_light); nvgStroke(ctx); nvgBeginPath(ctx); nvgRoundedRect(ctx, m_pos.x() + 0.5f, m_pos.y() + 0.5f, m_size.x() - 1, m_size.y() - 2, m_theme->m_button_corner_radius); nvgStrokeColor(ctx, m_theme->m_border_dark); nvgStroke(ctx); int font_size = m_font_size == -1 ? m_theme->m_button_font_size : m_font_size; nvgFontSize(ctx, font_size); nvgFontFace(ctx, "sans-bold"); Vector2f center = Vector2f(m_pos) + Vector2f(m_size) * 0.5f; Vector2f text_pos(m_pos.x() + 10, center.y() - 1); NVGcolor text_color = m_text_color.w() == 0 ? m_theme->m_text_color : m_text_color; if (!m_enabled) text_color = m_theme->m_disabled_text_color; nvgFontSize(ctx, font_size); nvgFontFace(ctx, "sans-bold"); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); nvgFillColor(ctx, m_theme->m_text_color_shadow); nvgText(ctx, text_pos.x(), text_pos.y(), m_caption.c_str(), nullptr); nvgFillColor(ctx, text_color); nvgText(ctx, text_pos.x(), text_pos.y() + 1, m_caption.c_str(), nullptr); auto icon = utf8(FA_SORT); nvgFontSize(ctx, (m_font_size < 0 ? m_theme->m_button_font_size : m_font_size) * icon_scale()); nvgFontFace(ctx, "icons"); nvgFillColor(ctx, m_enabled ? text_color : NVGcolor(m_theme->m_disabled_text_color)); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); float iw = nvgTextBounds(ctx, 0, 0, icon.data(), nullptr, nullptr); Vector2f icon_pos(0, m_pos.y() + m_size.y() * 0.5f); icon_pos[0] = m_pos.x() + m_size.x() - iw - 8; nvgText(ctx, icon_pos.x(), icon_pos.y(), icon.data(), nullptr); } NAMESPACE_END(nanogui)
33.046875
118
0.628014
[ "vector" ]
7d024a7407196f775035432518f0fdb40bdf6cf3
3,324
cpp
C++
2. Рекуррентные соотношения/34. Доминошки #828/[OK]210479.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
2. Рекуррентные соотношения/34. Доминошки #828/[OK]210479.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
2. Рекуррентные соотношения/34. Доминошки #828/[OK]210479.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> #include <vector> #include <unordered_map> #include <algorithm> struct SumInfo{ std::vector<int> count; bool canSum; SumInfo(): count(13, 0), canSum(false) {} }; int main() { std::ifstream in("in.txt"); std::size_t size; in >> size; std::unordered_map<int, std::size_t> count; std::vector<int> numbers{1, 2, 3, 4, 5, 6, -6, -5, -4, -3, -2, -1}; int sum = 0; int posCount = 0; int negCount = 0; for (std::size_t i = 0; i < size; ++i) { int up, down; in >> up >> down; int difference = up - down; if (difference < 0) { ++negCount; } else if (difference > 0) { ++posCount; } int absoluteDifference = std::abs(difference); ++count[difference]; sum += absoluteDifference; } int median = sum / 2; std::vector<SumInfo> subsetWithSum(median + 1); subsetWithSum[0].canSum = true; for (int j = 0; j < 12; ++j) { int value = numbers[j]; int sumand = std::abs(value); for (int i = 0; i < (int)subsetWithSum.size()-sumand; ++i) { if (subsetWithSum[i].canSum && !subsetWithSum[i+sumand].canSum) { if (subsetWithSum[i].count[value+6] < count[value]) { subsetWithSum[i+sumand] = subsetWithSum[i]; ++subsetWithSum[i+sumand].count[value+6]; } } } } int smallestReverses = 0; for (int i = median; i > 0; --i) { if (subsetWithSum[i].canSum) { int negatives = 0; for (int j = 0; j < 6; ++j) { negatives += subsetWithSum[i].count[j]; } int positives = 0; for (int j = 7; j < 13; ++j) { positives += subsetWithSum[i].count[j]; } smallestReverses = std::min(negCount-negatives+positives, posCount-positives+negatives); break; } } std::reverse(numbers.begin(), numbers.end()); subsetWithSum = std::vector<SumInfo>(median + 1); subsetWithSum[0].canSum = true; for (int j = 0; j < 12; ++j) { int value = numbers[j]; int sumand = std::abs(value); for (int i = 0; i < (int)subsetWithSum.size()-sumand; ++i) { if (subsetWithSum[i].canSum && !subsetWithSum[i+sumand].canSum) { if (subsetWithSum[i].count[value+6] < count[value]) { subsetWithSum[i+sumand] = subsetWithSum[i]; ++subsetWithSum[i+sumand].count[value+6]; } } } } int newSmallestReverses = 0; for (int i = median; i > 0; --i) { if (subsetWithSum[i].canSum) { int negatives = 0; for (int j = 0; j < 6; ++j) { negatives += subsetWithSum[i].count[j]; } int positives = 0; for (int j = 7; j < 13; ++j) { positives += subsetWithSum[i].count[j]; } newSmallestReverses = std::min(negCount-negatives+positives, posCount-positives+negatives); break; } } std::ofstream out("out.txt"); out << std::min(smallestReverses, newSmallestReverses); return 0; }
33.575758
100
0.498195
[ "vector" ]
7d16478d36bc10992fc6349746d7c2da3ebdb460
24,468
cxx
C++
main/tools/source/generic/b3dtrans.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/tools/source/generic/b3dtrans.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/tools/source/generic/b3dtrans.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include <tools/b3dtrans.hxx> #include <tools/debug.hxx> /************************************************************************* |* |* Transformationen fuer alle 3D Ausgaben |* \************************************************************************/ B3dTransformationSet::B3dTransformationSet() { Reset(); } B3dTransformationSet::~B3dTransformationSet() { } void B3dTransformationSet::Orientation(basegfx::B3DHomMatrix& rTarget, basegfx::B3DPoint aVRP, basegfx::B3DVector aVPN, basegfx::B3DVector aVUP) { rTarget.translate( -aVRP.getX(), -aVRP.getY(), -aVRP.getZ()); aVUP.normalize(); aVPN.normalize(); basegfx::B3DVector aRx(aVUP); basegfx::B3DVector aRy(aVPN); aRx = aRx.getPerpendicular(aRy); aRx.normalize(); aRy = aRy.getPerpendicular(aRx); aRy.normalize(); basegfx::B3DHomMatrix aTemp; aTemp.set(0, 0, aRx.getX()); aTemp.set(0, 1, aRx.getY()); aTemp.set(0, 2, aRx.getZ()); aTemp.set(1, 0, aRy.getX()); aTemp.set(1, 1, aRy.getY()); aTemp.set(1, 2, aRy.getZ()); aTemp.set(2, 0, aVPN.getX()); aTemp.set(2, 1, aVPN.getY()); aTemp.set(2, 2, aVPN.getZ()); rTarget *= aTemp; } void B3dTransformationSet::Frustum(basegfx::B3DHomMatrix& rTarget, double fLeft, double fRight, double fBottom, double fTop, double fNear, double fFar) { if(!(fNear > 0.0)) { fNear = 0.001; } if(!(fFar > 0.0)) { fFar = 1.0; } if(fNear == fFar) { fFar = fNear + 1.0; } if(fLeft == fRight) { fLeft -= 1.0; fRight += 1.0; } if(fTop == fBottom) { fBottom -= 1.0; fTop += 1.0; } basegfx::B3DHomMatrix aTemp; aTemp.set(0, 0, 2.0 * fNear / (fRight - fLeft)); aTemp.set(1, 1, 2.0 * fNear / (fTop - fBottom)); aTemp.set(0, 2, (fRight + fLeft) / (fRight - fLeft)); aTemp.set(1, 2, (fTop + fBottom) / (fTop - fBottom)); aTemp.set(2, 2, -1.0 * ((fFar + fNear) / (fFar - fNear))); aTemp.set(3, 2, -1.0); aTemp.set(2, 3, -1.0 * ((2.0 * fFar * fNear) / (fFar - fNear))); aTemp.set(3, 3, 0.0); rTarget *= aTemp; } void B3dTransformationSet::Ortho(basegfx::B3DHomMatrix& rTarget, double fLeft, double fRight, double fBottom, double fTop, double fNear, double fFar) { if(fNear == fFar) { DBG_ERROR("Near and far clipping plane in Ortho definition are identical"); fFar = fNear + 1.0; } if(fLeft == fRight) { DBG_ERROR("Left and right in Ortho definition are identical"); fLeft -= 1.0; fRight += 1.0; } if(fTop == fBottom) { DBG_ERROR("Top and bottom in Ortho definition are identical"); fBottom -= 1.0; fTop += 1.0; } basegfx::B3DHomMatrix aTemp; aTemp.set(0, 0, 2.0 / (fRight - fLeft)); aTemp.set(1, 1, 2.0 / (fTop - fBottom)); aTemp.set(2, 2, -1.0 * (2.0 / (fFar - fNear))); aTemp.set(0, 3, -1.0 * ((fRight + fLeft) / (fRight - fLeft))); aTemp.set(1, 3, -1.0 * ((fTop + fBottom) / (fTop - fBottom))); aTemp.set(2, 3, -1.0 * ((fFar + fNear) / (fFar - fNear))); rTarget *= aTemp; } /************************************************************************* |* |* Reset der Werte |* \************************************************************************/ void B3dTransformationSet::Reset() { // Matritzen auf Einheitsmatritzen maObjectTrans.identity(); PostSetObjectTrans(); Orientation(maOrientation); PostSetOrientation(); maTexture.identity(); mfLeftBound = mfBottomBound = -1.0; mfRightBound = mfTopBound = 1.0; mfNearBound = 0.001; mfFarBound = 1.001; meRatio = Base3DRatioGrow; mfRatio = 0.0; maViewportRectangle = Rectangle(-1, -1, 2, 2); maVisibleRectangle = maViewportRectangle; mbPerspective = sal_True; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; CalcViewport(); } /************************************************************************* |* |* Objekttransformation |* \************************************************************************/ void B3dTransformationSet::SetObjectTrans(const basegfx::B3DHomMatrix& rObj) { maObjectTrans = rObj; mbObjectToDeviceValid = sal_False; mbInvTransObjectToEyeValid = sal_False; PostSetObjectTrans(); } void B3dTransformationSet::PostSetObjectTrans() { // Zuweisen und Inverse bestimmen maInvObjectTrans = maObjectTrans; maInvObjectTrans.invert(); } /************************************************************************* |* |* Orientierungstransformation |* \************************************************************************/ void B3dTransformationSet::SetOrientation( basegfx::B3DPoint aVRP, basegfx::B3DVector aVPN, basegfx::B3DVector aVUP) { maOrientation.identity(); Orientation(maOrientation, aVRP, aVPN, aVUP); mbInvTransObjectToEyeValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; PostSetOrientation(); } void B3dTransformationSet::SetOrientation(basegfx::B3DHomMatrix& mOrient) { maOrientation = mOrient; mbInvTransObjectToEyeValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; PostSetOrientation(); } void B3dTransformationSet::PostSetOrientation() { // Zuweisen und Inverse bestimmen maInvOrientation = maOrientation; maInvOrientation.invert(); } /************************************************************************* |* |* Projektionstransformation |* \************************************************************************/ void B3dTransformationSet::SetProjection(const basegfx::B3DHomMatrix& mProject) { maProjection = mProject; PostSetProjection(); } const basegfx::B3DHomMatrix& B3dTransformationSet::GetProjection() { if(!mbProjectionValid) CalcViewport(); return maProjection; } const basegfx::B3DHomMatrix& B3dTransformationSet::GetInvProjection() { if(!mbProjectionValid) CalcViewport(); return maInvProjection; } void B3dTransformationSet::PostSetProjection() { // Zuweisen und Inverse bestimmen maInvProjection = GetProjection(); maInvProjection.invert(); // Abhaengige Matritzen invalidieren mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } /************************************************************************* |* |* Texturtransformation |* \************************************************************************/ void B3dTransformationSet::SetTexture(const basegfx::B2DHomMatrix& rTxt) { maTexture = rTxt; PostSetTexture(); } void B3dTransformationSet::PostSetTexture() { } /************************************************************************* |* |* Viewport-Transformation |* \************************************************************************/ void B3dTransformationSet::CalcViewport() { // Faktoren fuer die Projektion double fLeft(mfLeftBound); double fRight(mfRightBound); double fBottom(mfBottomBound); double fTop(mfTopBound); // Soll das Seitenverhaeltnis Beachtung finden? // Falls ja, Bereich der Projektion an Seitenverhaeltnis anpassen if(GetRatio() != 0.0) { // Berechne aktuelles Seitenverhaeltnis der Bounds double fBoundWidth = (double)(maViewportRectangle.GetWidth() + 1); double fBoundHeight = (double)(maViewportRectangle.GetHeight() + 1); double fActRatio = 1; double fFactor; if(fBoundWidth != 0.0) fActRatio = fBoundHeight / fBoundWidth; // FIXME else in this case has a lot of problems, should this return. switch(meRatio) { case Base3DRatioShrink : { // Kleineren Teil vergroessern if(fActRatio > mfRatio) { // X vergroessern fFactor = 1.0 / fActRatio; fRight *= fFactor; fLeft *= fFactor; } else { // Y vergroessern fFactor = fActRatio; fTop *= fFactor; fBottom *= fFactor; } break; } case Base3DRatioGrow : { // GroesserenTeil verkleinern if(fActRatio > mfRatio) { // Y verkleinern fFactor = fActRatio; fTop *= fFactor; fBottom *= fFactor; } else { // X verkleinern fFactor = 1.0 / fActRatio; fRight *= fFactor; fLeft *= fFactor; } break; } case Base3DRatioMiddle : { // Mitteln fFactor = ((1.0 / fActRatio) + 1.0) / 2.0; fRight *= fFactor; fLeft *= fFactor; fFactor = (fActRatio + 1.0) / 2.0; fTop *= fFactor; fBottom *= fFactor; break; } } } // Ueberschneiden sich Darstellungsflaeche und Objektflaeche? maSetBound = maViewportRectangle; // Mit den neuen Werten Projektion und ViewPort setzen basegfx::B3DHomMatrix aNewProjection; // #i36281# // OpenGL needs a little more rough additional size to not let // the front face vanish. Changed from SMALL_DVALUE to 0.000001, // which is 1/10000th, comared with 1/tenth of a million from SMALL_DVALUE. const double fDistPart((mfFarBound - mfNearBound) * 0.0001); // Near, Far etwas grosszuegiger setzen, um falsches, // zu kritisches clippen zu verhindern if(mbPerspective) { Frustum(aNewProjection, fLeft, fRight, fBottom, fTop, mfNearBound - fDistPart, mfFarBound + fDistPart); } else { Ortho(aNewProjection, fLeft, fRight, fBottom, fTop, mfNearBound - fDistPart, mfFarBound + fDistPart); } // jetzt schon auf gueltig setzen um Endlosschleife zu vermeiden mbProjectionValid = sal_True; // Neue Projektion setzen SetProjection(aNewProjection); // fill parameters for ViewportTransformation // Translation maTranslate.setX((double)maSetBound.Left() + ((maSetBound.GetWidth() - 1L) / 2.0)); maTranslate.setY((double)maSetBound.Top() + ((maSetBound.GetHeight() - 1L) / 2.0)); maTranslate.setZ(ZBUFFER_DEPTH_RANGE / 2.0); // Skalierung maScale.setX((maSetBound.GetWidth() - 1L) / 2.0); maScale.setY((maSetBound.GetHeight() - 1L) / -2.0); maScale.setZ(ZBUFFER_DEPTH_RANGE / 2.0); // Auf Veraenderung des ViewPorts reagieren PostSetViewport(); } void B3dTransformationSet::SetRatio(double fNew) { if(mfRatio != fNew) { mfRatio = fNew; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::SetRatioMode(Base3DRatio eNew) { if(meRatio != eNew) { meRatio = eNew; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::SetDeviceRectangle(double fL, double fR, double fB, double fT, sal_Bool bBroadCastChange) { if(fL != mfLeftBound || fR != mfRightBound || fB != mfBottomBound || fT != mfTopBound) { mfLeftBound = fL; mfRightBound = fR; mfBottomBound = fB; mfTopBound = fT; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; // Aenderung bekanntmachen if(bBroadCastChange) DeviceRectangleChange(); } } void B3dTransformationSet::SetDeviceVolume(const basegfx::B3DRange& rVol, sal_Bool bBroadCastChange) { SetDeviceRectangle(rVol.getMinX(), rVol.getMaxX(), rVol.getMinY(), rVol.getMaxY(), bBroadCastChange); SetFrontClippingPlane(rVol.getMinZ()); SetBackClippingPlane(rVol.getMaxZ()); } void B3dTransformationSet::DeviceRectangleChange() { } void B3dTransformationSet::GetDeviceRectangle(double &fL, double &fR, double& fB, double& fT) { fL = mfLeftBound; fR = mfRightBound; fB = mfBottomBound; fT = mfTopBound; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } basegfx::B3DRange B3dTransformationSet::GetDeviceVolume() { basegfx::B3DRange aRet; aRet.expand(basegfx::B3DTuple(mfLeftBound, mfBottomBound, mfNearBound)); aRet.expand(basegfx::B3DTuple(mfRightBound, mfTopBound, mfFarBound)); return aRet; } void B3dTransformationSet::SetFrontClippingPlane(double fF) { if(mfNearBound != fF) { mfNearBound = fF; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::SetBackClippingPlane(double fB) { if(mfFarBound != fB) { mfFarBound = fB; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::SetPerspective(sal_Bool bNew) { if(mbPerspective != bNew) { mbPerspective = bNew; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::SetViewportRectangle(Rectangle& rRect, Rectangle& rVisible) { if(rRect != maViewportRectangle || rVisible != maVisibleRectangle) { maViewportRectangle = rRect; maVisibleRectangle = rVisible; mbProjectionValid = sal_False; mbObjectToDeviceValid = sal_False; mbWorldToViewValid = sal_False; } } void B3dTransformationSet::PostSetViewport() { } const Rectangle& B3dTransformationSet::GetLogicalViewportBounds() { if(!mbProjectionValid) CalcViewport(); return maSetBound; } const basegfx::B3DVector& B3dTransformationSet::GetScale() { if(!mbProjectionValid) CalcViewport(); return maScale; } const basegfx::B3DVector& B3dTransformationSet::GetTranslate() { if(!mbProjectionValid) CalcViewport(); return maTranslate; } /************************************************************************* |* |* Hilfsmatrixberechnungsroutinen |* \************************************************************************/ void B3dTransformationSet::CalcMatObjectToDevice() { // ObjectToDevice berechnen (Orientation * Projection * Object) maObjectToDevice = maObjectTrans; maObjectToDevice *= maOrientation; maObjectToDevice *= GetProjection(); // auf gueltig setzen mbObjectToDeviceValid = sal_True; } const basegfx::B3DHomMatrix& B3dTransformationSet::GetObjectToDevice() { if(!mbObjectToDeviceValid) CalcMatObjectToDevice(); return maObjectToDevice; } void B3dTransformationSet::CalcMatInvTransObjectToEye() { maInvTransObjectToEye = maObjectTrans; maInvTransObjectToEye *= maOrientation; maInvTransObjectToEye.invert(); maInvTransObjectToEye.transpose(); // eventuelle Translationen rausschmeissen, da diese // Matrix nur zur Transformation von Vektoren gedacht ist maInvTransObjectToEye.set(3, 0, 0.0); maInvTransObjectToEye.set(3, 1, 0.0); maInvTransObjectToEye.set(3, 2, 0.0); maInvTransObjectToEye.set(3, 3, 1.0); // auf gueltig setzen mbInvTransObjectToEyeValid = sal_True; } const basegfx::B3DHomMatrix& B3dTransformationSet::GetInvTransObjectToEye() { if(!mbInvTransObjectToEyeValid) CalcMatInvTransObjectToEye(); return maInvTransObjectToEye; } basegfx::B3DHomMatrix B3dTransformationSet::GetMatFromObjectToView() { basegfx::B3DHomMatrix aFromObjectToView = GetObjectToDevice(); const basegfx::B3DVector& rScale(GetScale()); aFromObjectToView.scale(rScale.getX(), rScale.getY(), rScale.getZ()); const basegfx::B3DVector& rTranslate(GetTranslate()); aFromObjectToView.translate(rTranslate.getX(), rTranslate.getY(), rTranslate.getZ()); return aFromObjectToView; } void B3dTransformationSet::CalcMatFromWorldToView() { maMatFromWorldToView = maOrientation; maMatFromWorldToView *= GetProjection(); const basegfx::B3DVector& rScale(GetScale()); maMatFromWorldToView.scale(rScale.getX(), rScale.getY(), rScale.getZ()); const basegfx::B3DVector& rTranslate(GetTranslate()); maMatFromWorldToView.translate(rTranslate.getX(), rTranslate.getY(), rTranslate.getZ()); maInvMatFromWorldToView = maMatFromWorldToView; maInvMatFromWorldToView.invert(); // gueltig setzen mbWorldToViewValid = sal_True; } const basegfx::B3DHomMatrix& B3dTransformationSet::GetMatFromWorldToView() { if(!mbWorldToViewValid) CalcMatFromWorldToView(); return maMatFromWorldToView; } const basegfx::B3DHomMatrix& B3dTransformationSet::GetInvMatFromWorldToView() { if(!mbWorldToViewValid) CalcMatFromWorldToView(); return maInvMatFromWorldToView; } /************************************************************************* |* |* Direkter Zugriff auf verschiedene Transformationen |* \************************************************************************/ const basegfx::B3DPoint B3dTransformationSet::WorldToEyeCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetOrientation(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::EyeToWorldCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvOrientation(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::EyeToViewCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetProjection(); aVec *= GetScale(); aVec += GetTranslate(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ViewToEyeCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec -= GetTranslate(); aVec = aVec / GetScale(); aVec *= GetInvProjection(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::WorldToViewCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetMatFromWorldToView(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ViewToWorldCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvMatFromWorldToView(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::DeviceToViewCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetScale(); aVec += GetTranslate(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ViewToDeviceCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec -= GetTranslate(); aVec = aVec / GetScale(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ObjectToWorldCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetObjectTrans(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::WorldToObjectCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvObjectTrans(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ObjectToViewCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetObjectTrans(); aVec *= GetMatFromWorldToView(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ViewToObjectCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvMatFromWorldToView(); aVec *= GetInvObjectTrans(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::ObjectToEyeCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetObjectTrans(); aVec *= GetOrientation(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::EyeToObjectCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvOrientation(); aVec *= GetInvObjectTrans(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::DeviceToEyeCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvProjection(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::EyeToDeviceCoor(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetProjection(); return aVec; } const basegfx::B3DPoint B3dTransformationSet::InvTransObjectToEye(const basegfx::B3DPoint& rVec) { basegfx::B3DPoint aVec(rVec); aVec *= GetInvTransObjectToEye(); return aVec; } const basegfx::B2DPoint B3dTransformationSet::TransTextureCoor(const basegfx::B2DPoint& rVec) { basegfx::B2DPoint aVec(rVec); aVec *= GetTexture(); return aVec; } /************************************************************************* |* |* Konstruktor B3dViewport |* \************************************************************************/ B3dViewport::B3dViewport() : B3dTransformationSet(), aVRP(0, 0, 0), aVPN(0, 0, 1), aVUV(0, 1, 0) { CalcOrientation(); } B3dViewport::~B3dViewport() { } void B3dViewport::SetVRP(const basegfx::B3DPoint& rNewVRP) { aVRP = rNewVRP; CalcOrientation(); } void B3dViewport::SetVPN(const basegfx::B3DVector& rNewVPN) { aVPN = rNewVPN; CalcOrientation(); } void B3dViewport::SetVUV(const basegfx::B3DVector& rNewVUV) { aVUV = rNewVUV; CalcOrientation(); } void B3dViewport::SetViewportValues( const basegfx::B3DPoint& rNewVRP, const basegfx::B3DVector& rNewVPN, const basegfx::B3DVector& rNewVUV) { aVRP = rNewVRP; aVPN = rNewVPN; aVUV = rNewVUV; CalcOrientation(); } void B3dViewport::CalcOrientation() { SetOrientation(aVRP, aVPN, aVUV); } /************************************************************************* |* |* Konstruktor B3dViewport |* \************************************************************************/ B3dCamera::B3dCamera( const basegfx::B3DPoint& rPos, const basegfx::B3DVector& rLkAt, double fFocLen, double fBnkAng, sal_Bool bUseFocLen) : B3dViewport(), aPosition(rPos), aCorrectedPosition(rPos), aLookAt(rLkAt), fFocalLength(fFocLen), fBankAngle(fBnkAng), bUseFocalLength(bUseFocLen) { CalcNewViewportValues(); } B3dCamera::~B3dCamera() { } void B3dCamera::SetPosition(const basegfx::B3DPoint& rNewPos) { if(rNewPos != aPosition) { // Zuweisen aCorrectedPosition = aPosition = rNewPos; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::SetLookAt(const basegfx::B3DVector& rNewLookAt) { if(rNewLookAt != aLookAt) { // Zuweisen aLookAt = rNewLookAt; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::SetPositionAndLookAt(const basegfx::B3DPoint& rNewPos, const basegfx::B3DVector& rNewLookAt) { if(rNewPos != aPosition || rNewLookAt != aLookAt) { // Zuweisen aPosition = rNewPos; aLookAt = rNewLookAt; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::SetFocalLength(double fLen) { if(fLen != fFocalLength) { // Zuweisen if(fLen < 5.0) fLen = 5.0; fFocalLength = fLen; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::SetBankAngle(double fAngle) { if(fAngle != fBankAngle) { // Zuweisen fBankAngle = fAngle; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::SetUseFocalLength(sal_Bool bNew) { if(bNew != (sal_Bool)bUseFocalLength) { // Zuweisen bUseFocalLength = bNew; // Neuberechnung CalcNewViewportValues(); } } void B3dCamera::DeviceRectangleChange() { // call parent B3dViewport::DeviceRectangleChange(); // Auf Aenderung reagieren CalcNewViewportValues(); } void B3dCamera::CalcNewViewportValues() { basegfx::B3DVector aViewVector(aPosition - aLookAt); basegfx::B3DVector aNewVPN(aViewVector); basegfx::B3DVector aNewVUV(0.0, 1.0, 0.0); if(aNewVPN.getLength() < aNewVPN.getY()) aNewVUV.setX(0.5); aNewVUV.normalize(); aNewVPN.normalize(); basegfx::B3DVector aNewToTheRight = aNewVPN; aNewToTheRight = aNewToTheRight.getPerpendicular(aNewVUV); aNewToTheRight.normalize(); aNewVUV = aNewToTheRight.getPerpendicular(aNewVPN); aNewVUV.normalize(); SetViewportValues(aPosition, aNewVPN, aNewVUV); if(CalcFocalLength()) SetViewportValues(aCorrectedPosition, aNewVPN, aNewVUV); if(fBankAngle != 0.0) { basegfx::B3DHomMatrix aRotMat; aRotMat.rotate(0.0, 0.0, fBankAngle); basegfx::B3DVector aUp(0.0, 1.0, 0.0); aUp *= aRotMat; aUp = EyeToWorldCoor(aUp); aUp.normalize(); SetVUV(aUp); } } sal_Bool B3dCamera::CalcFocalLength() { double fWidth = GetDeviceRectangleWidth(); sal_Bool bRetval = sal_False; if(bUseFocalLength) { // Position aufgrund der FocalLength korrigieren aCorrectedPosition = basegfx::B3DPoint(0.0, 0.0, fFocalLength * fWidth / 35.0); aCorrectedPosition = EyeToWorldCoor(aCorrectedPosition); bRetval = sal_True; } else { // FocalLength anhand der Position anpassen basegfx::B3DPoint aOldPosition; aOldPosition = WorldToEyeCoor(aOldPosition); if(fWidth != 0.0) fFocalLength = aOldPosition.getZ() / fWidth * 35.0; if(fFocalLength < 5.0) fFocalLength = 5.0; } return bRetval; } // eof
24.20178
151
0.677742
[ "object", "3d" ]
7d194a79d2fd4a0593b6d423e1ae24840aeaf080
31,136
cc
C++
boosting/probabilizer.cc
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
1
2018-02-27T08:01:22.000Z
2018-02-27T08:01:22.000Z
boosting/probabilizer.cc
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
null
null
null
boosting/probabilizer.cc
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
null
null
null
/* probabilizer.cc Jeremy Barnes, 13 June 2003 Copyright (c) 2003 Jeremy Barnes. All rights reserved. $Source$ */ #include "probabilizer.h" #include "registry.h" #include "training_data.h" #include "training_index.h" #include "classifier.h" #include "jml/stats/moments.h" #include "jml/stats/distribution_ops.h" #include "jml/stats/distribution_simd.h" #include "jml/math/xdiv.h" #include "registry.h" #include "jml/utils/environment.h" #include "jml/utils/vector_utils.h" #include <cmath> #include <fstream> #include "config_impl.h" #include "jml/utils/exc_assert.h" using namespace std; using namespace ML::DB; using std::sqrt; namespace ML { namespace { Env_Option<bool> debug("DEBUG_PROBABILIZER", false); } /*****************************************************************************/ /* GLZ_PROBABILIZER */ /*****************************************************************************/ GLZ_Probabilizer::GLZ_Probabilizer() : link(LOGIT) { } GLZ_Probabilizer::~GLZ_Probabilizer() { } distribution<float> GLZ_Probabilizer::apply(const distribution<float> & input) const { if (params.size() == 0) throw Exception("applying untrained glz probabilizer"); if (params.size() != input.size()) { cerr << "input = " << input << endl; cerr << "params.size() = " << params.size() << endl; throw Exception("applying glz probabilizer to wrong num classes"); } bool regression = params.size() == 1; distribution<float> input2(input); // add inputs if (!regression) input2.push_back(input.max()); // add max term input2.push_back(1.0); // add bias term if (debug & 2) cerr << "link = " << link << endl; if (debug & 2) cerr << "input2 = " << input2 << endl; distribution<float> result(input.size()); for (unsigned i = 0; i < input.size(); ++i) result[i] = apply_link_inverse((input2 * params[i]).total(), link); if (debug & 2) cerr << "result = " << result << endl; if (result.total() > 0.0 && !regression) result.normalize(); if (debug & 2) cerr << "normalized = " << result << endl; #if 1 bool all_ok = true; for (unsigned i = 0; i < result.size(); ++i) if (!isfinite(result[i])) all_ok = false; if (!all_ok || result.total() == 0.0) { cerr << "applying GLZ_Probabilizer lead to zero results: " << endl; cerr << " input = " << input << endl; cerr << " input2 = " << input2 << endl; cerr << " result = " << result << endl; for (unsigned i = 0; i < params.size(); ++i) cerr << " params[" << i << "] = " << params[i] << endl; for (unsigned i = 0; i < params.size(); ++i) { cerr << " params[" << i << "] * input2 = " << params[i] * input2 << " (total " << (params[i] * input2).total() << ")" << endl; } for (unsigned i = 0; i < input.size(); ++i) result[i] = apply_link_inverse((input2 * params[i]).total(), link); cerr << " result before normalize = " << result << endl; cerr << " total = " << result.total() << endl; } #endif return result; } GLZ_Probabilizer GLZ_Probabilizer:: construct_sparse(const distribution<double> & params, size_t label_count, Link_Function link) { /* If x, y and z are the params, then we create a matrix x 0 0 ... 0 y z 0 x 0 ... 0 y z 0 0 x ... 0 y z : : : : : : 0 0 0 ... x y z */ GLZ_Probabilizer result; result.link = link; result.params.clear(); size_t ol = label_count + 2; // number of columns to create for (unsigned l = 0; l < label_count; ++l) { distribution<float> expanded(ol, 0.0); expanded[l] = params[0]; expanded[ol - 2] = params[1]; expanded[ol - 1] = params[2]; result.params.push_back(expanded); } return result; } void GLZ_Probabilizer:: add_data_sparse(std::vector<distribution<double> > & data, const std::vector<float> & output, int correct_label) { size_t nl = output.size(); if (nl == 0 || correct_label < 0 || correct_label >= nl) throw Exception("GLZ_Probabilizer::add_data_sparse: input invariant"); double max = *std::max_element(output.begin(), output.end()); distribution<double> entry(4); for (unsigned l = 0; l < nl; ++l) { entry[0] = output[l]; entry[1] = max; entry[2] = (l == correct_label); if (l == correct_label) entry[3] = 1.0; else entry[3] = 1.0 / (nl - 1); data.push_back(entry); } } void GLZ_Probabilizer:: add_data_sparse(std::vector<distribution<double> > & data, const Training_Data & training_data, const Classifier_Impl & classifier, const Optimization_Info & opt_info) { size_t nx = training_data.example_count(); const vector<Label> & labels = training_data.index().labels(classifier.predicted()); /* Go through the training examples one by one, and record the outputs. */ for (unsigned x = 0; x < nx; ++x) { distribution<float> output = classifier.predict(training_data[x], opt_info); add_data_sparse(data, output, labels[x]); } } distribution<double> GLZ_Probabilizer:: train_sparse(const std::vector<distribution<double> > & data, Link_Function link, const distribution<double> & weights_) { size_t nd = data.size(); /* Convert to the correct data structures. */ /* If weights passed in were empty, then we use uniform weights. */ distribution<double> weights = weights_; if (weights.empty()) weights.resize(nd, 1.0); boost::multi_array<double, 2> outputs(boost::extents[3][nd]); // value, max, bias distribution<double> correct(nd); for (unsigned d = 0; d < nd; ++d) { outputs[0][d] = data[d][0]; outputs[1][d] = data[d][1]; outputs[2][d] = 1.0; correct[d] = data[d][2]; weights[d] *= data[d][3]; } /* Perform the GLZ. */ distribution<double> param(3, 0.0); Ridge_Regressor regressor; return run_irls(correct, outputs, weights, link, regressor); } void GLZ_Probabilizer:: train_glz_regress(const boost::multi_array<double, 2> & outputs, const distribution<double> & correct, const distribution<float> & weights, bool debug) { distribution<double> w(weights.begin(), weights.end()); /* Perform the GLZ. */ distribution<double> param = run_irls(correct, outputs, w, link); params.clear(); params.push_back(distribution<float>(param.begin(), param.end())); } void GLZ_Probabilizer:: train_identity_regress(const boost::multi_array<double, 2> & outputs, const distribution<double> & correct, const distribution<float> & weights, bool debug) { size_t ol = outputs.shape()[0]; /* Make the parameterization be an identity function. */ params.clear(); distribution<float> p(ol, 0.0); p[0] = 1.0; params.push_back(p); if (debug) cerr << "params for " << 0 << " = " << params[0] << endl; } distribution<float> GLZ_Probabilizer:: train_one_mode0(const boost::multi_array<double, 2> & outputs, const distribution<double> & correct, const distribution<double> & w, const vector<int> & dest) const { size_t ol = dest.size(); distribution<double> param = run_irls(correct, outputs, w, link); /* Expand the learned distribution back into its proper size, putting back the removed columns as zeros. */ distribution<float> output(ol, 0.0); for (unsigned i = 0; i < ol; ++i) output[i] = (dest[i] == -1 ? 0.0 : param[dest[i]]); return output; } void GLZ_Probabilizer:: train_mode0(boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; size_t nx = outputs.shape()[1]; /* Train the mode2 over all of the data. We use these ones for where we don't have enough data or we get a negative value for our output. */ train_mode2(outputs, correct, num_correct, weights, false); /* Remove any linearly dependent rows. */ vector<int> dest = remove_dependent(outputs); /* Learn glz as a whole matrix. Needs lots of data to work well. */ distribution<double> w(weights.begin(), weights.end()); /* Perform a GLZ for each column. TODO: really use the GLZ class. */ for (unsigned l = 0; l < nl; ++l) { if (num_correct[l] > 0 && num_correct[l] <= nx) { distribution<float> trained = train_one_mode0(outputs, correct[l], w, dest); if (trained[l] > 0.0) params[l] = trained; } if (debug) cerr << "params for " << l << " = " << params.at(l) << endl; } } distribution<float> GLZ_Probabilizer:: train_one_mode1(const boost::multi_array<double, 2> & outputs, const distribution<double> & correct, const distribution<double> & w, int l) const { size_t ol = outputs.shape()[0]; size_t nx = outputs.shape()[1]; //cerr << "ol = " << ol << " nx = " << nx << endl; boost::multi_array<double, 2> outputs2(boost::extents[3][nx]); // value, max, bias for (unsigned x = 0; x < nx; ++x) { outputs2[0][x] = outputs[l][x]; outputs2[1][x] = outputs[ol - 2][x]; outputs2[2][x] = outputs[ol - 1][x]; } vector<int> dest = remove_dependent(outputs2); //cerr << "dest = " << dest << endl; distribution<double> param(3, 0.0); param = run_irls(correct, outputs2, w, link); /* Put the 3 columns back into ol columns, so that the output is still compatible. */ distribution<float> param2(ol, 0.0); param2[l] = (dest[0] == -1 ? 0.0 : param[dest[0]]); param2[ol - 2] = (dest[1] == -1 ? 0.0 : param[dest[1]]); param2[ol - 1] = (dest[2] == -1 ? 0.0 : param[dest[2]]); return param2; } void GLZ_Probabilizer:: train_mode1(const boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; /* Train the mode2 over all of the data. We use these ones for where we don't have enough data or we get a negative value for our output. */ train_mode2(outputs, correct, num_correct, weights, false); distribution<double> w(weights.begin(), weights.end()); /* Perform a GLZ for each column. TODO: really use the GLZ class. */ for (unsigned l = 0; l < nl; ++l) { if (num_correct[l] > 0) { distribution<float> trained = train_one_mode1(outputs, correct[l], w, l); if (trained[l] > 0.0) params[l] = trained; } if (debug) cerr << "params for " << l << " = " << params[l] << endl; } } void GLZ_Probabilizer:: train_mode2(const boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; size_t ol = outputs.shape()[0]; size_t nx = outputs.shape()[1]; //debug = true; /* Are there any linearly dependent columns in the outputs? If so, we don't try to include them. */ boost::multi_array<double, 2> independent = outputs; if (debug) { for (unsigned l = 0; l < nl; ++l) for (unsigned x = 0; x < nx; ++x) independent[l][x] = outputs[l][x]; cerr << "training mode 2" << endl; } vector<distribution<double> > reconstruct; vector<int> removed = remove_dependent_impl(independent, reconstruct); if (debug) { for (unsigned x = 0; x < std::min<size_t>(nx, 10); ++x) { for (unsigned l = 0; l < ol; ++l) cerr << format("%10f ", outputs[l][x]); cerr << " : "; for (unsigned l = 0; l < nl; ++l) cerr << format("%3f ", correct[l][x]); cerr << " --> "; for (unsigned l = 0; l < nl; ++l) cerr << format("%10f ", independent[l][x]); cerr << endl; } cerr << "removed = " << removed << endl; for (unsigned i = 0; i < reconstruct.size(); ++i) cerr << "reconstruct[" << i << "] = " << reconstruct[i] << endl; cerr << outputs.shape()[0] << "x" << outputs.shape()[1] << " matrix" << endl; } distribution<bool> skip(removed.size()); int nlu = 0; // nl unskipped for (unsigned l = 0; l < nl; ++l) { skip[l] = removed[l] == -1; if (!skip[l]) ++nlu; } if (debug) { cerr << "skip = " << skip << endl; cerr << "nlu = " << nlu << endl; cerr << "weights.min() = " << weights.min() << " weights.max() = " << weights.max() << " weights.total() = " << weights.total() << endl; cerr << "num_correct = " << num_correct << endl; } // In the case that one output is always less than another, we'll have // a problem with the max column being identical to the higher output. // In this case, we end up trying to skip all of the columns. // // Solutions to this are: // 1. Using ridge regression; // 2. if all labels are skipped, then skip the input instead bool ridge = true; // can't think of where we wouldn't want it... if (nlu == 0) { nlu = nl; for (unsigned i = 0; i < nlu; ++i) skip[i] = false; ridge = true; } // very underparamerized version, to avoid overfitting // We learn a single GLZ, with the data as all of the labels together. // The predictions here get weighted in such a way that the correct // ones are more important than the incorrect ones. distribution<double> w(nx * nlu, 1.0); /* Get the entire enormous data set. */ boost::multi_array<double, 2> outputs2(boost::extents[3][nx * nlu]); // value, max, bias distribution<double> correct2(nx * nlu); for (unsigned x = 0; x < nx; ++x) { int li = 0; for (unsigned l = 0; l < nl; ++l) { if (skip[l]) continue; outputs2[0][x*nlu + li] = outputs[l ][x]; outputs2[1][x*nlu + li] = outputs[ol - 2][x]; outputs2[2][x*nlu + li] = outputs[ol - 1][x]; correct2 [x*nlu + li] = correct[l][x]; w [x*nlu + li] = 1.0; /* Note: this doesn't work when we have a large number of classes. It causes all of the outputs to have a high result, which in turn causes them to all be about 1/nl when normalized. */ //if (correct[l][x] == 1.0) w[x*nl + l] = nl; //else w[x*nl + l] = 1.0; w[x*nlu + li] *= weights[x]; ++li; } } /* Perform the GLZ. */ distribution<double> param; if (ridge) { Ridge_Regressor regressor; param = run_irls(correct2, outputs2, w, link, regressor); } else { param = run_irls(correct2, outputs2, w, link); } if (debug) cerr << "param = " << param << endl; /* Constuct it from the results. */ *this = construct_sparse(param, nl, link); if (debug) for (unsigned l = 0; l < nl; ++l) cerr << "params for " << l << " = " << params[l] << endl; } void GLZ_Probabilizer:: train_mode3(const boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; size_t ol = outputs.shape()[0]; /* Make the parameterization be an identity function. */ params.clear(); distribution<float> p(ol, 0.0); for (unsigned l = 0; l < nl; ++l) { p[l] = 1.0; params.push_back(p); p[l] = 0.0; } if (debug) for (unsigned l = 0; l < nl; ++l) cerr << "params for " << l << " = " << params[l] << endl; } void GLZ_Probabilizer:: train_mode4(const boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; boost::multi_array<double, 2> outputs_nodep = outputs; /* Remove any linearly dependent rows. */ vector<int> dest = remove_dependent(outputs_nodep); /* Get our weights vector ready. */ distribution<double> w(weights.begin(), weights.end()); /* Cutoff points. */ int min_mode0_examples = 50; int min_mode1_examples = 20; /* Train the mode2 over all of the data. We use this as a fallback. */ train_mode2(outputs, correct, num_correct, weights, false); /* Now select between them for each row. */ for (unsigned l = 0; l < nl; ++l) { distribution<float> trained; if (num_correct[l] >= min_mode0_examples) trained = train_one_mode0(outputs_nodep, correct[l], w, dest); else if (num_correct[l] >= min_mode1_examples) trained = train_one_mode1(outputs, correct[l], w, l); if (trained.size() && trained[l] > 0.0) params[l] = trained; if (debug) cerr << "params for " << l << " (" << num_correct[l] << " ex) = " << params[l] << endl; } } void GLZ_Probabilizer:: train_mode5(const boost::multi_array<double, 2> & outputs, const std::vector<distribution<double> > & correct, const distribution<int> & num_correct, const distribution<float> & weights, bool debug) { size_t nl = outputs.shape()[0] - 2; size_t ol = outputs.shape()[0]; size_t nx = outputs.shape()[1]; //cerr << "nl = " << nl << " nx = " << nx << " ol = " << ol << endl; if (nl != 2) throw Exception("GLZ_Probabilizer::train_mode5(): " "not a binary classifer"); /* We learn the zero label only */ distribution<double> w(nx, 1.0); /* Get the entire enormous data set. */ boost::multi_array<double, 2> outputs2(boost::extents[3][nx]); // value, max, bias distribution<double> correct2(nx); for (unsigned x = 0; x < nx; ++x) { outputs2[0][x] = outputs[0][x]; outputs2[1][x] = outputs[2][x]; outputs2[2][x] = outputs[3][x]; correct2 [x] = correct[0][x]; w [x] = weights[x]; } //cerr << "correct2 = " << correct2 << endl; //cerr << "w = " << w << endl; //cerr << "performing GLZ" << endl; /* Perform the GLZ. */ distribution<double> param = run_irls(correct2, outputs2, w, link); /* Construct it from the results. We want the label 1 to be 1 - label 0, so we just learn a single label 0. */ /* If x, y and z are the params, then we create a matrix x 0 y z -x 0 -y 1-z */ //cerr << "param = " << param << endl; params.clear(); distribution<float> expanded(ol, 0.0); expanded[0] = param[0]; expanded[2] = param[1]; expanded[3] = param[2]; params.push_back(expanded); expanded[0] = -param[0]; expanded[2] = -param[1]; expanded[3] = 1.0 - param[2]; // add one to bias so we get 1- params.push_back(expanded); if (debug) for (unsigned l = 0; l < nl; ++l) cerr << "params for " << l << " = " << params[l] << endl; } namespace { /** Small object to record the values of predictions once they're ready */ struct Write_Output { boost::multi_array<double, 2> & outputs; int nl; bool regression_problem; Write_Output(boost::multi_array<double, 2> & outputs, int nl, bool regression_problem) : outputs(outputs), nl(nl), regression_problem(regression_problem) { if (!regression_problem) ExcAssertEqual(nl + 2, outputs.shape()[0]); else ExcAssertEqual(nl, 1); } void operator () (int example, const float * vals) { //cerr << "writing output: example " << example << " vals[0] " // << vals[0] << " nl " << nl << " sz " << outputs.shape()[0] // << "x" << outputs.shape()[1] << endl; ExcAssertLess(example, outputs.shape()[1]); if (!regression_problem) { float max_output = *vals; for (unsigned l = 0; l < nl; ++l) { outputs[l][example] = vals[l]; max_output = std::max(max_output, vals[l]); } outputs[nl][example] = max_output; // maximum output outputs[nl + 1][example] = 1.0; // bias term } else { outputs[0][example] = *vals; outputs[1][example] = 1.0; } } }; } // file scope void GLZ_Probabilizer:: train(const Training_Data & training_data, const Classifier_Impl & classifier, const Optimization_Info & opt_info, const distribution<float> & weights, int mode, const string & link_name) { if (link_name != "") link = parse_link_function(link_name); //cerr << "training in mode " << mode << " link = " << link // << " weights " << weights.size() << endl; const vector<Label> & labels = training_data.index().labels(classifier.predicted()); size_t nl = training_data.label_count(classifier.predicted()); if (classifier.label_count() != nl) throw Exception (format("classifier (%zd) and training data (%zd) have " "different label counts", classifier.label_count(), nl)); size_t nx = training_data.example_count(); if (weights.size() != nx) throw Exception(format("GLZ_Probabilizer::train(): passed %zd examples " "but %zd weights", nx, weights.size())); if (nx == 0 && mode != 3) throw Exception("GLZ_Probabilizer::train(): passed 0 examples"); /* In order to train this, we make a vector of the output of the classifier for each variable. */ bool regression_problem = (nl == 1); size_t ol = regression_problem ? 2 : nl + 2; //bool debug = false; boost::multi_array<double, 2> outputs(boost::extents[ol][nx]); distribution<double> model(nx, 0.0); vector<distribution<double> > correct(nl, model); distribution<int> num_correct(nl); /* Go through the training examples one by one, and record the outputs. */ classifier.predict(training_data, Write_Output(outputs, nl, regression_problem), &opt_info); //for (unsigned i = 0; i < 10; ++i) // cerr << "outputs[" << 0 << "][" << i << "] = " // << outputs[0][i] << endl; for (unsigned x = 0; x < nx; ++x) { if (regression_problem) { correct[0][x] = labels[x].value(); } else { num_correct[labels[x]] += 1; for (unsigned l = 0; l < nl; ++l) { correct[l][x] = (float)(labels[x] == l); } } } //cerr << "num_correct = " << num_correct << endl; //cerr << "num_correct.total() = " << num_correct.total() // << " nx = " << nx << endl; //cerr << "before training: link = " << link << endl; //cerr << "mode = " << mode << endl; //cerr << "nl = " << nl << " regression_problem = " << regression_problem // << endl; if (regression_problem) { switch (mode) { case 0: case 3: train_identity_regress(outputs, correct[0], weights, debug); break; case 1: case 2: train_glz_regress(outputs, correct[0], weights, debug); break; default: throw Exception(format("unknown GLZ probabilizer regression mode %d", mode)); } } else { switch (mode) { case 0: train_mode0(outputs, correct, num_correct, weights, debug); break; case 1: train_mode1(outputs, correct, num_correct, weights, debug); break; case 2: train_mode2(outputs, correct, num_correct, weights, debug); break; case 3: train_mode3(outputs, correct, num_correct, weights, debug); break; case 4: train_mode4(outputs, correct, num_correct, weights, debug); break; case 5: train_mode5(outputs, correct, num_correct, weights, debug); break; default: throw Exception(format("unknown GLZ probabilizer mode %d", mode)); } } //cerr << "trained probabilizer: " << print() << endl; //cerr << "after training: link = " << link << endl; } void GLZ_Probabilizer:: train(const Training_Data & training_data, const Classifier_Impl & classifier, const Optimization_Info & opt_info, int mode, const string & link_name) { distribution<float> weights(training_data.example_count(), 1.0); train(training_data, classifier, opt_info, weights, mode, link_name); } void GLZ_Probabilizer:: init(const Classifier_Impl & classifier, int mode, const std::string & link_name, const std::vector<float> & params) { if (link_name != "") link = parse_link_function(link_name); size_t nl = classifier.label_count(); bool regression_problem = (nl == 1); if (regression_problem) { throw Exception("GLZ_Probabilizer::init(): not impl for regression"); #if 0 switch (mode) { case 0: case 3: train_identity_regress(outputs, correct[0], weights, debug); break; case 1: case 2: train_glz_regress(outputs, correct[0], weights, debug); break; default: throw Exception(format("unknown GLZ probabilizer regression mode %d", mode)); } #endif } else { switch (mode) { case 1: { if (params.size() != 3 * nl) throw Exception("GLZ_Probabilizer::init(): " "mode 1 needs 3 values per label"); this->link = link; this->params.clear(); size_t ol = nl + 2; // number of columns to create for (unsigned l = 0; l < nl; ++l) { distribution<float> expanded(ol, 0.0); expanded[l] = params[0 + l * 3]; expanded[ol - 2] = params[1 + l * 3]; expanded[ol - 1] = params[2 + l * 3]; this->params.push_back(expanded); } break; } case 2: { /* Perform the GLZ. */ if (params.size() != 3) throw Exception("GLZ_Probabilizer::init(): " "mode 2 needs 3 values"); distribution<double> param(params.begin(), params.end()); *this = construct_sparse(param, nl, link); for (unsigned l = 0; l < nl; ++l) cerr << "params for " << l << " = " << params[l] << endl; break; } default: throw Exception(format("GLZ_Probabilizer::init(): " "can't init mode %d", mode)); } } } size_t GLZ_Probabilizer::domain() const { return params.size(); } size_t GLZ_Probabilizer::range() const { if (params.empty()) return 0; else return params[0].size(); } Output_Encoding GLZ_Probabilizer::output_encoding(Output_Encoding) const { return OE_PROB; } bool GLZ_Probabilizer::positive() const { for (unsigned l = 0; l < params.size(); ++l) if (params[l][l] < 0.0) return false; return true; } std::string GLZ_Probabilizer::print() const { string result = "GLZ_Probabilizer { link = " + ML::print(link); for (unsigned i = 0; i < params.size(); ++i) result += format(" params[%d] = ", i) + ostream_format(params[i]); result += " }"; return result; } namespace { static const std::string GLZP_MAGIC="GLZ_PROBABILIZER"; static const compact_size_t GLZP_VERSION = 1; } // file scope void GLZ_Probabilizer::serialize(DB::Store_Writer & store) const { store << GLZP_MAGIC << GLZP_VERSION << link << params; } void GLZ_Probabilizer::reconstitute(DB::Store_Reader & store) { std::string magic; compact_size_t version; store >> magic >> version; if (magic != GLZP_MAGIC) throw Exception("Attempt to reconstitute \"" + magic + "\" with glz probabilizer reconstitutor"); if (version > GLZP_VERSION) throw Exception(format("Attemp to reconstitute glzp version %zd, only " "<= %zd supported", version.size_, GLZP_VERSION.size_)); // link added in version 1 if (version == 0) link = LOGIT; else store >> link; //cerr << "link = " << link << endl; store >> params; } GLZ_Probabilizer::GLZ_Probabilizer(DB::Store_Reader & store) { reconstitute(store); } GLZ_Probabilizer * GLZ_Probabilizer::make_copy() const { return new GLZ_Probabilizer(*this); } DB::Store_Writer & operator << (DB::Store_Writer & store, const GLZ_Probabilizer & prob) { prob.serialize(store); return store; } DB::Store_Reader & operator >> (DB::Store_Reader & store, GLZ_Probabilizer & prob) { prob.reconstitute(store); return store; } /*****************************************************************************/ /* REGISTRATION */ /*****************************************************************************/ namespace { //Register_Factory<Probabilizer, GLZ_Probabilizer> GLZ_REG1("GLZ_PROBABILIZER"); Register_Factory<Decoder_Impl, GLZ_Probabilizer> GLZ_REG2("GLZ_PROBABILIZER"); } // file scope } // namespace ML
31.011952
93
0.541174
[ "object", "shape", "vector", "model" ]
7d29793645c4b9b39a0bd076518607ad68901d65
11,271
cc
C++
src/lm/kaldi-nnlm.cc
boostpapa/kaldi
1727fa234ef505b8550cab991e30c5ee6aaff64d
[ "Apache-2.0" ]
1
2021-04-29T16:09:26.000Z
2021-04-29T16:09:26.000Z
src/lm/kaldi-nnlm.cc
boostpapa/kaldi
1727fa234ef505b8550cab991e30c5ee6aaff64d
[ "Apache-2.0" ]
2
2019-04-09T06:57:51.000Z
2019-04-09T07:12:48.000Z
src/lm/kaldi-nnlm.cc
ishine/kaldi
1845b94477c1ca0066797c320bf4eaf56cbd75cc
[ "Apache-2.0" ]
2
2017-08-20T10:24:05.000Z
2019-02-28T02:48:53.000Z
// lm/kaldi-nnlm.cc // Copyright 2015-2016 Shanghai Jiao Tong University (author: Wei Deng) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <utility> #include "lm/kaldi-nnlm.h" #include "util/stl-utils.h" #include "util/text-utils.h" namespace kaldi { KaldiNNlmWrapper::KaldiNNlmWrapper( const KaldiNNlmWrapperOpts &opts, const std::string &unk_prob_rspecifier, const std::string &word_symbol_table_rxfilename, const std::string &lm_word_symbol_table_rxfilename, const std::string &nnlm_rxfilename) { // class boundary if (opts.class_boundary == "") KALDI_ERR<< "The lm class boundary file '" << opts.class_boundary << "' is empty."; Input in; Vector<BaseFloat> classinfo; in.OpenTextMode(opts.class_boundary); classinfo.Read(in.Stream(), false); in.Close(); class_boundary_.resize(classinfo.Dim()); for (int i = 0; i < classinfo.Dim(); i++) class_boundary_[i] = classinfo(i); // log(zt) class constant if (opts.class_constant == "") KALDI_ERR<< "The lm class boundary file '" << opts.class_boundary << "' is empty."; Vector<BaseFloat> constantinfo; in.OpenTextMode(opts.class_constant); constantinfo.Read(in.Stream(), false); in.Close(); class_constant_.resize(constantinfo.Dim()); for (int i = 0; i < constantinfo.Dim(); i++) class_constant_[i] = constantinfo(i); // map wordid to class word2class_.resize(class_boundary_.back()); int j = 0; for (int i = 0; i < class_boundary_.back(); i++) { if (i>=class_boundary_[j] && i<class_boundary_[j+1]) word2class_[i] = j; else word2class_[i] = ++j; } // load lstm lm nnlm_.Read(nnlm_rxfilename); // get rc information nnlm_.GetHiddenLstmLayerRCInfo(recurrent_dim_, cell_dim_); // split net to lstm hidden part and output part nnlm_.SplitLstmLm(out_linearity_, out_bias_, class_linearity_, class_bias_, class_boundary_.size()-1); // nstream utterance parallelization num_stream_ = opts.num_stream; std::vector<int> new_utt_flags(num_stream_, 0); nnlm_.ResetLstmStreams(new_utt_flags); // init rc context buffer his_recurrent_.resize(recurrent_dim_.size()); for (int i = 0; i < recurrent_dim_.size(); i++) his_recurrent_[i].Resize(num_stream_, recurrent_dim_[i], kUndefined); his_cell_.resize(cell_dim_.size()); for (int i = 0; i < cell_dim_.size(); i++) his_cell_[i].Resize(num_stream_, cell_dim_[i], kUndefined); // Reads symbol table. fst::SymbolTable *word_symbols = NULL; if (!(word_symbols = fst::SymbolTable::ReadText(word_symbol_table_rxfilename))) { KALDI_ERR << "Could not read symbol table from file " << word_symbol_table_rxfilename; } label_to_word_.resize(word_symbols->NumSymbols()); for (int32 i = 0; i < word_symbols->NumSymbols(); i++) { label_to_word_[i] = word_symbols->Find(i); if (label_to_word_[i] == "") { KALDI_ERR << "Could not find word for integer " << i << "in the word " << "symbol table, mismatched symbol table or you have discoutinuous " << "integers in your symbol table?"; } } // Reads lstm lm symbol table. fst::SymbolTable *lm_word_symbols = NULL; if (!(lm_word_symbols = fst::SymbolTable::ReadText(lm_word_symbol_table_rxfilename))) { KALDI_ERR << "Could not read symbol table from file " << lm_word_symbol_table_rxfilename; } for (int i = 0; i < lm_word_symbols->NumSymbols(); i++) word_to_lmwordid_[lm_word_symbols->Find(i)] = i; auto it = word_to_lmwordid_.find(opts.unk_symbol); if (it == word_to_lmwordid_.end()) KALDI_WARN << "Could not find symbol " << opts.unk_symbol << " for out-of-vocabulary " << lm_word_symbol_table_rxfilename; it = word_to_lmwordid_.find(opts.sos_symbol); if (it == word_to_lmwordid_.end()) KALDI_ERR << "Could not find start of sentence symbol " << opts.sos_symbol << " in " << lm_word_symbol_table_rxfilename; sos_ = it->second; it = word_to_lmwordid_.find(opts.eos_symbol); if (it == word_to_lmwordid_.end()) KALDI_ERR << "Could not find end of sentence symbol " << opts.eos_symbol << " in " << lm_word_symbol_table_rxfilename; eos_ = it->second; //map label id to language model word id unk_ = word_to_lmwordid_[opts.unk_symbol]; label_to_lmwordid_.resize(label_to_word_.size()); for (int i = 0; i < label_to_word_.size(); i++) { auto it = word_to_lmwordid_.find(label_to_word_[i]); if (it != word_to_lmwordid_.end()) label_to_lmwordid_[i] = it->second; else label_to_lmwordid_[i] = unk_; } in_words_.Resize(num_stream_, kUndefined); in_words_mat_.Resize(num_stream_, 1, kUndefined); words_.Resize(num_stream_, kUndefined); hidden_out_.Resize(num_stream_, nnlm_.OutputDim(), kUndefined); } void KaldiNNlmWrapper::GetLogProbParallel(const std::vector<int> &curt_words, const std::vector<LstmLmHistroy*> &context_in, std::vector<LstmLmHistroy*> &context_out, std::vector<BaseFloat> &logprob) { // get current words log probility (CPU done) LstmLmHistroy *his; int i, j, wid, cid; logprob.resize(num_stream_); for (i = 0; i < num_stream_; i++) { wid = curt_words[i]; in_words_(i) = wid; cid = word2class_[wid]; his = context_in[i]; SubVector<BaseFloat> linear_vec(out_linearity_.Row(wid)); SubVector<BaseFloat> class_linear_vec(class_linearity_.Row(cid)); Vector<BaseFloat> &hidden_out_vec = his->his_recurrent.back(); BaseFloat prob = VecVec(hidden_out_vec, linear_vec) + out_bias_(wid); BaseFloat classprob = VecVec(hidden_out_vec, class_linear_vec) + class_bias_(cid); logprob[i] = prob+classprob-class_constant_[cid]-class_constant_.back(); } // next produce and save current word rc information (recommend GPU) // restore history int num_layers = context_in[0]->his_recurrent.size(); for (i = 0; i < num_layers; i++) { for (j = 0; j < num_stream_; j++) { his_recurrent_[i].Row(j).CopyFromVec(context_in[j]->his_recurrent[i]); his_cell_[i].Row(j).CopyFromVec(context_in[j]->his_cell[i]); } } nnlm_.RestoreContext(his_recurrent_, his_cell_); in_words_mat_.CopyColFromVec(in_words_, 0); words_.CopyFromMat(in_words_mat_); // forward propagate nnlm_.Propagate(words_, &hidden_out_); // save current words history nnlm_.SaveContext(his_recurrent_, his_cell_); for (i = 0; i < num_layers; i++) { for (j = 0; j < num_stream_; j++) { context_out[j]->his_recurrent[i] = his_recurrent_[i].Row(j); context_out[j]->his_cell[i] = his_cell_[i].Row(j); } } } BaseFloat KaldiNNlmWrapper::GetLogProb(int32 curt_word, LstmLmHistroy *context_in, LstmLmHistroy *context_out) { // get current words log probility (CPU done) BaseFloat logprob = 0.0; int i, cid = word2class_[curt_word]; SubVector<BaseFloat> linear_vec(out_linearity_.Row(curt_word)); SubVector<BaseFloat> class_linear_vec(class_linearity_.Row(cid)); Vector<BaseFloat> &hidden_out_vec = context_in->his_recurrent.back(); BaseFloat prob = VecVec(hidden_out_vec, linear_vec) + out_bias_(curt_word); BaseFloat classprob = VecVec(hidden_out_vec, class_linear_vec) + class_bias_(cid); logprob = prob + classprob - class_constant_[cid] - class_constant_.back(); if (context_out == NULL) return logprob; // next produce and save current word rc information (recommend GPU) // restore history int num_layers = context_in->his_recurrent.size(); for (i = 0; i < num_layers; i++) { his_recurrent_[i].Row(0).CopyFromVec(context_in->his_recurrent[i]); his_cell_[i].Row(0).CopyFromVec(context_in->his_cell[i]); } nnlm_.RestoreContext(his_recurrent_, his_cell_); in_words_(0) = curt_word; in_words_mat_.CopyColFromVec(in_words_, 0); words_.CopyFromMat(in_words_mat_); // forward propagate nnlm_.Propagate(words_, &hidden_out_); // save current words history nnlm_.SaveContext(his_recurrent_, his_cell_); for (i = 0; i < num_layers; i++) { context_out->his_recurrent[i] = his_recurrent_[i].Row(0); context_out->his_cell[i] = his_cell_[i].Row(0); } return logprob; } NNlmDeterministicFst::NNlmDeterministicFst(int32 max_ngram_order, KaldiNNlmWrapper *nnlm) { KALDI_ASSERT(nnlm != NULL); max_ngram_order_ = max_ngram_order; nnlm_ = nnlm; // Uses empty history for <s>. std::vector<Label> bos; LstmLmHistroy* bos_context = new LstmLmHistroy(nnlm_->GetRDim(), nnlm_->GetCDim(), kSetZero); nnlm_->GetLogProb(nnlm_->GetSos(), bos_context, bos_context); state_to_wseq_.push_back(bos); state_to_context_.push_back(bos_context); wseq_to_state_[bos] = 0; start_state_ = 0; } NNlmDeterministicFst::~NNlmDeterministicFst() { for (int i = 0; i < state_to_context_.size(); i++) { delete state_to_context_[i]; state_to_context_[i] = NULL; } } fst::StdArc::Weight NNlmDeterministicFst::Final(StateId s) { // At this point, we should have created the state. KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size()); std::vector<Label> wseq = state_to_wseq_[s]; BaseFloat logprob = nnlm_->GetLogProb(nnlm_->GetEos(), state_to_context_[s], NULL); return Weight(-logprob); } bool NNlmDeterministicFst::GetArc(StateId s, Label ilabel, fst::StdArc *oarc) { // At this point, we should have created the state. KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size()); // map to nnlm wordlist int32 curt_word = nnlm_->GetWordId(ilabel); std::vector<Label> wseq = state_to_wseq_[s]; LstmLmHistroy *new_context = new LstmLmHistroy(nnlm_->GetRDim(), nnlm_->GetCDim(), kUndefined); BaseFloat logprob = nnlm_->GetLogProb(curt_word, state_to_context_[s], new_context); wseq.push_back(ilabel); if (max_ngram_order_ > 0) { while (wseq.size() >= max_ngram_order_) { // History state has at most <max_ngram_order_> - 1 words in the state. wseq.erase(wseq.begin(), wseq.begin() + 1); } } std::pair<const std::vector<Label>, StateId> wseq_state_pair( wseq, static_cast<Label>(state_to_wseq_.size())); // Attemps to insert the current <lseq_state_pair>. If the pair already exists // then it returns false. typedef MapType::iterator IterType; std::pair<IterType, bool> result = wseq_to_state_.insert(wseq_state_pair); // If the pair was just inserted, then also add it to <state_to_wseq_> and // <state_to_context_>. if (result.second == true) { state_to_wseq_.push_back(wseq); state_to_context_.push_back(new_context); } // Creates the arc. oarc->ilabel = ilabel; oarc->olabel = ilabel; oarc->nextstate = result.first->second; oarc->weight = Weight(-logprob); return true; } } // namespace kaldi
35.003106
97
0.704108
[ "vector", "model" ]
7d2a57b70638cb1b48af8a43d4b87ebb4d708224
1,850
cpp
C++
srcAmiga/modeler/opengl.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
2
2016-04-03T23:57:54.000Z
2019-12-05T17:50:37.000Z
srcAmiga/modeler/opengl.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
null
null
null
srcAmiga/modeler/opengl.cpp
privatosan/RayStorm
17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa
[ "MIT" ]
2
2015-06-20T19:22:47.000Z
2021-11-15T15:22:14.000Z
/*************** * PROGRAM: Modeler * NAME: opengl.cpp * DESCRIPTION: OpenGL platform specific implementation * AUTHORS: Andreas Heumann, Mike Hesser * HISTORY: * DATE NAME COMMENT * 02.03.98 ah initial release ***************/ #ifndef OPENGL_H #include "opengl.h" #endif #ifndef OBJECT_H #include "object.h" #endif BOOL OPENGL::CreateContext(ULONG left, ULONG top, ULONG width, ULONG height, BOOL directrender) { ULONG bottom; struct TagItem tags[] = { {(long)AMA_Window, (long)_window(win)}, {AMA_Left, _mleft(win)+left}, {AMA_Bottom, (_window(win))->Height-(top+height)-_mtop(win) - 1}, {AMA_Width, width + 1}, {AMA_Height, height + 1}, {AMA_DoubleBuf, TRUE}, {AMA_RGBMode, TRUE}, {AMA_DirectRender, directrender}, {TAG_DONE, NULL}, }; left = _mleft(win)+left; bottom = (_window(win))->Height-(top+height)-_mtop(win) - 1; width = width + 1; height = height + 1; if(!context || (left != this->left) || (bottom != this->bottom) || (width != this->width) || (height != this->height)) { this->left = left; this->bottom = bottom; this->width = width; this->height = height; if(context) DestroyContext(); context = PPC_STUB(AmigaMesaCreateContext)(tags); if(!context) return FALSE; } return TRUE; } void OPENGL::SwapBuffers() { PPC_STUB(AmigaMesaSwapBuffers)(context); } void OPENGL::DestroyContext() { if(context) { PPC_STUB(AmigaMesaDestroyContext)(context); context = NULL; } } void OPENGL::MakeCurrent() { if(context) PPC_STUB(AmigaMesaMakeCurrent)(context, context->buffer); } void OPENGL::Viewport(int left, int top, int width, int height) { if(context) { MakeCurrent(); PPC_STUB(glViewport)( left - (this->left - _mleft(win)), this->height - height, width, height); } }
21.022727
119
0.630811
[ "object" ]
7d2e077f06b98aaa4a05e635fccf797d5c1ce215
8,479
cpp
C++
ChromeWorker/fontreplace.cpp
vadkasevas/BAS
657f62794451c564c77d6f92b2afa9f5daf2f517
[ "MIT" ]
302
2016-05-20T12:55:23.000Z
2022-03-29T02:26:14.000Z
ChromeWorker/fontreplace.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
9
2016-07-21T09:04:50.000Z
2021-05-16T07:34:42.000Z
ChromeWorker/fontreplace.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
113
2016-05-18T07:48:37.000Z
2022-02-26T12:59:39.000Z
#include <Windows.h> #include "fontreplace.h" #include "MinHook.h" #include "converter.h" #include "log.h" #include "split.h" #include "trim.h" #include "multithreading.h" typedef HFONT (WINAPI *BAS_TYPE_CreateFontIndirectW)(CONST LOGFONTW *); BAS_TYPE_CreateFontIndirectW BAS_POINTER_CreateFontIndirectW = NULL; HFONT WINAPI BAS_REPLACED_CreateFontIndirectW(CONST LOGFONTW *lplf) { //WORKER_LOG(std::string(" <- CreateFontIndirectW ") + ws2s(lplf->lfFaceName)); std::wstring OriginalFont; std::wstring Font(lplf->lfFaceName); if(FontReplace::GetInstance().IsStandartFont(Font)) { //font is standart }else { if(!FontReplace::GetInstance().NeedDisplayFont(Font)) { //No need to display font, change to standart OriginalFont.assign(lplf->lfFaceName); OriginalFont.push_back(0); std::wstring ReplaceFont(L"Times New Roman\0"); wcsncpy((wchar_t*)lplf->lfFaceName, ReplaceFont.data(), ReplaceFont.length() + 1); }else { //need to display font /*if(FontReplace::GetInstance().IsFontIsPresentInSystem(Font)) { //if font already present in system }else { //if not present in system, but need to display OriginalFont.assign(lplf->lfFaceName); OriginalFont.push_back(0); std::wstring ReplaceFont(L"Comic Sans MS\0"); wcsncpy((wchar_t*)lplf->lfFaceName, ReplaceFont.data(), ReplaceFont.length() + 1); }*/ } } //WORKER_LOG(std::string(" -> CreateFontIndirectW ") + ws2s(lplf->lfFaceName)); HFONT res = BAS_POINTER_CreateFontIndirectW(lplf); if(!OriginalFont.empty()) { wcsncpy((wchar_t*)lplf->lfFaceName, OriginalFont.data(), OriginalFont.length()); } return res; } static int CALLBACK EnumFontFamExProc(ENUMLOGFONTEXW* logical_font, NEWTEXTMETRICEXW* physical_font, DWORD font_type, LPARAM lparam) { FontReplace* font_replace = reinterpret_cast<FontReplace*>(lparam); if (font_replace) { const LOGFONTW& lf = logical_font->elfLogFont; if (lf.lfFaceName[0] && lf.lfFaceName[0] != '@') { std::wstring face_name(lf.lfFaceName); font_replace->AddFontPresentInSystem(face_name); } } return 1; } void FontReplace::CollectFonts() { if(IsFontsCollectedSystem) return; LOGFONTW logfont; memset(&logfont, 0, sizeof(logfont)); logfont.lfCharSet = DEFAULT_CHARSET; HDC hdc = ::GetDC(NULL); EnumFontFamiliesExW(hdc, &logfont, (FONTENUMPROCW)&EnumFontFamExProc,(LPARAM)this, 0); ReleaseDC(NULL, hdc); IsFontsCollectedSystem = true; } void FontReplace::AddFontPresentInSystem(const std::wstring& font) { if(IsFontIsPresentInSystem(font)) return; std::wstring font_copy = font; std::transform(font_copy.begin(), font_copy.end(), font_copy.begin(), ::tolower); WORKER_LOG(std::string("Available font ") + ws2s(font_copy)); fonts_available.push_back(font_copy); } bool FontReplace::IsFontIsPresentInSystem(const std::wstring& font) { std::wstring font_copy = font; std::transform(font_copy.begin(), font_copy.end(), font_copy.begin(), ::tolower); return std::find(fonts_available.begin(), fonts_available.end(), font_copy) != fonts_available.end(); } bool FontReplace::IsStandartFont(const std::wstring& font) { std::wstring font_copy = font; std::transform(font_copy.begin(), font_copy.end(), font_copy.begin(), ::tolower); return font_copy == std::wstring(L"arial") || font_copy == std::wstring(L"times new roman") || font_copy == std::wstring(L"courier new") || font_copy == std::wstring(L"lucida console") || font_copy == std::wstring(L"georgia") || font_copy == std::wstring(L"") || font_copy.find(L"==") != std::wstring::npos; } bool FontReplace::NeedDisplayFont(const std::wstring& font) { std::wstring font_copy = font; std::transform(font_copy.begin(), font_copy.end(), font_copy.begin(), ::tolower); LOCK_FONTS return std::find(fonts.begin(), fonts.end(), font_copy) != fonts.end(); } void FontReplace::InstallFonts() { if(IsFontsInstalled) return; WORKER_LOG(std::string("FontReplace::InstallFonts")); WIN32_FIND_DATA search_data; memset(&search_data, 0, sizeof(WIN32_FIND_DATA)); HANDLE handle = FindFirstFile(L"fonts\\*", &search_data); while(handle != INVALID_HANDLE_VALUE) { search_data.cFileName; if(std::wstring(search_data.cFileName) != L"." && std::wstring(search_data.cFileName) != L"..") { std::wstring font(search_data.cFileName); /*if(!IsFontsCollectedAdditional) { std::string font_copy = ws2s(font); std::transform(font_copy.begin(), font_copy.end(), font_copy.begin(), ::tolower); font_copy = split(font_copy,'.')[0]; AddFontPresentInSystem(s2ws(font_copy)); }*/ font = std::wstring(L"fonts\\") + font; AddFontResourceEx(font.c_str(), FR_PRIVATE /*| FR_NOT_ENUM*/, 0); WORKER_LOG(std::string("Found font ") + ws2s(font)); } if(FindNextFile(handle, &search_data) == FALSE) break; } FindClose(handle); IsFontsInstalled = true; IsFontsCollectedAdditional = true; } void FontReplace::UninstallFonts() { if(!IsFontsInstalled) return; WORKER_LOG(std::string("FontReplace::UninstallFonts")); WIN32_FIND_DATA search_data; memset(&search_data, 0, sizeof(WIN32_FIND_DATA)); HANDLE handle = FindFirstFile(L"fonts\\*", &search_data); while(handle != INVALID_HANDLE_VALUE) { search_data.cFileName; if(std::wstring(search_data.cFileName) != L"." && std::wstring(search_data.cFileName) != L"..") { std::wstring font(search_data.cFileName); font = std::wstring(L"fonts\\") + font; RemoveFontResourceEx(font.c_str(), FR_PRIVATE /*| FR_NOT_ENUM*/, 0); WORKER_LOG(std::string("Remove font ") + ws2s(font)); } if(FindNextFile(handle, &search_data) == FALSE) break; } FindClose(handle); IsFontsInstalled = false; } bool FontReplace::Initialize() { if (MH_Initialize() != MH_OK) { WORKER_LOG("FontReplace::Initialize Failed MH_Initialize"); return false; } if (MH_CreateHook(&CreateFontIndirectW, &BAS_REPLACED_CreateFontIndirectW, reinterpret_cast<LPVOID*>(&BAS_POINTER_CreateFontIndirectW)) != MH_OK) { WORKER_LOG("FontReplace::Initialize Failed MH_CreateHook"); return false; } WORKER_LOG("FontReplace::Initialize Success"); IsHookInstalled = false; return true; } bool FontReplace::Hook() { if(IsHookInstalled) return true; InstallFonts(); CollectFonts(); if (MH_EnableHook(&CreateFontIndirectW) != MH_OK) { WORKER_LOG("FontReplace::Hook failed MH_EnableHook"); return false; } WORKER_LOG("FontReplace::Hook Success"); IsHookInstalled = true; return true; } void FontReplace::SetFonts(const std::string& fonts) { LOCK_FONTS this->fonts.clear(); std::vector<std::string> all = split(fonts,';'); for(std::string& font: all) { std::string tf = trim(font); std::transform(tf.begin(), tf.end(), tf.begin(), ::tolower); if(tf.size() > 0) this->fonts.push_back(s2ws(tf)); } } bool FontReplace::UnHook() { if(!IsHookInstalled) return true; { LOCK_FONTS fonts.clear(); } UninstallFonts(); if (MH_DisableHook(&CreateFontIndirectW) != MH_OK) { WORKER_LOG("FontReplace::UnHook Failed MH_DisableHook"); return false; } WORKER_LOG("FontReplace::UnHook Success"); IsHookInstalled = false; return true; } bool FontReplace::Uninitialize() { UnHook(); if (MH_Uninitialize() != MH_OK) { WORKER_LOG("FontReplace::Uninitialize Failed MH_Uninitialize"); return false; } WORKER_LOG("FontReplace::Uninitialize Success"); return true; }
27.263666
149
0.617644
[ "vector", "transform" ]
7d351c281ec83c1272ff511d4012e219241f4fde
5,801
cpp
C++
src/ngraph/op/softmax.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/op/softmax.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/op/softmax.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-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 "ngraph/op/softmax.hpp" #include <algorithm> #include "ngraph/builder/autobroadcast.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/subtract.hpp" #include "ngraph/op/sum.hpp" #include "ngraph/util.hpp" using namespace std; using namespace ngraph; // *** SOFTMAX OP SET 0 *** constexpr NodeTypeInfo op::v0::Softmax::type_info; op::v0::Softmax::Softmax(const Output<Node>& arg, const AxisSet& axes) : Op({arg}) , m_axes(axes) { constructor_validate_and_infer_types(); const PartialShape& input_shape = get_input_partial_shape(0); NODE_VALIDATION_CHECK(this, input_shape.rank().is_static(), "Input node rank must be static (input_shape=", input_shape, ")."); for (auto axis : m_axes) { NODE_VALIDATION_CHECK(this, axis < static_cast<size_t>(input_shape.rank()), "Reduction axis (", axis, ") is out of bounds (argument shape: ", input_shape, ")."); } if (input_shape.is_static()) { set_output_type(0, get_input_element_type(0), input_shape.to_shape()); } else { set_output_type(0, get_input_element_type(0), PartialShape::dynamic()); } // empty axes == all axes if (m_axes.size() == 0) { for (size_t i = 0; i < get_shape().size(); ++i) { m_axes.insert(i); } } } shared_ptr<Node> op::v0::Softmax::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<Softmax>(new_args.at(0), m_axes); } void op::v0::Softmax::generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) { auto delta = deltas.at(0); auto z = delta * shared_from_this(); auto zsum = make_shared<op::Sum>(z, m_axes); Shape shape; for (size_t i = 0; i < get_shape().size(); ++i) { if (m_axes.find(i) == m_axes.end()) { shape.push_back(get_shape()[i]); } else { shape.push_back(1); } } auto order = ngraph::get_default_order(zsum->get_shape()); auto zreshape = make_shared<op::Reshape>(zsum, order, shape); auto adjoint = z - builder::make_with_numpy_broadcast<op::Multiply>(output(0), zreshape); auto x = input_value(0); adjoints.add_delta(x, adjoint); } // *** SOFTMAX OP SET V1 *** constexpr NodeTypeInfo op::v1::Softmax::type_info; op::v1::Softmax::Softmax(const Output<Node>& arg, const size_t axis) : Op({arg}) , m_axis(axis) { constructor_validate_and_infer_types(); const PartialShape& input_shape = get_input_partial_shape(0); NODE_VALIDATION_CHECK(this, input_shape.rank().is_static(), "Input node rank must be static (input_shape=", input_shape, ")."); NODE_VALIDATION_CHECK(this, axis < static_cast<size_t>(input_shape.rank()), "Reduction axis (", axis, ") is out of bounds (argument shape: ", input_shape, ")."); if (input_shape.is_static()) set_output_type(0, get_input_element_type(0), input_shape.to_shape()); else set_output_type(0, get_input_element_type(0), PartialShape::dynamic()); } shared_ptr<Node> op::v1::Softmax::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<op::v1::Softmax>(new_args.at(0), m_axis); } void op::v1::Softmax::generate_adjoints(autodiff::Adjoints& /* adjoints */, const NodeVector& /* deltas */) { throw ngraph_error("op::v1::Softmax::generate_adjoints function is not implemented yet"); /* This might work, but as of this writing we have no way to test it, so we are being careful auto delta = deltas.at(0); auto z = delta * shared_from_this(); std::vector<size_t> axes(get_shape().size() - m_axis); std::iota(std::begin(axes), std::end(axes), m_axis); AxisSet axes_set{axes}; auto zsum = make_shared<op::Sum>(z, axes_set); Shape shape; for (size_t i = 0; i < get_shape().size(); ++i) { if (axes_set.find(i) == axes_set.end()) { shape.push_back(get_shape()[i]); } else { shape.push_back(1); } } auto order = ngraph::get_default_order(zsum->get_shape()); auto zreshape = make_shared<op::Reshape>(zsum, order, shape); auto adjoint = z - builder::make_with_numpy_broadcast<op::Multiply>(output(0), zreshape); auto x = input(0).get_source_output(); adjoints.add_delta(x, adjoint); */ }
32.049724
97
0.576108
[ "shape", "vector" ]
7d3d2dea69f3711b593efd1023329b707bf5e821
4,221
cpp
C++
SofaKernel/framework/sofa/core/behavior/BaseMechanicalState.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/framework/sofa/core/behavior/BaseMechanicalState.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/framework/sofa/core/behavior/BaseMechanicalState.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/behavior/BaseMechanicalState.h> #include <sofa/core/objectmodel/BaseNode.h> namespace sofa { namespace core { namespace behavior { BaseMechanicalState::BaseMechanicalState() { } BaseMechanicalState::~BaseMechanicalState() { } /// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$ /// /// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$. /// Note that if the result vector appears inside the expression, it must be the first operand. /// By default this method decompose the computation into multiple vOp calls. void BaseMechanicalState::vMultiOp(const ExecParams* params, const VMultiOp& ops) { for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it) { VecId r = it->first.getId(this); const helper::vector< std::pair< ConstMultiVecId, SReal > >& operands = it->second; size_t nop = operands.size(); if (nop==0) { vOp(params, r); } else if (nop==1) { if (operands[0].second == 1.0) vOp( params, r, operands[0].first.getId(this)); else vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second); } else { size_t i; if (operands[0].second == 1.0) { vOp( params, r, operands[0].first.getId(this), operands[1].first.getId(this), operands[1].second); i = 2; } else { vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second); i = 1; } for (; i<nop; ++i) vOp( params, r, r, operands[i].first.getId(this), operands[i].second); } } } /// Handle state Changes from a given Topology void BaseMechanicalState::handleStateChange(core::topology::Topology* /*t*/) { // if (t == this->getContext()->getTopology()) // { handleStateChange(); // } } void BaseMechanicalState::writeState( std::ostream& ) { } bool BaseMechanicalState::insertInNode( objectmodel::BaseNode* node ) { node->addMechanicalState(this); Inherit1::insertInNode(node); return true; } bool BaseMechanicalState::removeInNode( objectmodel::BaseNode* node ) { node->removeMechanicalState(this); Inherit1::removeInNode(node); return true; } } // namespace behavior } // namespace core } // namespace sofa
36.076923
114
0.521914
[ "vector" ]
7d4130e4fef1b0f3bc6cd3662bff230c8b9c3497
12,517
cc
C++
cccc/cccc_opt.cc
bbannier/cccc
ff4e76179f7a13781575d173867de0311419f4ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2016-10-07T14:26:42.000Z
2016-10-07T14:26:42.000Z
cccc/cccc_opt.cc
bbannier/cccc
ff4e76179f7a13781575d173867de0311419f4ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
cccc/cccc_opt.cc
bbannier/cccc
ff4e76179f7a13781575d173867de0311419f4ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* CCCC - C and C++ Code Counter Copyright (C) 1994-2005 Tim Littlefair (tim_littlefair@hotmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ // cccc_opt.cc #include "cccc.h" #include <fstream> #include "cccc_opt.h" #include "cccc_utl.h" #include "cccc_met.h" #include <map> typedef std::map<string,string> file_extension_language_map_t; typedef std::map<string,Metric_Treatment*> metric_treatment_map_t; typedef std::pair<string,string> dialect_keyword_t; typedef std::map<dialect_keyword_t,string> dialect_keyword_map_t; static file_extension_language_map_t extension_map; static metric_treatment_map_t treatment_map; static dialect_keyword_map_t dialect_keyword_map; // these are declared extern so that it can be defined later in the file extern const char *default_fileext_options[]; extern const char *default_treatment_options[]; extern const char *default_dialect_options[]; static void add_file_extension(CCCC_Item& fileext_line) { string ext, lang; if( fileext_line.Extract(ext) && fileext_line.Extract(lang) ) { file_extension_language_map_t::value_type extension_pair(ext,lang); extension_map.insert(extension_pair); } } void add_treatment(CCCC_Item& treatment_line) { Metric_Treatment *new_treatment=new Metric_Treatment(treatment_line); metric_treatment_map_t::iterator iter= treatment_map.find(new_treatment->code); if(iter!=treatment_map.end()) { delete (*iter).second; (*iter).second=new_treatment; } else { metric_treatment_map_t::value_type treatment_pair(new_treatment->code,new_treatment); treatment_map.insert(treatment_pair); } } static void add_dialect_keyword(CCCC_Item& dialect_keyword_line) { string dialect, keyword, policy; if( dialect_keyword_line.Extract(dialect) && dialect_keyword_line.Extract(keyword) && dialect_keyword_line.Extract(policy) ) { dialect_keyword_map_t::key_type kt(dialect,keyword); dialect_keyword_map_t::value_type vt(kt,policy); dialect_keyword_map.insert(vt); } } void CCCC_Options::Add_Option(CCCC_Item& option) { string first_token; bool retval=option.Extract(first_token); if(retval==false) { // do nothing } else if(first_token=="CCCC_FileExt") { add_file_extension(option); } else if(first_token=="CCCC_MetTmnt") { add_treatment(option); } else if(first_token=="CCCC_Dialect") { add_dialect_keyword(option); } else { retval=false; } } void CCCC_Options::Save_Options(const string& filename) { ofstream optstr(filename.c_str()); file_extension_language_map_t::iterator felIter; for(felIter=extension_map.begin(); felIter!=extension_map.end(); ++felIter) { CCCC_Item extLine; extLine.Insert("CCCC_FileExt"); extLine.Insert((*felIter).first.c_str()); extLine.Insert((*felIter).second.c_str()); extLine.ToFile(optstr); } metric_treatment_map_t::iterator tIter; for(tIter=treatment_map.begin(); tIter!=treatment_map.end(); ++tIter) { CCCC_Item tmtLine; tmtLine.Insert("CCCC_MetTmnt"); tmtLine.Insert((*tIter).second->code); tmtLine.Insert((*tIter).second->lower_threshold); tmtLine.Insert((*tIter).second->upper_threshold); tmtLine.Insert((*tIter).second->numerator_threshold); tmtLine.Insert((*tIter).second->width); tmtLine.Insert((*tIter).second->precision); tmtLine.Insert((*tIter).second->name); tmtLine.ToFile(optstr); } dialect_keyword_map_t::iterator dkIter; for(dkIter=dialect_keyword_map.begin(); dkIter!=dialect_keyword_map.end(); ++dkIter) { CCCC_Item dkLine; dkLine.Insert("CCCC_Dialect"); dkLine.Insert((*dkIter).first.first); dkLine.Insert((*dkIter).first.second); dkLine.Insert((*dkIter).second); dkLine.ToFile(optstr); } } void CCCC_Options::Load_Options(const string& filename) { ifstream optstr(filename.c_str()); while(optstr.good()) { CCCC_Item option_line; if(optstr.good() && option_line.FromFile(optstr) ) { Add_Option(option_line); } } } // initialise using hard-coded defaults void CCCC_Options::Load_Options() { int i=0; const char **option_ptr; option_ptr=default_fileext_options; while( (*option_ptr)!=NULL) { string option_string="CCCC_FileExt@"; option_string+=(*option_ptr); CCCC_Item option_line(option_string); Add_Option(option_line); option_ptr++; } option_ptr=default_treatment_options; while( (*option_ptr)!=NULL) { string option_string="CCCC_MetTmnt@"; option_string+=(*option_ptr); CCCC_Item option_line(option_string); Add_Option(option_line); option_ptr++; } option_ptr=default_dialect_options; while( (*option_ptr)!=NULL) { string option_string="CCCC_Dialect@"; option_string+=(*option_ptr); CCCC_Item option_line(option_string); Add_Option(option_line); option_ptr++; } } // map a filename to a language string CCCC_Options::getFileLanguage(const string& filename) { string retval; string extension; file_extension_language_map_t::iterator iter; unsigned int extpos=filename.rfind("."); if(extpos!=string::npos) { extension=filename.substr(extpos); iter=extension_map.find(extension); if(iter!=extension_map.end()) { retval=(*iter).second; } } if(retval.size()==0) { iter=extension_map.find(""); if(iter!=extension_map.end()) { retval=(*iter).second; } else { // could not find language for extension cerr << "No language found for extension " << extension.c_str() << endl; } } return retval; } // map a metric name to a Metric_Treatment object Metric_Treatment *CCCC_Options::getMetricTreatment(const string& metric_tag) { Metric_Treatment *retval=NULL; metric_treatment_map_t::iterator iter=treatment_map.find(metric_tag); if(iter!=treatment_map.end()) { retval=(*iter).second; } return retval; } string CCCC_Options::dialectKeywordPolicy(const string& lang, const string& kw) { string retval; dialect_keyword_map_t::key_type kt(lang,kw); dialect_keyword_map_t::const_iterator iter=dialect_keyword_map.find(kt); if(iter!=dialect_keyword_map.end()) { retval=(*iter).second; } return retval; } const char *default_fileext_options[]= { // file extensions ".c@c.ansi@", ".h@c++.ansi@", ".cc@c++.ansi@", ".cpp@c++.ansi@", ".cxx@c++.ansi@", ".c++@c++.ansi@", ".C@c++.ansi@", ".CC@c++.ansi@", ".CPP@c++.ansi@", ".CXX@c++.ansi@", ".hh@c++.ansi@", ".hpp@c++.ansi@", ".hxx@c++.ansi@", ".h++@c++.ansi@", ".H@c++.ansi@", ".HH@c++.ansi@", ".HPP@c++.ansi@", ".HXX@c++.ansi@", ".H++@c++.ansi@", ".j@java@", ".jav@java@", ".java@java@", ".J@java@", ".JAV@java@", ".JAVA@java@", ".ada@ada.95@", ".ads@ada.95@", ".adb@ada.95@", ".ADA@ada.95@", ".ADS@ada.95@", ".ADB@ada.95@", // The language associated with the empty file extension would be used as a default // if defined. // This is presently disabled so that we don't process files in // MSVC projects like .rc, .odl which are not in C++. // "@c++.ansi@", NULL }; const char *default_treatment_options[] = { // metric treatments // all metric values are displayed using the class CCCC_Metric, which may be // viewed as ratio of two integers associated with a character string tag // the denominator of the ratio defaults to 1, allowing simple counts to // be handled by the same code as is used for ratios // // the tag associated with a metric is used as a key to lookup a record // describing a policy for its display (class Metric_Treatment) // // the fields of each treatment record are as follows: // TAG the short string of characters used as the lookup key. // T1, T2 two numeric thresholds which are the lower bounds for the ratio of // the metric's numerator and denominator beyond which the // value is treated as high or extreme by the analyser // these will be displayed in emphasized fonts, and if the browser // supports the BGCOLOR attribute, extreme values will have a red // background, while high values will have a yellow background. // The intent is that high values should be treated as suspicious but // tolerable in moderation, whereas extreme values should almost // always be regarded as defects (not necessarily that you will fix // them). // NT a third threshold which supresses calculation of ratios where // the numerator is lower than NT. // The principal reason for doing this is to prevent ratios like L_C // being shown as *** (infinity) and displayed as extreme when the // denominator is 0, providing the numerator is sufficiently low. // Suitable values are probably similar to those for T1. // W the width of the metric (total number of digits). // P the precision of the metric (digits after the decimal point). // Comment a free form field extending to the end of the line. // TAG T1 T2 NT W P Comment "LOCf@ 30@ 100@ 0@ 6@ 0@Lines of code/function@", "LOCm@ 500@ 2000@ 0@ 6@ 0@Lines of code/single module@", "LOCper@ 500@ 2000@ 0@ 6@ 3@Lines of code/average module@", "LOCp@ 999999@ 999999@ 0@ 6@ 0@Lines of code/project@", "MVGf@ 10@ 30@ 0@ 6@ 0@Cyclomatic complexity/function@", "MVGm@ 200@ 1000@ 0@ 6@ 0@Cyclomatic complexity/single module@", "MVGper@ 200@ 1000@ 0@ 6@ 3@Cyclomatic complexity/average module@", "MVGp@ 999999@ 999999@ 0@ 6@ 0@Cyclomatic complexity/project@", "COM@ 999999@ 999999@ 0@ 6@ 0@Comment lines@", "COMper@999999@ 999999@ 0@ 6@ 3@Comment lines (averaged)@", "M_C@ 5@ 10@ 5@ 6@ 3@MVG/COM McCabe/comment line@", "L_C@ 7@ 30@ 20@ 6@ 3@LOC/COM Lines of code/comment line@", "FI@ 12@ 20@ 0@ 6@ 0@Fan in (overall)@", "FIv@ 6@ 12@ 0@ 6@ 0@Fan in (visible uses only)@", "FIc@ 6@ 12@ 0@ 6@ 0@Fan in (concrete uses only)@", "FO@ 12@ 20@ 0@ 6@ 0@Fan out (overall)@", "FOv@ 6@ 12@ 0@ 6@ 0@Fan out (visible uses only)@", "FOc@ 6@ 12@ 0@ 6@ 0@Fan out (concrete uses only)@", "IF4@ 100@ 1000@ 0@ 6@ 0@Henry-Kafura/Shepperd measure (overall)@", "IF4v@ 30@ 100@ 0@ 6@ 0@Henry-Kafura/Shepperd measure (visible)@", "IF4c@ 30@ 100@ 0@ 6@ 0@Henry-Kafura/Shepperd measure (concrete)@", // WMC stands for weighted methods per class, // the suffix distinguishes the weighting function "WMC1@ 30@ 100@ 0@ 6@ 0@Weighting function=1 unit per method@", "WMCv@ 10@ 30@ 0@ 6@ 0@Weighting function=1 unit per visible method@", "DIT@ 3@ 6@ 0@ 6@ 0@Depth of Inheritance Tree@", "NOC@ 4@ 15@ 0@ 6@ 0@Number of children@", "CBO@ 12@ 30@ 0@ 6@ 0@Coupling between objects@", "8.3@ 999999@ 999999@ 0@ 8@ 3@General format for fixed precision 3 d.p.@", NULL }; const char *default_dialect_options[] = { // This configuration item allows the description of // dialects in which C/C++ identifiers get treated // as supplementary keyword. The rules specified // here (or in the runtime option file, if specified) // allow the parser to make the call // CCCC_Options::dialect_keyword_policy(lang,kw) which // returns a string. If nothing is known about the // pair <lang,kw>, an empty string is returned. If // an entry is specified here the associated string is // returned, which is called the policy, which the // parser uses to guide its actions. The most common // policy is to ignore, but any string can be // specified, providing the person implementing // the parser can think of an intelligent way to // proceed. "c++.mfc@BEGIN_MESSAGE_MAP@start_skipping@", "c++.mfc@END_MESSAGE_MAP@stop_skipping@", "c++.stl@__STL_BEGIN_NAMESPACE@ignore@", "c++.stl@__STL_END_NAMESPACE@ignore@", NULL };
29.451765
85
0.683311
[ "object" ]
7d444f29b943d9f063daf2fa43e131b69ce82b2e
1,767
c++
C++
Tests/baseConvert.c++
lepertheory/cxx-general
016794f89e2347edee3aa9232683400ab56b4c63
[ "MIT" ]
null
null
null
Tests/baseConvert.c++
lepertheory/cxx-general
016794f89e2347edee3aa9232683400ab56b4c63
[ "MIT" ]
null
null
null
Tests/baseConvert.c++
lepertheory/cxx-general
016794f89e2347edee3aa9232683400ab56b4c63
[ "MIT" ]
null
null
null
/***************************************************************************** * baseConvert.c++ ***************************************************************************** * Unit tests for the baseConvert() functions. *****************************************************************************/ // Standard includes. #include <string> #include <iostream> #include <limits> #include <vector> // Internal includes. #include "demangle.h++" #include "to_string.h++" #include "testcommon.h++" // Testing include. #include "baseConvert.h++" // Bring in namespaces. using namespace std; using namespace DAC; /*****************************************************************************/ // Declarations. // Run test suite on a given type. template <class T> int test (); /*****************************************************************************/ // Definitions. /* * Run test suite on a given type. */ template <class T> int test () { { string tmpstr; cout << "Testing type " << demangle<T>(tmpstr) << "..." << endl; } vector<T> edges; build_edges(edges); for (vector<T>::const_iterator frombase // All tests passed. return 0; } /* * This is it. */ int main () { // Test types. if (test<bool >()) { return 1; } if (test<char >()) { return 1; } if (test<signed char >()) { return 1; } if (test<unsigned char >()) { return 1; } if (test<wchar_t >()) { return 1; } if (test<short >()) { return 1; } if (test<unsigned short>()) { return 1; } if (test<int >()) { return 1; } if (test<unsigned int >()) { return 1; } if (test<long >()) { return 1; } if (test<unsigned long >()) { return 1; } // All tests passed. return 0; }
22.948052
79
0.441992
[ "vector" ]
7d659848c3143e81a2a4a8fe7904e938cbd6301b
3,655
cpp
C++
src/qt/src/corelib/statemachine/qfinalstate.cpp
martende/phantomjs
5cecd7dde7b8fd04ad2c036d16f09a8d2a139854
[ "BSD-3-Clause" ]
1
2015-03-16T20:49:09.000Z
2015-03-16T20:49:09.000Z
src/qt/src/corelib/statemachine/qfinalstate.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
src/qt/src/corelib/statemachine/qfinalstate.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfinalstate.h" #ifndef QT_NO_STATEMACHINE #include "qabstractstate_p.h" QT_BEGIN_NAMESPACE /*! \class QFinalState \brief The QFinalState class provides a final state. \since 4.6 \ingroup statemachine A final state is used to communicate that (part of) a QStateMachine has finished its work. When a final top-level state is entered, the state machine's \l{QStateMachine::finished()}{finished}() signal is emitted. In general, when a final substate (a child of a QState) is entered, the parent state's \l{QState::finished()}{finished}() signal is emitted. QFinalState is part of \l{The State Machine Framework}. To use a final state, you create a QFinalState object and add a transition to it from another state. Example: \code QPushButton button; QStateMachine machine; QState *s1 = new QState(); QFinalState *s2 = new QFinalState(); s1->addTransition(&button, SIGNAL(clicked()), s2); machine.addState(s1); machine.addState(s2); QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit())); machine.setInitialState(s1); machine.start(); \endcode \sa QState::finished() */ class QFinalStatePrivate : public QAbstractStatePrivate { Q_DECLARE_PUBLIC(QFinalState) public: QFinalStatePrivate(); }; QFinalStatePrivate::QFinalStatePrivate() : QAbstractStatePrivate(FinalState) { } /*! Constructs a new QFinalState object with the given \a parent state. */ QFinalState::QFinalState(QState *parent) : QAbstractState(*new QFinalStatePrivate, parent) { } /*! Destroys this final state. */ QFinalState::~QFinalState() { } /*! \reimp */ void QFinalState::onEntry(QEvent *event) { Q_UNUSED(event); } /*! \reimp */ void QFinalState::onExit(QEvent *event) { Q_UNUSED(event); } /*! \reimp */ bool QFinalState::event(QEvent *e) { return QAbstractState::event(e); } QT_END_NAMESPACE #endif //QT_NO_STATEMACHINE
25.921986
89
0.700684
[ "object" ]
de10982debac99c1f29eea5a9ad5962045b0bd93
4,205
cpp
C++
modules/compute/map_gen.cpp
GnaeusPompeius/godot
e4ae129d450e7e7a263fd789217dd24fbd293128
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/compute/map_gen.cpp
GnaeusPompeius/godot
e4ae129d450e7e7a263fd789217dd24fbd293128
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/compute/map_gen.cpp
GnaeusPompeius/godot
e4ae129d450e7e7a263fd789217dd24fbd293128
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/* map_gen.cpp */ #include "map_gen.h" void MapGenerator::_bind_methods() { //ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add); ClassDB::bind_method(D_METHOD("get_image"), &MapGenerator::get_image); ClassDB::bind_method(D_METHOD("step"), &MapGenerator::step); } MapGenerator::MapGenerator() { String path = String("C:\\Godot\\modules\\compute\\river.particle.comp"); terrain_shader.generate_program(path); world.resize(world_size_x * world_size_y); data.resize(particle_count); load_data(); generate_normals(); terrain_shader.set_workgroups(120, 120, 1); terrain_shader.set_input_data(data, world); terrain_shader.generate_buffers(); } void MapGenerator::step() { OS::get_singleton()->print("Step taken.\n"); terrain_shader.step(); } Ref<Image> MapGenerator::get_image() { //TerrainCell* out = terrain_shader.open_world_data(); WaterParticle *p_out = terrain_shader.open_particle_data(); OS::get_singleton()->print("%d\n", particle_count); StreamPeerBuffer image_data; image_data.resize(world_size_x * world_size_y * 3 * sizeof(float)); float value = 0; const float avg_population = float(particle_count) / (world_size_x * world_size_y * 256); WaterParticle particle; TerrainCell ter; image->create(world_size_x, world_size_y, false, Image::FORMAT_RGBF); image->lock(); for (int i = 0; i < particle_count; i++) { //Floats normalized to [0, 1] particle = p_out[i]; //ter = out[i]; //OS::get_singleton()->print("Pos %i: %i, %i, %f\n", i, int(particle.position.x), int(particle.position.y), particle.position.z); /* Color temp = image->get_pixel(int(particle.position.x), int(particle.position.y)); temp.b += 100 * avg_population; if (temp.b > 1) { temp.b = 1; } */ image->set_pixel(particle.position.x, particle.position.y, Color(0, 0, 1)); //float height = ter.height / 1400.0; //image->set_pixel(i % 3600, i / 3600, Color(height, height, height)); /* value = out[i].normal_NW.z / 5; image_data.put_float(out[i].normal_NW.x); //R image_data.put_float(out[i].normal_NW.y); //G image_data.put_float(out[i].normal_NW.z); //B */ } image->unlock(); terrain_shader.close_data(); return image; } TerrainCell MapGenerator::get_world_cell(uint32_t x, uint32_t y) { return world.get(x + world_size_x * y); } void MapGenerator::set_world_cell(uint32_t x, uint32_t y, TerrainCell cell) { return world.set(x + world_size_x * y, cell); } void MapGenerator::load_data() { //Replace file loading w/ generated data String path = String("D:\\Data\\Geography\\N42E12_adj.tif"); FileAccess *file = FileAccess::open(path, FileAccess::READ); uint16_t *source = (uint16_t *)calloc(file->get_len(), sizeof(uint8_t)); file->get_buffer((uint8_t *)source, file->get_len()); for (int i = 0; i < world_size_x * world_size_y; i++) { TerrainCell cell; cell.height = (float)(source[i]); world.write().ptr()[i] = cell; } file->close(); free(source); } //For Irrigation /* Godot's Plane Mesh: NW _____ Oppo | /| | / | |/__| Target SE */ void MapGenerator::generate_normals() { Vector3 NW_t, NW_o, SE_t, SE_o; TerrainCell target, opposite, NW, SE; for (int i = 0; i < world_size_x - 1; i++) { for (int j = 0; j < world_size_y - 1; j++) { target = get_world_cell(i, j); opposite = get_world_cell(i + 1, j + 1); NW = get_world_cell(i, j + 1); SE = get_world_cell(i + 1, j); //NW Normal // Cross( NW->Target, NW->Oppo ) NW_t = Vector3(0, -1 * terrain_resolution, NW.height - target.height); NW_o = Vector3(terrain_resolution, 0, opposite.height - NW.height); target.normal_NW = NW_t.cross(NW_o).normalized(); //SE Normal // Cross( SE->Oppo, SE->Target ) SE_t = Vector3(-1 * terrain_resolution, 0, target.height - SE.height); SE_o = Vector3(0, terrain_resolution, SE.height - opposite.height); target.normal_SE = SE_o.cross(SE_t).normalized(); //OS::get_singleton()->print("Normal NW: %f, %f, %f\n", target.normal_NW.x, target.normal_NW.y, target.normal_NW.z); //OS::get_singleton()->print(" Normal SE: %f, %f, %f\n", target.normal_SE.x, target.normal_SE.y, target.normal_SE.z); set_world_cell(i, j, target); } } }
28.605442
133
0.67396
[ "mesh" ]
de124a4b34c679775429dab748eda824657bce31
1,558
cpp
C++
main.cpp
astrellon/simple-snake
3dbe1f2af1afe31d3cef8bcc995d9150beafa1b2
[ "MIT" ]
null
null
null
main.cpp
astrellon/simple-snake
3dbe1f2af1afe31d3cef8bcc995d9150beafa1b2
[ "MIT" ]
null
null
null
main.cpp
astrellon/simple-snake
3dbe1f2af1afe31d3cef8bcc995d9150beafa1b2
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <iostream> #include <thread> #include <chrono> #include <vector> #include "src/engine.hpp" #include "src/managers/font_manager.hpp" #include "src/map.hpp" #include "src/tiles.hpp" #include "src/snake.hpp" #include "src/game_session.hpp" #include "src/particle_system.hpp" int main() { sf::RenderWindow window(sf::VideoMode(1280, 800), "Snake"); window.setVerticalSyncEnabled(true); town::Engine engine(window); engine.spriteScale(4.0f); engine.readDataPaths("data/data.csv"); auto textureManager = engine.textureManager(); auto sansFont = engine.fontManager()->font("sans"); auto spriteSize = static_cast<uint>(engine.spriteSize()); auto spriteScale = engine.spriteScale(); auto mapTiles = engine.tilesManager()->tiles("map"); auto portalTiles = engine.tilesManager()->tiles("portal"); auto portalSprite1 = portalTiles->getSprite(0); auto mapManager = engine.mapManager(); auto map1 = mapManager->loadMap("data/testMap.csv"); if (map1 == nullptr) { std::cout << "Cannot play without a map!" << std::endl; return 1; } map1->initTiles(mapTiles); auto gameSession = engine.startGameSession(); gameSession->currentMap(map1); // Create a text // sf::Text text("hello", *sansFont); // text.setCharacterSize(72); while (window.isOpen()) { engine.processEvents(); engine.preUpdate(); engine.update(); engine.draw(); } return 0; }
23.969231
63
0.655969
[ "vector" ]
de128031396c94922f4769f65758a8ac1a23569a
6,658
cc
C++
packages/Alea/mc_solvers/test/tstMC_Data.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/Alea/mc_solvers/test/tstMC_Data.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/Alea/mc_solvers/test/tstMC_Data.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file Alea/mc_solvers/test/tstMC_Data.cc * \author Steven Hamilton * \brief Test of MC_Data class. */ //---------------------------------------------------------------------------// #include <iostream> #include "gtest/utils_gtest.hh" #include "../LinearSystem.hh" #include "../LinearSystemFactory.hh" #include "../MC_Data.hh" #include "../PolynomialBasis.hh" #include "../AleaTypedefs.hh" #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" using namespace alea; TEST(MC_Data, Basic) { // Set problem parameters Teuchos::RCP<Teuchos::ParameterList> pl( new Teuchos::ParameterList() ); Teuchos::RCP<Teuchos::ParameterList> mat_pl = Teuchos::sublist(pl,"Problem"); Teuchos::RCP<Teuchos::ParameterList> poly_pl = Teuchos::sublist(pl,"Polynomial"); Teuchos::RCP<Teuchos::ParameterList> mc_pl = Teuchos::sublist(pl,"Monte Carlo"); // Construct Map LO N = 50; mat_pl->set("matrix_type","laplacian"); mat_pl->set("matrix_size",N); mat_pl->set("scaling_type","diagonal"); // Test Adjoint MC mc_pl->set("mc_type","adjoint"); Teuchos::RCP<alea::LinearSystem> system = alea::LinearSystemFactory::buildLinearSystem(pl); Teuchos::RCP<const MATRIX> A = system->getMatrix(); Teuchos::RCP<PolynomialBasis> basis( new PolynomialBasis("neumann") ); Teuchos::RCP<MC_Data> data(new MC_Data(A,basis,pl)); EXPECT_TRUE( data != Teuchos::null ); Teuchos::RCP<const MATRIX> H = data->getIterationMatrix(); EXPECT_TRUE( H != Teuchos::null ); EXPECT_EQ(H->getGlobalNumRows(), static_cast<size_t>(N)); EXPECT_EQ(H->getGlobalNumCols(), static_cast<size_t>(N)); Teuchos::RCP<const MATRIX> P = data->getProbabilityMatrix(); EXPECT_TRUE( P != Teuchos::null ); EXPECT_EQ(P->getGlobalNumRows(), static_cast<size_t>(N)); EXPECT_EQ(P->getGlobalNumCols(), static_cast<size_t>(N)); Teuchos::RCP<const MATRIX> W = data->getWeightMatrix(); EXPECT_TRUE( W != Teuchos::null ); EXPECT_EQ(W->getGlobalNumRows(), static_cast<size_t>(N)); EXPECT_EQ(W->getGlobalNumCols(), static_cast<size_t>(N)); // Test values in H, P, W // We intentially don't test details of how the matrix is stored, but // rather only the action of the matrix on various vectors MV x(A->getDomainMap(),1); MV y(A->getDomainMap(),1); for( LO icol=0; icol<N; ++icol ) { // Set vector to irow column of identity x.putScalar(0.0); x.replaceLocalValue(icol,0,1.0); // Multiply H->apply(x,y); // Check result for( LO irow=0; irow<N; ++irow ) { // Diagonal entries are 0 if( irow==icol ) { EXPECT_DOUBLE_EQ( 0.0, y.getData(0)[irow] ); } else if( irow==1 && icol==0 ) { EXPECT_DOUBLE_EQ( 1.0/3.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-1 ) { EXPECT_DOUBLE_EQ( 1.0/3.0, y.getData(0)[irow] ); } // First upper and lower diagonal are 0.5 else if( std::abs(irow-icol) == 1 ) { EXPECT_DOUBLE_EQ( 0.5, y.getData(0)[irow] ); } // Everything else is zero else { EXPECT_DOUBLE_EQ( 0.0, y.getData(0)[irow] ); } } // Multiply P->apply(x,y); // Check result for( LO irow=0; irow<N; ++irow ) { if( irow==0 && icol==0 ) { EXPECT_DOUBLE_EQ( 0.0, y.getData(0)[irow] ); } else if( irow==0 && icol==1 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( irow==1 && icol==0 ) { EXPECT_DOUBLE_EQ( 2.0/5.0, y.getData(0)[irow] ); } else if( irow==1 && icol==1 ) { EXPECT_DOUBLE_EQ( 2.0/5.0, y.getData(0)[irow] ); } else if( irow==1 && icol==2 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-3 ) { EXPECT_DOUBLE_EQ( 3.0/5.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-2 ) { EXPECT_DOUBLE_EQ( 3.0/5.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-1 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( irow==N-1 && icol==N-2 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( irow==N-1 && icol==N-1 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( icol - irow == 1 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else if( irow - icol == 1 ) { EXPECT_DOUBLE_EQ( 0.5, y.getData(0)[irow] ); } else if( icol == irow ) { EXPECT_DOUBLE_EQ( 0.5, y.getData(0)[irow] ); } else { EXPECT_DOUBLE_EQ( 0.0, y.getData(0)[irow] ); } } // Multiply W->apply(x,y); // Check result for( LO irow=0; irow<N; ++irow ) { if( irow==0 && icol==1 ) { EXPECT_DOUBLE_EQ( 0.5, y.getData(0)[irow] ); } else if( irow==1 && icol==0 ) { EXPECT_DOUBLE_EQ( 5.0/6.0, y.getData(0)[irow] ); } else if( irow==1 && icol==2 ) { EXPECT_DOUBLE_EQ( 5.0/6.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-3 ) { EXPECT_DOUBLE_EQ( 5.0/6.0, y.getData(0)[irow] ); } else if( irow==N-2 && icol==N-1 ) { EXPECT_DOUBLE_EQ( 5.0/6.0, y.getData(0)[irow] ); } else if( irow==N-1 && icol==N-2 ) { EXPECT_DOUBLE_EQ( 0.5, y.getData(0)[irow] ); } else if( std::abs(icol - irow) == 1 ) { EXPECT_DOUBLE_EQ( 1.0, y.getData(0)[irow] ); } else { EXPECT_DOUBLE_EQ( 0.0, y.getData(0)[irow] ); } } } }
30.682028
79
0.466206
[ "vector" ]
de14da6e64828f272231858a5449f84d9914c3b8
812
cpp
C++
N0221-Maximal-Square/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N0221-Maximal-Square/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N0221-Maximal-Square/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
2
2022-01-25T05:31:31.000Z
2022-02-26T07:22:23.000Z
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size() == 0 || matrix[0].size() == 0){ return 0; } int rows = matrix.size(), columns = matrix[0].size(); int maxS = 0; vector<vector<int>> dp(rows, vector<int>(columns)); for(int i = 0; i < rows; ++i){ for(int j = 0; j < columns; ++j){ if(matrix[i][j] == '1'){ if(i == 0 || j == 0){ dp[i][j] = 1; }else{ dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1; } maxS = max(maxS, dp[i][j]); } } } int maxArea = maxS * maxS; return maxArea; } };
31.230769
86
0.368227
[ "vector" ]
de1ae7d128eca3b06c5a4fed283afcefc8243c76
1,242
cpp
C++
leetcode/787.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
3
2020-06-25T21:04:02.000Z
2021-05-12T03:33:19.000Z
leetcode/787.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
null
null
null
leetcode/787.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
1
2020-06-25T21:04:06.000Z
2020-06-25T21:04:06.000Z
// Author: btjanaka (Bryon Tjanaka) // Problem: (LeetCode) 787 // Title: Cheapest Flights Within K Stops // Link: https://leetcode.com/problems/cheapest-flights-within-k-stops/ // Idea: Perform a BFS that only goes K layers deep, and if dst is reached // within that search, you can return its distance. // Difficulty: medium // Tags: BFS, graph class Solution { public: int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) { vector<vector<pair<int, int>>> g(n); for (vector<int> f : flights) { g[f[0]].push_back({f[1], f[2]}); } int d = -1; queue<tuple<int, int, int>> q; q.push({src, 0, 0}); while (!q.empty()) { int u, stops, dist; tie(u, stops, dist) = q.front(); q.pop(); for (pair<int, int> v : g[u]) { if (v.first == dst) { if (d == -1 || dist + v.second < d) { d = dist + v.second; } } else { // Don't add in the node if it exceeds the distance or number of // stops. if (stops < K && (d == -1 || dist + v.second < d)) { q.push({v.first, stops + 1, dist + v.second}); } } } } return d; } };
28.227273
78
0.519324
[ "vector" ]
de2360b7e7c9a84f095643c1f5331c6a4ed855d7
1,480
hpp
C++
src/prob/conf/inst/pass.hpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
2
2022-02-27T11:41:57.000Z
2022-03-03T04:15:24.000Z
src/prob/conf/inst/pass.hpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
null
null
null
src/prob/conf/inst/pass.hpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
1
2022-02-28T20:15:03.000Z
2022-02-28T20:15:03.000Z
// ---------------------------------------------------------------------------- // Header file for the Pass class. pass.hpp // Created by Ferhat Erata <ferhat.erata@yale.edu> on November 14, 2020. // Copyright (c) 2020 Yale University. All rights reserved. // ----------------------------------------------------------------------------- #ifndef STANDALONE_APPLICATION_WRITER_HPP #define STANDALONE_APPLICATION_WRITER_HPP #include <llvm/IR/Instruction.h> #include <llvm/Pass.h> #include <llvm/Support/CommandLine.h> #include <fstream> #include <vector> #include "model.hpp" namespace prob::conf::inst { llvm::cl::list<std::string> FileParam("model-file", llvm::cl::ZeroOrMore); class Pass : public llvm::ModulePass { public: static char ID; std::vector<Model> Configs; Pass() : ModulePass(ID) { parseConfigFile(FileParam.front()); }; bool runOnModule(llvm::Module& M) override { insertModelsIntoIR(M); return true; } private: void parseConfigFile(const std::string& fileName); static Model parseLine(const std::string& str); [[maybe_unused]] void printConfigFile(); std::pair<std::string, std::string> findModel(const std::string& opcode); void insertModelsIntoIR(llvm::Module& M); static void attachMetadata(llvm::Instruction& I, const std::pair<std::string, std::string>& model); }; } // namespace prob::conf::inst #endif // STANDALONE_APPLICATION_WRITER_HPP
28.461538
80
0.614189
[ "vector", "model" ]
de278b2b943d0ff52f510e82d360d1d2b509dee1
3,225
cpp
C++
tests/workers/test_facedetect.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
4
2021-11-03T21:32:55.000Z
2022-02-17T17:13:16.000Z
tests/workers/test_facedetect.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
null
null
null
tests/workers/test_facedetect.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
2
2022-03-05T20:01:33.000Z
2022-03-25T06:00:35.000Z
// Copyright 2021 Xilinx Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <cmath> // for abs #include <cstdlib> // for getenv #include "facedetect.hpp" // IWYU pragma: associated #include "gtest/gtest.h" // for Test, AssertionResult, EXPECT_EQ const int gold_response_size = 6; const float gold_response_output[gold_response_size] = { -1, 0.9937100410461426, 268, 79.875, 156, 169.06874084472656, }; std::string prepareDirectory() { fs::path temp_dir = fs::temp_directory_path() / "proteus/tests/cpp/native/facedetect"; fs::create_directories(temp_dir); auto src_file = fs::path(std::getenv("PROTEUS_ROOT")) / "tests/assets/girl-1867092_640.jpg"; fs::copy_file(src_file, temp_dir / src_file.filename(), fs::copy_options::skip_existing); return temp_dir; } void dequeue_validate(FutureQueue& my_queue, int num_images) { std::future<proteus::InferenceResponse> element; for (int i = 0; i < num_images; i++) { my_queue.wait_dequeue(element); auto results = element.get(); EXPECT_STREQ(results.getID().c_str(), ""); EXPECT_STREQ(results.getModel().c_str(), "facedetect"); auto outputs = results.getOutputs(); EXPECT_EQ(outputs.size(), 1); for (auto& output : outputs) { auto* data = static_cast<std::vector<float>*>(output.getData()); auto size = output.getSize(); EXPECT_STREQ(output.getName().c_str(), ""); EXPECT_STREQ(proteus::types::mapTypeToStr(output.getDatatype()).c_str(), "FP32"); auto* parameters = output.getParameters(); ASSERT_NE(parameters, nullptr); EXPECT_TRUE(parameters->empty()); auto num_boxes = gold_response_size / 6; auto shape = output.getShape(); EXPECT_EQ(shape.size(), 2); EXPECT_EQ(shape[0], 6); EXPECT_EQ(shape[1], num_boxes); EXPECT_EQ(size, gold_response_size); for (size_t i = 0; i < gold_response_size; i++) { // expect that the response values are within 1% of the golden const float abs_error = std::abs(gold_response_output[i] * 0.01); EXPECT_NEAR((*data)[i], gold_response_output[i], abs_error); } } } } // @pytest.mark.extensions(["vitis"]) // @pytest.mark.fpgas("DPUCADF8H", 1) TEST(Native, Facedetect) { proteus::initialize(); auto fpgas_exist = proteus::hasHardware("DPUCADF8H", 1); if (!fpgas_exist) { proteus::terminate(); GTEST_SKIP(); } auto path = prepareDirectory(); auto worker_name = load(1); auto image_paths = getImages(path); auto num_images = image_paths.size(); FutureQueue my_queue; run(image_paths, 1, worker_name, my_queue); dequeue_validate(my_queue, num_images); proteus::terminate(); }
34.308511
80
0.68093
[ "shape", "vector" ]
de40780f349623e27e2c31c4e1261d8646debf2c
708
cpp
C++
CodeForces/Registration System.cpp
abdelrahman0123/Problem-Solving
9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b
[ "MIT" ]
null
null
null
CodeForces/Registration System.cpp
abdelrahman0123/Problem-Solving
9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b
[ "MIT" ]
null
null
null
CodeForces/Registration System.cpp
abdelrahman0123/Problem-Solving
9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define all(v) v.begin(), v.end() #define sz(v) v.size() typedef long long ll; typedef vector<int> vi; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll lcm(ll a, ll b) { return a * b / gcd(a, b); } int main() { fast; // Code //ll t; cin >> t; vi print; // while (t--) int n; cin >> n; vector<string> v(n); map<string, int> mp; vector<string> p; for (int i = 0; i < n; i++) { cin >> v[i]; mp[v[i]]++; if (mp[v[i]] == 1) p.push_back("OK"); else p.push_back(v[i] + to_string(mp[v[i]] - 1)); } for (auto i : p) cout << i << endl; return 0; }
18.153846
67
0.54661
[ "vector" ]
de4c46e8732fc3248d36a282d0e3bcb52e141741
2,841
cpp
C++
JobBoard2/mainwindow.cpp
AlanD88/jobBoard
e97bd247a1a0c911b844cfa516063c7b45b7ac7b
[ "MIT" ]
null
null
null
JobBoard2/mainwindow.cpp
AlanD88/jobBoard
e97bd247a1a0c911b844cfa516063c7b45b7ac7b
[ "MIT" ]
null
null
null
JobBoard2/mainwindow.cpp
AlanD88/jobBoard
e97bd247a1a0c911b844cfa516063c7b45b7ac7b
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "additem.h" #include "edit.h" #include <QStandardItemModel> #include <fstream> #include <QDebug> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("C:/JobBoard/JobBoard.sqlite"); bool ok = db.open(); if (!ok) { qDebug("Failed to open the database."); } else { qDebug("Connected..."); } LoadTable(); } MainWindow::~MainWindow() { db.close(); delete ui; } void MainWindow::on_pushButton_Add_clicked() { /*Opening a new window for adding jobs */ additem dialogwindow; dialogwindow.setModal(true); dialogwindow.exec(); } void MainWindow::on_pushButton_Refresh_clicked() { LoadTable(); } void MainWindow::on_pushButton_Edit_clicked() { edit dialogWindow; dialogWindow.setModal(true); dialogWindow.exec(); } void MainWindow::LoadTable() { /* Loads the Filtered tables from the database into each respected tab in the main window UI */ /*"All" Tab*/ model = new QSqlTableModel(this); model->setTable("jobboard"); model->select(); ui->tableView->setModel(model); toApply = new QSqlTableModel(this); toApply->setTable("jobboard"); toApply->setFilter("status='To Apply'"); toApply->select(); ui->tableView_toApply->setModel(toApply); inProgress = new QSqlTableModel(this); inProgress->setTable("jobboard"); inProgress->setFilter("status='In Progress'"); inProgress->select(); ui->tableView_InProgress->setModel(inProgress); applied = new QSqlTableModel(this); applied->setTable("jobboard"); applied->setFilter("status='Applied'"); applied->select(); ui->tableView_Applied->setModel(applied); followUp = new QSqlTableModel(this); followUp->setTable("jobboard"); followUp->setFilter("status='Follow Up'"); followUp->select(); ui->tableView_FollowUp->setModel(followUp); offer = new QSqlTableModel(this); offer->setTable("jobboard"); offer->setFilter("status='Offer'"); offer->select(); ui->tableView_Offer->setModel(offer); declined = new QSqlTableModel(this); declined->setTable("jobboard"); declined->setFilter("status='Rejected'"); declined->select(); ui->tableView_Rejected->setModel(declined); noResponse = new QSqlTableModel(this); noResponse->setTable("jobboard"); noResponse->setFilter("status='No Response'"); noResponse->select(); ui->tableView_NoResponse->setModel(noResponse); }
25.594595
97
0.629356
[ "model" ]
de511406a91a5ff899e635995d27e3b8010ef96b
80,429
cxx
C++
Modules/Core/Metadata/src/otbPleiadesImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/src/otbPleiadesImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/src/otbPleiadesImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
1
2020-10-15T09:37:30.000Z
2020-10-15T09:37:30.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbPleiadesImageMetadataInterface.h" #include "otbMacro.h" #include "itkMetaDataObject.h" #include "otbImageKeywordlist.h" #include "otbGeometryMetadata.h" #include "otbStringUtils.h" // useful constants #include <otbMath.h> namespace otb { using boost::lexical_cast; using boost::bad_lexical_cast; PleiadesImageMetadataInterface::PleiadesImageMetadataInterface() { } bool PleiadesImageMetadataInterface::CanRead() const { std::string sensorID = GetSensorID(); if (sensorID.find("PHR") != std::string::npos) return true; else return false; } std::string PleiadesImageMetadataInterface::GetInstrument() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (imageKeywordlist.HasKey("support_data.instrument")) { std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.instrument"); return valueString; } return ""; } std::string PleiadesImageMetadataInterface::GetInstrumentIndex() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (imageKeywordlist.HasKey("support_data.instrument_index")) { std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.instrument_index"); return valueString; } return ""; // Invalid value } PleiadesImageMetadataInterface::VariableLengthVectorType PleiadesImageMetadataInterface::GetSolarIrradiance() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } std::vector<double> outputValues; if (imageKeywordlist.HasKey("support_data.solar_irradiance")) { std::vector<std::string> outputValuesString; std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.solar_irradiance"); boost::trim(valueString); boost::split(outputValuesString, valueString, boost::is_any_of(" ")); for (unsigned int i = 0; i < outputValuesString.size(); ++i) { outputValues.push_back(atof(outputValuesString[i].c_str())); } } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // Check that values read from metadata is not too far from the standard realistic values // '999' are likely to be dummy values (see Mantis #601) // This values were provided by the French Space Agency double defaultRadianceMS[4]; double defaultRadianceP; const std::string sensorId = this->GetSensorID(); if (sensorId == "PHR 1A") { // MS, ordered as B0, B1, B2, B3 defaultRadianceMS[0] = 1915.01; defaultRadianceMS[1] = 1830.57; defaultRadianceMS[2] = 1594.06; defaultRadianceMS[3] = 1060.01; defaultRadianceP = 1548.71; } else if (sensorId == "PHR 1B") { // MS, ordered as B0, B1, B2, B3 defaultRadianceMS[0] = 1926.51688; defaultRadianceMS[1] = 1805.91412; defaultRadianceMS[2] = 1533.60973; defaultRadianceMS[3] = 1019.23037; defaultRadianceP = 1529.00384; } else { itkExceptionMacro(<< "Invalid sensor ID."); } // tolerance threshold double tolerance = 0.05; if (outputValues.size() == 1) { // Pan if (std::abs(outputValues[0] - defaultRadianceP) > (tolerance * defaultRadianceP)) { outputValuesVariableLengthVector[0] = defaultRadianceP; } else { outputValuesVariableLengthVector[0] = outputValues[0]; } } else { // MS for (unsigned int i = 0; i < outputValues.size(); ++i) { int wavelenghPos = this->BandIndexToWavelengthPosition(i); if (std::abs(outputValues[wavelenghPos] - defaultRadianceMS[wavelenghPos]) > (tolerance * defaultRadianceMS[wavelenghPos])) { outputValuesVariableLengthVector[i] = defaultRadianceMS[wavelenghPos]; } else { outputValuesVariableLengthVector[i] = outputValues[wavelenghPos]; } } } return outputValuesVariableLengthVector; } int PleiadesImageMetadataInterface::GetDay() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-.")); int value; try { value = lexical_cast<int>(outputValues[2]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Day"); } return value; } int PleiadesImageMetadataInterface::GetMonth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-.")); int value; try { value = lexical_cast<int>(outputValues[1]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Month"); } return value; } int PleiadesImageMetadataInterface::GetYear() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-.")); int value; try { value = lexical_cast<int>(outputValues[0]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Year"); } return value; } int PleiadesImageMetadataInterface::GetHour() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-.")); int value; try { value = lexical_cast<int>(outputValues[3]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Hour"); } return value; } int PleiadesImageMetadataInterface::GetMinute() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-.")); int value; try { value = lexical_cast<int>(outputValues[4]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Minute"); } return value; } int PleiadesImageMetadataInterface::GetProductionDay() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); int value; try { value = lexical_cast<int>(outputValues[2]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Day"); } return value; } int PleiadesImageMetadataInterface::GetProductionMonth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); int value; try { value = lexical_cast<int>(outputValues[1]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Month"); } return value; } int PleiadesImageMetadataInterface::GetProductionYear() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Year"); int value; try { value = lexical_cast<int>(outputValues[0]); } catch (bad_lexical_cast&) { itkExceptionMacro(<< "Invalid Year"); } return value; } PleiadesImageMetadataInterface::VariableLengthVectorType PleiadesImageMetadataInterface::GetPhysicalBias() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } std::vector<double> outputValues; if (imageKeywordlist.HasKey("support_data.physical_bias")) { std::vector<std::string> outputValuesString; std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.physical_bias"); boost::trim(valueString); boost::split(outputValuesString, valueString, boost::is_any_of(" ")); for (unsigned int i = 0; i < outputValuesString.size(); ++i) { outputValues.push_back(atof(outputValuesString[i].c_str())); } } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // Use BandIndexToWavelengthPosition because values in keywordlist are sorted by wavelength for (unsigned int i = 0; i < outputValues.size(); ++i) { outputValuesVariableLengthVector[i] = outputValues[this->BandIndexToWavelengthPosition(i)]; } return outputValuesVariableLengthVector; } PleiadesImageMetadataInterface::VariableLengthVectorType PleiadesImageMetadataInterface::GetPhysicalGain() const { // We use here tabulate in flight values for physical gain of PHR. Those values evolve // with time and are much more accurate. Values provided by CNES calibration // team. Diference between metadata values and in flight gain can lead to // difference of 10%. // Values: // Ak values for PHR1A are given in the following table : // Dates PA NTDI=13 B0 B1 B2 B3 // From 17/12/2011 to 01/08/2012 11.75 9.52 9.62 10.55 15.73 // From 01/08/2012 to 01/03/2013 11.73 9.45 9.48 10.51 15.71 // From 01/03/2013 11.70 9.38 9.34 10.46 15.69 // For PHR1B in the following table : // Dates PA NTDI=13 B0 B1 B2 B3 // From 01/12/2012 12.04 10.46 10.47 11.32 17.21 std::vector<double> outputValues; const std::string sensorId = this->GetSensorID(); const int nbBands = this->GetNumberOfBands(); if (sensorId == "PHR 1A") { // PHR 1A if ((this->GetYear() < 2012) || (this->GetYear() == 2012 && this->GetMonth() < 8)) { if (nbBands == 1) { outputValues.push_back(11.75); } else { outputValues.push_back(9.52); outputValues.push_back(9.62); outputValues.push_back(10.55); outputValues.push_back(15.73); } } else if ((this->GetYear() == 2012 && this->GetMonth() >= 8) || (this->GetYear() == 2013 && this->GetMonth() < 3)) { if (nbBands == 1) { outputValues.push_back(11.73); } else { outputValues.push_back(9.45); outputValues.push_back(9.48); outputValues.push_back(10.51); outputValues.push_back(15.71); } } else if ((this->GetYear() == 2013 && this->GetMonth() >= 3) || this->GetYear() > 2013) { if (nbBands == 1) { outputValues.push_back(11.7); } else { outputValues.push_back(9.38); outputValues.push_back(9.34); outputValues.push_back(10.46); outputValues.push_back(15.69); } } else { itkExceptionMacro(<< "Invalid metadata, wrong acquisition date"); } } else if (sensorId == "PHR 1B") { // PHR 1B if (this->GetYear() >= 2012) { if (nbBands == 1) { outputValues.push_back(12.04); } else { outputValues.push_back(10.46); outputValues.push_back(10.47); outputValues.push_back(11.32); outputValues.push_back(17.21); } } else { itkExceptionMacro(<< "Invalid metadata, wrong acquisition date"); } } else { itkExceptionMacro(<< "Invalid metadata, bad sensor id"); } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // Use BandIndexToWavelengthPosition because values are tabulated and sorted by wavelength for (unsigned int i = 0; i < outputValues.size(); ++i) { outputValuesVariableLengthVector[i] = outputValues[this->BandIndexToWavelengthPosition(i)]; } otbMsgDevMacro(<< "physical gain " << outputValuesVariableLengthVector); return outputValuesVariableLengthVector; } double PleiadesImageMetadataInterface::GetSatElevation() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.incident_angle")) { return 0; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.incident_angle"); std::istringstream is(valueString); std::vector<double> vecValues = std::vector<double>(std::istream_iterator<double>(is), std::istream_iterator<double>()); // Take the second value (Center value) double value = vecValues[1]; // Convention use in input of atmospheric correction parameters computation is //"90 - satOrientation". Pleiades does not seem to follow this convention so // inverse the formula here to be able to take the angle read in the metadata // as input for 6S value = 90. - value; return value; } double PleiadesImageMetadataInterface::GetSatAzimuth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.scene_orientation")) { return 0; } else if (!imageKeywordlist.HasKey("support_data.along_track_incidence_angle") || !imageKeywordlist.HasKey("support_data.across_track_incidence_angle")) { std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.scene_orientation"); std::istringstream is(valueString); std::vector<double> vecCap = std::vector<double>(std::istream_iterator<double>(is), std::istream_iterator<double>()); // Take the second value (Center value) double cap = vecCap[1]; // return only orientation if across/along track incidence are not available return cap; } else { // Got orientation and incidences angle which allow computing satellite // azimuthal angle // MSD: for the moment take only topCenter value std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.scene_orientation"); std::istringstream is(valueString); std::vector<double> vecCap = std::vector<double>(std::istream_iterator<double>(is), std::istream_iterator<double>()); // Take the second value (Center value) double cap = vecCap[1]; valueString = imageKeywordlist.GetMetadataByKey("support_data.along_track_incidence_angle"); std::istringstream isAlong(valueString); std::vector<double> vecAlong = std::vector<double>(std::istream_iterator<double>(isAlong), std::istream_iterator<double>()); // Take the second value (Center value) double along = vecAlong[1]; valueString = imageKeywordlist.GetMetadataByKey("support_data.across_track_incidence_angle"); std::istringstream isAcross(valueString); std::vector<double> vecAcross = std::vector<double>(std::istream_iterator<double>(isAcross), std::istream_iterator<double>()); // Take the second value (Center value) double ortho = vecAcross[1]; // Compute Satellite azimuthal angle using the azimuthal angle and the along // and across track incidence angle double satAz = (cap - std::atan2(std::tan(ortho * CONST_PI_180), std::tan(along * CONST_PI_180)) * CONST_180_PI); satAz = fmod(satAz, 360); return satAz; } } PleiadesImageMetadataInterface::VariableLengthVectorType PleiadesImageMetadataInterface::GetFirstWavelengths() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } VariableLengthVectorType wavel(1); wavel.Fill(0.); int nbBands = this->GetNumberOfBands(); std::string sensorId = this->GetSensorID(); // Panchromatic case if (nbBands == 1) { wavel.SetSize(1); wavel.Fill(0.430); } else if (nbBands > 1 && nbBands < 5) { wavel.SetSize(4); wavel[0] = 0.430; wavel[1] = 0.430; wavel[2] = 0.430; wavel[3] = 0.430; } else itkExceptionMacro(<< "Invalid number of bands..."); return wavel; } PleiadesImageMetadataInterface::VariableLengthVectorType PleiadesImageMetadataInterface::GetLastWavelengths() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } VariableLengthVectorType wavel(1); wavel.Fill(0.); int nbBands = this->GetNumberOfBands(); // Panchromatic case if (nbBands == 1) { wavel.SetSize(1); wavel.Fill(0.95); } else if (nbBands > 1 && nbBands < 5) { wavel.SetSize(4); wavel[0] = 0.95; wavel[1] = 0.95; wavel[2] = 0.95; wavel[3] = 0.95; } else itkExceptionMacro(<< "Invalid number of bands..."); return wavel; } // TODO MSD need to update this function // Comment this part as relative response // FIXME check if this is coherent with other sensor unsigned int PleiadesImageMetadataInterface::BandIndexToWavelengthPosition(unsigned int i) const { int nbBands = this->GetNumberOfBands(); // Panchromatic case if (nbBands == 1) { return 0; } else { otbMsgDevMacro(<< "Pleiades detected: first file component is red band and third component is blue one"); if (i == 0) return 2; if (i == 2) return 0; } return i; } std::vector<std::string> PleiadesImageMetadataInterface::GetEnhancedBandNames() const { std::vector<std::string> enhBandNames; std::vector<std::string> rawBandNames = this->Superclass::GetBandName(); if (rawBandNames.size()) { for (std::vector<std::string>::iterator it = rawBandNames.begin(); it != rawBandNames.end(); ++it) { // Manage Panchro case if ((rawBandNames.size() == 1) && !(*it).compare("P")) { enhBandNames.push_back("PAN"); break; } else if ((rawBandNames.size() != 1) && !(*it).compare("P")) { /* Launch exception situation not valid*/ itkExceptionMacro(<< "Invalid Metadata, we cannot provide an consistent name to the band"); } // Manage MS case if (!(*it).compare("B0")) { enhBandNames.push_back("Blue"); } else if (!(*it).compare("B1")) { enhBandNames.push_back("Green"); } else if (!(*it).compare("B2")) { enhBandNames.push_back("Red"); } else if (!(*it).compare("B3")) { enhBandNames.push_back("NIR"); } else { enhBandNames.push_back("Unknown"); } } } return enhBandNames; } std::vector<unsigned int> PleiadesImageMetadataInterface::GetDefaultDisplay() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } std::vector<unsigned int> rgb(3); rgb[0] = 0; rgb[1] = 1; rgb[2] = 2; ImageKeywordlistType imageKeywordlist; if (!dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { return rgb; } itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); if (!imageKeywordlist.HasKey("support_data.band_name_list")) { return rgb; } const std::string& rgbOrder = imageKeywordlist.GetMetadataByKey("support_data.band_name_list"); std::vector<std::string> bandList; boost::split(bandList, rgbOrder, boost::is_any_of(" ")); if (bandList[0] == "P") { rgb[1] = 0; rgb[2] = 0; return rgb; } if (bandList.size() >= 3) { for (int i = 0; i < 3; i++) { std::string band = bandList[i]; if (band[0] == 'B') { rgb[i] = lexical_cast<unsigned int>(band.c_str() + 1); } } } return rgb; } PleiadesImageMetadataInterface::WavelengthSpectralBandVectorType PleiadesImageMetadataInterface::GetSpectralSensitivity() const { // TODO tabulate spectral responses WavelengthSpectralBandVectorType wavelengthSpectralBand = InternalWavelengthSpectralBandVectorType::New(); std::list<std::vector<float>> tmpSpectralBandList; const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Pleiades Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } const int nbBands = this->GetNumberOfBands(); const std::string sensorId = this->GetSensorID(); // Panchromatic case if (nbBands == 1) { // if (sensorId.find("PHR") != std::string::npos) if (sensorId == "PHR 1A") { const float pan[209] = { 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0004358f, 0.0008051f, 0.0030464f, 0.0060688f, 0.0130170f, 0.0240166f, 0.0421673f, 0.0718226f, 0.1151660f, 0.1738520f, 0.2442960f, 0.3204090f, 0.3940400f, 0.4552560f, 0.5015220f, 0.5324310f, 0.5537040f, 0.5683830f, 0.5824280f, 0.5967100f, 0.6107110f, 0.6232080f, 0.6335930f, 0.6421600f, 0.6501020f, 0.6570500f, 0.6640260f, 0.6707420f, 0.6765340f, 0.6808170f, 0.6829760f, 0.6834310f, 0.6831800f, 0.6831390f, 0.6846760f, 0.6892820f, 0.6964400f, 0.7073100f, 0.7193370f, 0.7323050f, 0.7449550f, 0.7554270f, 0.7638770f, 0.7715940f, 0.7776340f, 0.7826480f, 0.7871060f, 0.7913600f, 0.7949010f, 0.7974290f, 0.7996850f, 0.8007000f, 0.8003370f, 0.8002560f, 0.8000160f, 0.8012780f, 0.8035920f, 0.8077100f, 0.8136680f, 0.8209800f, 0.8302930f, 0.8390660f, 0.8482460f, 0.8564130f, 0.8634600f, 0.8689680f, 0.8738000f, 0.8767770f, 0.8799960f, 0.8825630f, 0.8849870f, 0.8894330f, 0.8939110f, 0.8994160f, 0.9056300f, 0.9123790f, 0.9188800f, 0.9244770f, 0.9289540f, 0.9338010f, 0.9374110f, 0.9414880f, 0.9449190f, 0.9480210f, 0.9509810f, 0.9532570f, 0.9560420f, 0.9581430f, 0.9600910f, 0.9609580f, 0.9631350f, 0.9649320f, 0.9674470f, 0.9728920f, 0.9774240f, 0.9827830f, 0.9874630f, 0.9926650f, 0.9966400f, 0.9993680f, 0.9999140f, 0.9942900f, 0.9882640f, 0.9810720f, 0.9751580f, 0.9699990f, 0.9659940f, 0.9632210f, 0.9624050f, 0.9621500f, 0.9633410f, 0.9654310f, 0.9671030f, 0.9672570f, 0.9677370f, 0.9653110f, 0.9633140f, 0.9579490f, 0.9533250f, 0.9486410f, 0.9423590f, 0.9358410f, 0.9299340f, 0.9243940f, 0.9190090f, 0.9141220f, 0.9087800f, 0.9039750f, 0.8980690f, 0.8927220f, 0.8870500f, 0.8828150f, 0.8771870f, 0.8734510f, 0.8694140f, 0.8664310f, 0.8660560f, 0.8588170f, 0.8477750f, 0.8331070f, 0.8135860f, 0.7865930f, 0.7489860f, 0.6981680f, 0.6306270f, 0.5506620f, 0.4616840f, 0.3695890f, 0.2823490f, 0.2074510f, 0.1465300f, 0.1010100f, 0.0686868f, 0.0471034f, 0.0324221f, 0.0246752f, 0.0174143f, 0.0126697f, 0.0116629f, 0.0086694f, 0.0081772f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f, 0.0000000f}; // add panchromatic band to the temporary list const std::vector<float> vpan(pan, pan + sizeof(pan) / sizeof(float)); tmpSpectralBandList.push_back(vpan); } else if (sensorId == "PHR 1B") { const float pan[209] = {8.4949016432e-06f, 1.27423524648e-05f, 2.54847049296e-05f, 4.10586912755e-05f, 5.94643115024e-05f, 7.64541147888e-05f, 0.0001047705f, 0.0001628184f, 0.0004077553f, 0.0007560434f, 0.0027948226f, 0.0055783471f, 0.0119863062f, 0.022134882f, 0.0389179761f, 0.0664188043f, 0.1067016279f, 0.1614272001f, 0.2272018077f, 0.2986552571f, 0.367815083f, 0.4258041132f, 0.4697397445f, 0.4991660838f, 0.5193159905f, 0.5332504608f, 0.5467262065f, 0.5603038909f, 0.5736437182f, 0.5855337488f, 0.5956625032f, 0.6041036038f, 0.6120151889f, 0.618774299f, 0.625564557f, 0.6319045853f, 0.6377943837f, 0.6421862479f, 0.6443949223f, 0.6448819633f, 0.644884795f, 0.6451141573f, 0.6468357907f, 0.6513182672f, 0.6590911022f, 0.6691405708f, 0.6811806781f, 0.6937021631f, 0.7056091836f, 0.7157690859f, 0.7250568451f, 0.7323511339f, 0.7384193253f, 0.7438758838f, 0.7492531566f, 0.7536450207f, 0.7580793594f, 0.7610893862f, 0.7639125252f, 0.7652348982f, 0.766172169f, 0.7665969141f, 0.767494542f, 0.7687546191f, 0.7723026564f, 0.7771079391f, 0.7833828397f, 0.7917191699f, 0.8015449394f, 0.8109516272f, 0.8200326771f, 0.8290684208f, 0.8364646485f, 0.8426517685f, 0.8481876127f, 0.8519168746f, 0.8555045547f, 0.8583361886f, 0.8620173126f, 0.8666838452f, 0.8715797402f, 0.8780188757f, 0.8847071949f, 0.8913473763f, 0.898890849f, 0.9045824331f, 0.9105090428f, 0.9154615705f, 0.9207935371f, 0.9253156564f, 0.9289882855f, 0.9328931087f, 0.9369565033f, 0.9400797954f, 0.9441601799f, 0.9469295178f, 0.9503472999f, 0.9521085762f, 0.9542804394f, 0.9574405428f, 0.9607705442f, 0.9663148834f, 0.9720999114f, 0.9788278735f, 0.9845959117f, 0.991221935f, 0.9956874216f, 0.9990882139f, 1.0f, 0.9963273709f, 0.9914682871f, 0.9869688209f, 0.9817019819f, 0.9771458829f, 0.9745974125f, 0.9729012638f, 0.9739319785f, 0.9741924888f, 0.9768712145f, 0.9798246086f, 0.9827723395f, 0.9845732586f, 0.9850772894f, 0.9837266001f, 0.9825967782f, 0.9790232562f, 0.9745945808f, 0.9697411603f, 0.9648141174f, 0.9598389367f, 0.9533346736f, 0.9483566613f, 0.9445481137f, 0.93968903f, 0.9344561706f, 0.9297160154f, 0.9248342786f, 0.9183356789f, 0.9111942982f, 0.9061001889f, 0.9006181457f, 0.8953456434f, 0.8908093659f, 0.8894954878f, 0.8885412272f, 0.8809779331f, 0.8707840511f, 0.8566683562f, 0.8369346997f, 0.8102408871f, 0.7728519933f, 0.718954674f, 0.6528501811f, 0.5710810895f, 0.4795853355f, 0.3846491464f, 0.294773087f, 0.2166449103f, 0.1531319287f, 0.1057054591f, 0.0716799801f, 0.0491432892f, 0.0337757289f, 0.0256986066f, 0.0181762579f, 0.0131968863f, 0.0121562043f, 0.0090201414f, 0.0084156159f, 0.0042799863f, 0.0033130116f, 0.0026688064f, 0.0022115061f, 0.0018292327f, 0.0015290823f, 0.0013634289f, 0.0012147709f, 0.0011015056f, 0.0009939035f, 0.0009188652f, 0.0008523218f, 0.0008225925f, 0.0006965819f, 0.0007220666f, 0.0006682656f, 0.0006470283f, 0.0006144646f, 0.000603138f, 0.0006116329f, 0.0005578319f, 0.0005295155f, 0.0005295155f, 0.0005210206f, 0.0005054466f, 0.0004473982f, 0.0004473953f, 0.0004077553f, 0.0004558931f, 0.0004077553f, 0.0004346558f, 0.0003766073f, 0.0003851022f, 0.0003879338f, 0.0003723599f, 0.0003341328f, 0.0003723599f, 0.0003313012f, 0.0003341328f, 0.0003143114f}; // add panchromatic band to the temporary list const std::vector<float> vpan(pan, pan + sizeof(pan) / sizeof(float)); tmpSpectralBandList.push_back(vpan); } else { itkExceptionMacro(<< "Invalid Pleiades Sensor ID"); } } else if (nbBands > 1 && nbBands < 5) { if (sensorId == "PHR 1A") { // band B0 (blue band) const float b0[209] = { 0.0098681f, 0.0293268f, 0.0877320f, 0.1287040f, 0.1341240f, 0.2457050f, 0.4345520f, 0.5133040f, 0.4710970f, 0.5125880f, 0.6530370f, 0.7707870f, 0.7879420f, 0.7648330f, 0.7718380f, 0.8013290f, 0.8240790f, 0.8352890f, 0.8326150f, 0.8249150f, 0.8168160f, 0.8163380f, 0.8285420f, 0.8623820f, 0.9075060f, 0.9379000f, 0.9505710f, 0.9572260f, 0.9650570f, 0.9632790f, 0.9587260f, 0.9567320f, 0.9646760f, 0.9804620f, 0.9900240f, 0.9838940f, 0.9719110f, 0.9715280f, 0.9574890f, 0.8770130f, 0.7103910f, 0.4943810f, 0.3021990f, 0.1722720f, 0.0943537f, 0.0543895f, 0.0345732f, 0.0261018f, 0.0230010f, 0.0223203f, 0.0210136f, 0.0173172f, 0.0119112f, 0.0072895f, 0.0046311f, 0.0033297f, 0.0025865f, 0.0020232f, 0.0015030f, 0.0010527f, 0.0007044f, 0.0005199f, 0.0004117f, 0.0004097f, 0.0005317f, 0.0009532f, 0.0013521f, 0.0014273f, 0.0009182f, 0.0003440f, 0.0001323f, 0.0000783f, 0.0000626f, 0.0000511f, 0.0000538f, 0.0000533f, 0.0000454f, 0.0000404f, 0.0000315f, 0.0000327f, 0.0000262f, 0.0000303f, 0.0000206f, 0.0000241f, 0.0000241f, 0.0000273f, 0.0000258f, 0.0000208f, 0.0000341f, 0.0000379f, 0.0000393f, 0.0000429f, 0.0000281f, 0.0000277f, 0.0000187f, 0.0000272f, 0.0000245f, 0.0000209f, 0.0000137f, 0.0000171f, 0.0000257f, 0.0000300f, 0.0000330f, 0.0000446f, 0.0000397f, 0.0000399f, 0.0000384f, 0.0000336f, 0.0000307f, 0.0000300f, 0.0000242f, 0.0000224f, 0.0000210f, 0.0000325f, 0.0000690f, 0.0002195f, 0.0005063f, 0.0008373f, 0.0009464f, 0.0007099f, 0.0004910f, 0.0004433f, 0.0006064f, 0.0012019f, 0.0016241f, 0.0016779f, 0.0009733f, 0.0003606f, 0.0001659f, 0.0000864f, 0.0000564f, 0.0000562f, 0.0000590f, 0.0000458f, 0.0000382f, 0.0000586f, 0.0000685f, 0.0000474f, 0.0000872f, 0.0000628f, 0.0000948f, 0.0001015f, 0.0001564f, 0.0002379f, 0.0003493f, 0.0005409f, 0.0007229f, 0.0007896f, 0.0007188f, 0.0005204f, 0.0003939f, 0.0003128f, 0.0002699f, 0.0002605f, 0.0002378f, 0.0002286f, 0.0002406f, 0.0002741f, 0.0003203f, 0.0003812f, 0.0004904f, 0.0006077f, 0.0008210f, 0.0011791f, 0.0018150f, 0.0030817f, 0.0055589f, 0.0103652f, 0.0166309f, 0.0211503f, 0.0216246f, 0.0176910f, 0.0136927f, 0.0107136f, 0.0089555f, 0.0079790f, 0.0079189f, 0.0080456f, 0.0088920f, 0.0102062f, 0.0126157f, 0.0162251f, 0.0221306f, 0.0308295f, 0.0411980f, 0.0498232f, 0.0531265f, 0.0484487f, 0.0391122f, 0.0291405f, 0.0212633f, 0.0162146f, 0.0128925f, 0.0108169f, 0.0094115f, 0.0084386f, 0.0077249f, 0.0074231f, 0.0072603f, 0.0073459f, 0.0074214f, 0.0076433f, 0.0077788f, 0.0078151f, 0.0077003f, 0.0072256f, 0.0065903f, 0.0057120f, 0.0048136f}; // B1 green band const float b1[209] = { 0.0000144f, 0.0000143f, 0.0000259f, 0.0000189f, 0.0000132f, 0.0000179f, 0.0000224f, 0.0000179f, 0.0000124f, 0.0000202f, 0.0000276f, 0.0000292f, 0.0000420f, 0.0000366f, 0.0000261f, 0.0000247f, 0.0000445f, 0.0000902f, 0.0001144f, 0.0000823f, 0.0000778f, 0.0001923f, 0.0003401f, 0.0004085f, 0.0004936f, 0.0007849f, 0.0045979f, 0.0085122f, 0.0143014f, 0.0243310f, 0.0480572f, 0.1097360f, 0.2353890f, 0.4328370f, 0.6491340f, 0.8095770f, 0.8847680f, 0.9066640f, 0.9131150f, 0.9186700f, 0.9273270f, 0.9405210f, 0.9512930f, 0.9587500f, 0.9667360f, 0.9709750f, 0.9728630f, 0.9769560f, 0.9850710f, 0.9892500f, 0.9865960f, 0.9743300f, 0.9575190f, 0.9435550f, 0.9439310f, 0.9571350f, 0.9712530f, 0.9761580f, 0.9619590f, 0.9244890f, 0.8734580f, 0.8349840f, 0.8166740f, 0.8015960f, 0.7435910f, 0.6160350f, 0.4321320f, 0.2544540f, 0.1360870f, 0.0769553f, 0.0479321f, 0.0342014f, 0.0266703f, 0.0212632f, 0.0160541f, 0.0106967f, 0.0060543f, 0.0030797f, 0.0015416f, 0.0008333f, 0.0004706f, 0.0002918f, 0.0001917f, 0.0001472f, 0.0001063f, 0.0000912f, 0.0000589f, 0.0000552f, 0.0000752f, 0.0000884f, 0.0000985f, 0.0001125f, 0.0001368f, 0.0001947f, 0.0002284f, 0.0002088f, 0.0001498f, 0.0000637f, 0.0000307f, 0.0000283f, 0.0000311f, 0.0000331f, 0.0000215f, 0.0000236f, 0.0000205f, 0.0000186f, 0.0000233f, 0.0000233f, 0.0000198f, 0.0000195f, 0.0000161f, 0.0000308f, 0.0000464f, 0.0000290f, 0.0000264f, 0.0000233f, 0.0000395f, 0.0001113f, 0.0001903f, 0.0002290f, 0.0002229f, 0.0001322f, 0.0000548f, 0.0000608f, 0.0000414f, 0.0000382f, 0.0000381f, 0.0000269f, 0.0000233f, 0.0000198f, 0.0000208f, 0.0000302f, 0.0000419f, 0.0000305f, 0.0000340f, 0.0000334f, 0.0000362f, 0.0000282f, 0.0000337f, 0.0000330f, 0.0000424f, 0.0000420f, 0.0000470f, 0.0000417f, 0.0000233f, 0.0000439f, 0.0000503f, 0.0000446f, 0.0000428f, 0.0000597f, 0.0000671f, 0.0001142f, 0.0001780f, 0.0003546f, 0.0009610f, 0.0041260f, 0.0066679f, 0.0078563f, 0.0068645f, 0.0029441f, 0.0011320f, 0.0007028f, 0.0005471f, 0.0004967f, 0.0004929f, 0.0005351f, 0.0006223f, 0.0007957f, 0.0010708f, 0.0016699f, 0.0030334f, 0.0054959f, 0.0091390f, 0.0125045f, 0.0144212f, 0.0141099f, 0.0117418f, 0.0089824f, 0.0067916f, 0.0056849f, 0.0051998f, 0.0053640f, 0.0060350f, 0.0067668f, 0.0083174f, 0.0106521f, 0.0139110f, 0.0183736f, 0.0231289f, 0.0272661f, 0.0298126f, 0.0300318f, 0.0286507f, 0.0266172f, 0.0247529f, 0.0236974f, 0.0232734f, 0.0236733f, 0.0245808f, 0.0257173f, 0.0267721f, 0.0267455f, 0.0254447f, 0.0227056f, 0.0188513f, 0.0147988f, 0.0109864f, 0.0079795f, 0.0057516f}; // B2 red band const float b2[209] = { 0.0097386f, 0.0035306f, 0.0035374f, 0.0114418f, 0.0266686f, 0.0373494f, 0.0904431f, 0.0907580f, 0.0399312f, 0.0208748f, 0.0080694f, 0.0027002f, 0.0011241f, 0.0006460f, 0.0005029f, 0.0006051f, 0.0009979f, 0.0019446f, 0.0014554f, 0.0006090f, 0.0003230f, 0.0002503f, 0.0002538f, 0.0003360f, 0.0005377f, 0.0007773f, 0.0004895f, 0.0002045f, 0.0000875f, 0.0000594f, 0.0000217f, 0.0000290f, 0.0000297f, 0.0000408f, 0.0000456f, 0.0000447f, 0.0000322f, 0.0000222f, 0.0000147f, 0.0000095f, 0.0000072f, 0.0000113f, 0.0000313f, 0.0000123f, 0.0000122f, 0.0000280f, 0.0000180f, 0.0000261f, 0.0000138f, 0.0000392f, 0.0000517f, 0.0000695f, 0.0000797f, 0.0000785f, 0.0001004f, 0.0001170f, 0.0001483f, 0.0001837f, 0.0002110f, 0.0002973f, 0.0004162f, 0.0006371f, 0.0010012f, 0.0032888f, 0.0100109f, 0.0181837f, 0.0330510f, 0.0624784f, 0.1183670f, 0.2218740f, 0.3756820f, 0.5574830f, 0.7342220f, 0.8636840f, 0.9319920f, 0.9527010f, 0.9620090f, 0.9527340f, 0.9437220f, 0.9456300f, 0.9562330f, 0.9693120f, 0.9839640f, 0.9949160f, 0.9992700f, 0.9993300f, 0.9963430f, 0.9944130f, 0.9883050f, 0.9857580f, 0.9807560f, 0.9683790f, 0.9544700f, 0.9371750f, 0.9170350f, 0.8922820f, 0.8662710f, 0.8442750f, 0.8220420f, 0.7888070f, 0.7372920f, 0.6625080f, 0.5662120f, 0.4493120f, 0.3260000f, 0.2194040f, 0.1416500f, 0.0925669f, 0.0619437f, 0.0456444f, 0.0355683f, 0.0310879f, 0.0295168f, 0.0233351f, 0.0189628f, 0.0158627f, 0.0132266f, 0.0107473f, 0.0083969f, 0.0063847f, 0.0046601f, 0.0033814f, 0.0024167f, 0.0017478f, 0.0012949f, 0.0009939f, 0.0007442f, 0.0006312f, 0.0005142f, 0.0004354f, 0.0003549f, 0.0003156f, 0.0003079f, 0.0002906f, 0.0002867f, 0.0002751f, 0.0003048f, 0.0003010f, 0.0003342f, 0.0004310f, 0.0004955f, 0.0005488f, 0.0005838f, 0.0006687f, 0.0006968f, 0.0006650f, 0.0005866f, 0.0004688f, 0.0004086f, 0.0003611f, 0.0002404f, 0.0002609f, 0.0002476f, 0.0002133f, 0.0002098f, 0.0001916f, 0.0001642f, 0.0001799f, 0.0002180f, 0.0002003f, 0.0002030f, 0.0002348f, 0.0002735f, 0.0002652f, 0.0002944f, 0.0004666f, 0.0004882f, 0.0006642f, 0.0007798f, 0.0010588f, 0.0014008f, 0.0019011f, 0.0024917f, 0.0034379f, 0.0042182f, 0.0053618f, 0.0062814f, 0.0068774f, 0.0071141f, 0.0070399f, 0.0065876f, 0.0067873f, 0.0066877f, 0.0068572f, 0.0070486f, 0.0073911f, 0.0081201f, 0.0087391f, 0.0096581f, 0.0106625f, 0.0120129f, 0.0137222f, 0.0159817f, 0.0180896f, 0.0206562f, 0.0236408f, 0.0269627f, 0.0310497f, 0.0353146f, 0.0398729f, 0.0438795f, 0.0462377f, 0.0454916f, 0.0408754f, 0.0333175f, 0.0251186f, 0.0179089f, 0.0125129f, 0.0086117f}; // B3 nir band const float b3[209] = { 0.0024163f, 0.0017305f, 0.0020803f, 0.0020499f, 0.0012660f, 0.0007361f, 0.0006198f, 0.0006344f, 0.0007721f, 0.0011837f, 0.0020819f, 0.0023991f, 0.0013377f, 0.0006328f, 0.0003544f, 0.0002890f, 0.0002498f, 0.0002541f, 0.0003346f, 0.0005048f, 0.0008684f, 0.0009871f, 0.0006587f, 0.0003833f, 0.0002606f, 0.0002356f, 0.0002364f, 0.0002791f, 0.0003613f, 0.0005575f, 0.0007414f, 0.0007413f, 0.0005768f, 0.0004230f, 0.0003206f, 0.0003044f, 0.0003019f, 0.0003201f, 0.0003813f, 0.0004630f, 0.0005930f, 0.0007080f, 0.0008577f, 0.0009017f, 0.0008813f, 0.0007801f, 0.0006583f, 0.0005863f, 0.0005224f, 0.0005506f, 0.0006403f, 0.0008293f, 0.0013444f, 0.0023942f, 0.0027274f, 0.0014330f, 0.0006388f, 0.0003596f, 0.0002416f, 0.0001718f, 0.0001566f, 0.0001642f, 0.0001892f, 0.0002351f, 0.0003227f, 0.0006734f, 0.0014311f, 0.0013325f, 0.0005796f, 0.0002424f, 0.0001263f, 0.0001022f, 0.0000446f, 0.0000652f, 0.0000544f, 0.0000573f, 0.0000518f, 0.0000504f, 0.0000649f, 0.0000723f, 0.0000833f, 0.0000739f, 0.0000691f, 0.0001382f, 0.0001692f, 0.0002240f, 0.0002296f, 0.0001553f, 0.0001492f, 0.0001121f, 0.0001058f, 0.0001068f, 0.0001012f, 0.0000864f, 0.0000533f, 0.0000354f, 0.0000440f, 0.0000371f, 0.0000691f, 0.0000769f, 0.0000791f, 0.0001333f, 0.0001244f, 0.0002048f, 0.0002455f, 0.0002721f, 0.0003812f, 0.0004568f, 0.0006255f, 0.0008185f, 0.0009733f, 0.0012281f, 0.0013528f, 0.0015758f, 0.0017458f, 0.0019104f, 0.0020863f, 0.0023053f, 0.0025241f, 0.0037234f, 0.0044186f, 0.0053574f, 0.0066118f, 0.0083509f, 0.0107509f, 0.0150393f, 0.0212756f, 0.0292566f, 0.0414246f, 0.0586633f, 0.0834879f, 0.1190380f, 0.1671850f, 0.2326370f, 0.3124060f, 0.4070470f, 0.5091930f, 0.6148270f, 0.7140870f, 0.8017550f, 0.8714840f, 0.9241260f, 0.9587210f, 0.9782990f, 0.9882040f, 0.9922940f, 0.9902030f, 0.9854020f, 0.9777560f, 0.9660200f, 0.9532070f, 0.9421250f, 0.9303560f, 0.9241490f, 0.9212220f, 0.9203820f, 0.9217020f, 0.9227420f, 0.9230000f, 0.9237670f, 0.9243070f, 0.9206520f, 0.9154840f, 0.9090910f, 0.9003380f, 0.8905620f, 0.8776420f, 0.8668600f, 0.8537290f, 0.8428590f, 0.8305310f, 0.8195740f, 0.8069090f, 0.7921080f, 0.7791670f, 0.7660510f, 0.7521190f, 0.7375270f, 0.7217320f, 0.7043220f, 0.6853170f, 0.6642500f, 0.6413850f, 0.6173030f, 0.5919540f, 0.5672310f, 0.5430130f, 0.5184560f, 0.4957540f, 0.4734340f, 0.4528220f, 0.4332270f, 0.4131920f, 0.3919120f, 0.3659660f, 0.3325420f, 0.2917680f, 0.2453910f, 0.1962540f, 0.1486850f, 0.1068860f, 0.0738260f, 0.0491777f, 0.0327991f, 0.0215831f, 0.0145386f, 0.0103219f, 0.0076144f, 0.0061346f}; // Add multispectral bands to the temporary list const std::vector<float> vb0(b0, b0 + sizeof(b0) / sizeof(float)); const std::vector<float> vb1(b1, b1 + sizeof(b1) / sizeof(float)); const std::vector<float> vb2(b2, b2 + sizeof(b2) / sizeof(float)); const std::vector<float> vb3(b3, b3 + sizeof(b3) / sizeof(float)); // For Pleiades MS image the order of band in 1A product is: B2 B1 B0 B3 //(BandIndexToWavelength method could be used here) tmpSpectralBandList.push_back(vb2); tmpSpectralBandList.push_back(vb1); tmpSpectralBandList.push_back(vb0); tmpSpectralBandList.push_back(vb3); } else if (sensorId == "PHR 1B") { // B0 blue band const float b0[209] = {0.0016025229f, 0.0013381709f, 0.0043437933f, 0.0110724631f, 0.0176270388f, 0.0233671533f, 0.057403285f, 0.1345548468f, 0.2237631463f, 0.3085427458f, 0.4615565735f, 0.650820526f, 0.755369094f, 0.7477203647f, 0.7168186424f, 0.7185381794f, 0.7566962056f, 0.8101088802f, 0.842166474f, 0.8234370764f, 0.775247228f, 0.7527006008f, 0.7802203291f, 0.8199266521f, 0.8516631705f, 0.8602751259f, 0.858684019f, 0.8658261626f, 0.8828217532f, 0.9040412689f, 0.9196954778f, 0.9325955734f, 0.9502333148f, 0.9757980507f, 0.9949769539f, 1.0f, 0.995062574f, 0.9806284516f, 0.9417497895f, 0.8436220158f, 0.6711424576f, 0.4633403256f, 0.2888651055f, 0.1670783567f, 0.0901800876f, 0.0505194286f, 0.0314882201f, 0.0238137335f, 0.0213108438f, 0.0206298072f, 0.0195599127f, 0.0167943833f, 0.0113582202f, 0.0066519685f, 0.004144013f, 0.0030298814f, 0.0024159139f, 0.0019903178f, 0.0015682749f, 0.0011355438f, 0.0012529075f, 0.0008355166f, 0.0005508227f, 0.000419896f, 0.0003617449f, 0.000377798f, 0.0005322716f, 0.0011091514f, 0.0019870999f, 0.0012200722f, 0.0003753015f, 0.0001469798f, 7.49175906503e-05f, 5.2799e-05f, 5.56530673402e-05f, 5.74373902992e-05f, 5.63665682035e-05f, 3.78155457568e-05f, 3.49615423035e-05f, 2.06915250367e-05f, 1.35565164034e-05f, 1.99783095738e-05f, 4.281e-06f, 1.10591920316e-05f, 1.21295146767e-05f, 1.14159424633e-05f, 9.27551122337e-06f, 1.1773e-05f, 1.92645233101e-05f, 8.919e-06f, 1.1416e-05f, 1.71237353197e-05f, 4.99450604335e-06f, 8.56172495969e-06f, 2.4259e-05f, 3.85286898697e-05f, 1.2843e-05f, 2.35456711903e-05f, 9.989e-06f, 1.14162992137e-05f, 2.06915250367e-05f, 1.39132668351e-05f, 5.708e-06f, 2.854e-06f, 8.562e-06f, 1.24862651084e-05f, 8.562e-06f, 9.27565392354e-06f, 6.42150777002e-06f, 1.1773e-05f, 5.708e-06f, 1.35566591036e-05f, 1.7124e-05f, 7.13522268362e-06f, 9.989e-06f, 2.71133895572e-05f, 6.35015768369e-05f, 0.0002194051f, 0.0007613054f, 0.0011194829f, 0.0007541704f, 0.0004084771f, 0.0003546099f, 0.0004063402f, 0.0006792528f, 0.0016292935f, 0.0024002169f, 0.0010317222f, 0.0003481884f, 0.000165889f, 8.2766100147e-05f, 9.70361174137e-05f, 4.63775561168e-05f, 2.63994605933e-05f, 3.21075388501e-05f, 4.1026442342e-05f, 1.5697e-05f, 8.9192602423e-06f, 4.70910569802e-05f, 7.88411318978e-05f, 2.21185267634e-05f, 5.35134923013e-05f, 8.2766100147e-05f, 0.0001052421f, 0.0001833697f, 0.00026043f, 0.000441657f, 0.000710293f, 0.000864763f, 0.0007370464f, 0.0005515362f, 0.000394566f, 0.0002811193f, 0.0002340283f, 0.0002247528f, 0.0001922885f, 0.0002197583f, 0.0002340276f, 0.0002454443f, 0.0002454436f, 0.0002782653f, 0.000350685f, 0.000431668f, 0.0005326263f, 0.0006885283f, 0.0010277909f, 0.0015625669f, 0.0026085734f, 0.0045749675f, 0.0090618891f, 0.0171625498f, 0.0237927565f, 0.021523467f, 0.0159138519f, 0.011956134f, 0.0094824265f, 0.007869201f, 0.0072241962f, 0.0072420338f, 0.0075677469f, 0.0083793541f, 0.0098637927f, 0.0122586583f, 0.0162673916f, 0.0226015668f, 0.0320271273f, 0.0444304123f, 0.0546690783f, 0.0564243618f, 0.048004124f, 0.0357991923f, 0.0258336544f, 0.0188870814f, 0.0144386889f, 0.0116792956f, 0.0099112405f, 0.008646917f, 0.0078099805f, 0.0072270502f, 0.006995876f, 0.0069230989f, 0.0069141801f, 0.0070208485f, 0.0072527363f, 0.0073726044f, 0.0075049588f, 0.007470354f, 0.0070672332f, 0.0063679952f}; // B1 green band const float b1[209] = {3.2793605247e-06f, 3.2793605247e-06f, 4.919e-06f, 6.5587210494e-06f, 6.5587210494e-06f, 2.86944045911e-06f, 6.5587210494e-06f, 5.73885632302e-06f, 4.09920065587e-06f, 2.86943226071e-06f, 1.47571223611e-05f, 2.29553597049e-05f, 1.06579217053e-05f, 1.27075220332e-05f, 2.21356835417e-05f, 1.8856323017e-05f, 9.01824144292e-05f, 0.0001151875f, 0.0001123181f, 0.0001893831f, 0.000323017f, 0.0004849346f, 0.0006238983f, 0.0008153327f, 0.0015208034f, 0.0041299447f, 0.009953679f, 0.0196421398f, 0.0325476532f, 0.0567927854f, 0.1237909408f, 0.2859094077f, 0.5289756098f, 0.7716253331f, 0.8838040582f, 0.9079565485f, 0.9131461365f, 0.913728223f, 0.9224841156f, 0.9367083419f, 0.9497601968f, 0.9544988727f, 0.9585816766f, 0.9642057799f, 0.9705267473f, 0.9722648084f, 0.967517934f, 0.9589096126f, 0.9524492724f, 0.9524656692f, 0.9560483706f, 0.95517934f, 0.948989547f, 0.9471449067f, 0.9544496823f, 0.9710596434f, 0.9898175856f, 1.0f, 0.9953597049f, 0.9698216848f, 0.9253043656f, 0.8633244517f, 0.7948284485f, 0.7238967001f, 0.6453265013f, 0.5438524288f, 0.4170280795f, 0.2766706292f, 0.1575273622f, 0.0856068867f, 0.049225661f, 0.0327237549f, 0.0237934003f, 0.0181966796f, 0.0140618979f, 0.0099658947f, 0.0058454601f, 0.0030383275f, 0.0015355606f, 0.0008386965f, 0.0004878049f, 0.0003115409f, 0.0002074196f, 0.0001381439f, 9.26419348227e-05f, 7.00964131994e-05f, 6.39475302316e-05f, 5.41093666735e-05f, 4.0992e-05f, 7.00968231195e-05f, 4.75507276081e-05f, 4.71408895265e-05f, 6.23078499693e-05f, 6.72277925804e-05f, 0.0001483911f, 0.0002512826f, 0.0002992416f, 0.0002303743f, 0.0001270752f, 6.72265628203e-05f, 3.11539249846e-05f, 3.15638450502e-05f, 1.72166427547e-05f, 6.5587210494e-06f, 5.73888091822e-06f, 1.76265628203e-05f, 1.06579217053e-05f, 1.72168067227e-05f, 1.14777618364e-05f, 2.86946505431e-06f, 3.2793605247e-06f, 2.86941586391e-06f, 1.393728223e-05f, 1.27072760812e-05f, 1.72166427547e-05f, 9.83840951015e-06f, 7.37856118057e-06f, 2.41853658537e-05f, 3.2793605247e-05f, 0.0001295372f, 0.000277106f, 0.0001893831f, 0.0001237959f, 2.4185e-05f, 7.37856118057e-06f, 7.37870875179e-06f, 4.09920065587e-06f, 1.0248e-05f, 9.83808157409e-06f, 3.2793605247e-06f, 1.5577e-05f, 2.29556056569e-05f, 7.37856118057e-06f, 1.02477556876e-05f, 9.01824144292e-06f, 6.96851813896e-06f, 1.72166427547e-05f, 2.29553597049e-05f, 2.45952039352e-06f, 2.1315e-05f, 9.83808157409e-06f, 1.1887763886e-05f, 3.44332855093e-05f, 9.01856937897e-06f, 1.80364828858e-05f, 1.72165607706e-05f, 1.8856323017e-05f, 1.8037e-05f, 2.86944045911e-05f, 2.86944865751e-05f, 2.0496e-05f, 4.34515269522e-05f, 2.95142447223e-05f, 5.28796884608e-05f, 9.34617749539e-05f, 0.0001336339f, 0.000277106f, 0.0007050527f, 0.0031850789f, 0.0141905308f, 0.0083394138f, 0.0022443452f, 0.0009182209f, 0.000571841f, 0.0004369748f, 0.0004029514f, 0.0004181185f, 0.000445174f, 0.0005173191f, 0.0006021734f, 0.0007575323f, 0.0011108916f, 0.0019381021f, 0.0036905349f, 0.0063570404f, 0.0102714491f, 0.013107604f, 0.0132605042f, 0.0111153925f, 0.0083664685f, 0.0065644599f, 0.0056847797f, 0.0053797909f, 0.0056228653f, 0.0062004509f, 0.007239172f, 0.0089198606f, 0.0115101455f, 0.0149415864f, 0.0192686206f, 0.0234785817f, 0.0264402542f, 0.0270489854f, 0.0255453986f, 0.0233974175f, 0.0213945481f, 0.0199442509f, 0.0192531256f, 0.0190744005f, 0.0196892806f, 0.0206935848f, 0.0220106579f, 0.0232301701f, 0.0237573273f, 0.0229858578f, 0.0206595614f, 0.0172248412f, 0.01329215f, 0.0097815126f}; // B2 red band const float b2[209] = {0.0004536879f, 0.0008531472f, 0.000520901f, 0.0011945588f, 0.0051417966f, 0.0080033148f, 0.0066930427f, 0.0108594102f, 0.0246908583f, 0.0653593224f, 0.1225423328f, 0.0570092494f, 0.0213752702f, 0.0127972076f, 0.006277544f, 0.0023536016f, 0.0009409824f, 0.0005174639f, 0.0003742544f, 0.0003818922f, 0.0005155545f, 0.0008462731f, 0.0010127781f, 0.0006431042f, 0.0003513408f, 0.0002512851f, 0.000223025f, 0.000251667f, 0.0003551597f, 0.0004998969f, 0.0005262475f, 0.0003864772f, 0.0002528126f, 0.0001626868f, 0.0001069298f, 8.78352058781e-05f, 7.02681647025e-05f, 5.84297356542e-05f, 5.49924767237e-05f, 4.81185698901e-05f, 3.66616511491e-05f, 3.20791738908e-05f, 1.90946099735e-05f, 1.79493916457e-05f, 3.74254355481e-05f, 2.40590558097e-05f, 3.43702979523e-05f, 1.48934902656e-05f, 6.87405959046e-06f, 7.256e-06f, 3.8189219947e-06f, 2.29135319682e-06f, 9.16541278728e-06f, 2.94056993592e-05f, 2.36773163671e-05f, 2.90238071597e-05f, 3.8953e-05f, 4.5063e-05f, 6.95043803035e-05f, 8.13422747027e-05f, 0.0001038747f, 0.0001229693f, 0.0001351898f, 0.0001535207f, 0.0001833083f, 0.0002214967f, 0.0007454536f, 0.0012442124f, 0.0021416515f, 0.0038193268f, 0.0068045552f, 0.0123329031f, 0.0221780076f, 0.0413324983f, 0.0780709861f, 0.151934284f, 0.277674582f, 0.4510376011f, 0.6291322645f, 0.7625485958f, 0.8329450763f, 0.8579055504f, 0.8658870974f, 0.8692630244f, 0.8752205427f, 0.8857760431f, 0.9005934605f, 0.9174883714f, 0.9348797421f, 0.947810612f, 0.9569531113f, 0.9623301534f, 0.9647666257f, 0.9624294454f, 0.9613066823f, 0.9620246397f, 0.9699145325f, 0.9811574389f, 0.9933932649f, 1.0f, 0.9809512171f, 0.9522634751f, 0.9131729895f, 0.8694005056f, 0.8252079403f, 0.7830470415f, 0.7361270021f, 0.6734890435f, 0.5877527172f, 0.4804914189f, 0.3630068664f, 0.2523031919f, 0.1626028245f, 0.102221085f, 0.0641273381f, 0.0419155713f, 0.0284639532f, 0.0204548336f, 0.0153696335f, 0.0121174395f, 0.0098810788f, 0.0083168483f, 0.0071016673f, 0.0060949919f, 0.0051723479f, 0.0043142285f, 0.0034950774f, 0.0027713917f, 0.0035890229f, 0.0030310784f, 0.0023173219f, 0.001784208f, 0.0013312762f, 0.0010207978f, 0.0007897531f, 0.0006385253f, 0.0005079166f, 0.0004120624f, 0.0003788371f, 0.0003593606f, 0.0002978759f, 0.0002787813f, 0.0002810727f, 0.0002623607f, 0.0002856554f, 0.0002948208f, 0.0002757262f, 0.0003158256f, 0.0003750181f, 0.0004296295f, 0.0005186096f, 0.0005747478f, 0.0006194291f, 0.0006503624f, 0.0006515081f, 0.0006041535f, 0.0005369404f, 0.0004643817f, 0.0003765457f, 0.0003215532f, 0.0002841278f, 0.0002539583f, 0.000226844f, 0.0002226432f, 0.0001672688f, 0.0001978194f, 0.0002207337f, 0.000208895f, 0.0002329542f, 0.0002054572f, 0.0001871272f, 0.0002505213f, 0.0002932932f, 0.0002635079f, 0.0002589229f, 0.000449106f, 0.0005361766f, 0.000566728f, 0.0008210682f, 0.0009856638f, 0.0013075989f, 0.0017612792f, 0.0024028657f, 0.0032682258f, 0.0043635003f, 0.0056615366f, 0.0068900991f, 0.0078222979f, 0.0083298327f, 0.0084363806f, 0.0081854774f, 0.0081381228f, 0.0080006416f, 0.0077676873f, 0.0077844906f, 0.0079983502f, 0.0081518709f, 0.008505885f, 0.008792686f, 0.0093120594f, 0.009752763f, 0.0101358009f, 0.0103874678f, 0.0104061805f, 0.0101713168f, 0.009522482f, 0.008608614f, 0.0073373101f, 0.0059842508f}; // B3 nir band const float b3[209] = {0.0001962709f, 0.0007612586f, 0.0003823311f, 0.0005128001f, 0.0016870217f, 0.0026649725f, 0.0012252747f, 0.0007391367f, 0.0007408374f, 0.0007538843f, 0.0007760073f, 0.0009904326f, 0.0015486111f, 0.0021799679f, 0.0019876678f, 0.001044887f, 0.0004923789f, 0.0002830611f, 0.0002144231f, 0.0001957036f, 0.0002132886f, 0.0002819266f, 0.000417501f, 0.0006069659f, 0.0006410002f, 0.000437355f, 0.0002654762f, 0.0001905983f, 0.0001622354f, 0.0001707443f, 0.0001849257f, 0.0002461883f, 0.0003834656f, 0.0005627165f, 0.0006784391f, 0.0006143403f, 0.0004844373f, 0.0003880048f, 0.0003596408f, 0.000353401f, 0.0003970798f, 0.0004623154f, 0.0005513736f, 0.0006410013f, 0.0007306268f, 0.0007572878f, 0.0007669312f, 0.0007192805f, 0.0006364621f, 0.0005706603f, 0.0005286833f, 0.0004878409f, 0.0004764957f, 0.0005519409f, 0.0007181471f, 0.0012241402f, 0.0022656237f, 0.0028788283f, 0.00204099f, 0.0008389819f, 0.0003789275f, 0.0002252021f, 0.0001395452f, 0.0001242292f, 9.98371972976e-05f, 9.70007998321e-05f, 0.0001043753f, 0.0001242292f, 0.0001724461f, 0.000286467f, 0.0005275488f, 0.0008208217f, 0.0006602869f, 0.0003221996f, 0.000167908f, 0.0001032404f, 6.80708163393e-05f, 5.72929370855e-05f, 4.76495714375e-05f, 3.23336377612e-05f, 3.63044353809e-05f, 4.14097466064e-05f, 4.4246e-05f, 3.91404924924e-05f, 5.78601938884e-05f, 6.35326484653e-05f, 6.2398248311e-05f, 9.01938316495e-05f, 0.0001009717f, 0.0001525921f, 0.0001917328f, 0.0001968381f, 0.0001860602f, 0.0001429487f, 0.0001361416f, 9.47317726208e-05f, 8.96265748467e-05f, 8.79249178896e-05f, 7.9416e-05f, 7.54452682274e-05f, 7.60124115788e-05f, 8.50885204241e-05f, 9.41646292693e-05f, 8.22522364099e-05f, 8.1685e-05f, 0.0001066443f, 0.000121393f, 0.0001350071f, 0.0001690425f, 0.0002036441f, 0.0002507275f, 0.0003187972f, 0.0003970798f, 0.000508261f, 0.0006330586f, 0.000795859f, 0.0009688746f, 0.0011538003f, 0.0013523402f, 0.0015542836f, 0.0017562271f, 0.0019888024f, 0.002250875f, 0.0025345034f, 0.0029032203f, 0.0052357916f, 0.0064009258f, 0.0080125023f, 0.0101470897f, 0.0131093047f, 0.017134559f, 0.0229045817f, 0.030977894f, 0.0426621362f, 0.0591898438f, 0.0835072354f, 0.1178884433f, 0.1663775548f, 0.2311140356f, 0.3159359454f, 0.417216244f, 0.528495011f, 0.6409593447f, 0.7472394448f, 0.8385519068f, 0.9088123344f, 0.9593662607f, 0.988113701f, 1.0f, 0.9992058405f, 0.9896418908f, 0.9676958596f, 0.9514360106f, 0.9374939729f, 0.9254715322f, 0.9152234708f, 0.9087828371f, 0.9026076795f, 0.8966832495f, 0.8924832801f, 0.8854912728f, 0.8776551873f, 0.8676385667f, 0.8568958573f, 0.8474408209f, 0.8360480353f, 0.8236977202f, 0.8130435029f, 0.8016268925f, 0.7921616455f, 0.7827951012f, 0.7769353384f, 0.7714647138f, 0.7631453255f, 0.7543403654f, 0.7452370283f, 0.734920896f, 0.7255123747f, 0.714614237f, 0.7030887133f, 0.6919477897f, 0.6816475407f, 0.6705202312f, 0.6595358705f, 0.6475962493f, 0.6291853625f, 0.611093274f, 0.5934323007f, 0.5760594939f, 0.5599936467f, 0.5448751184f, 0.5306142824f, 0.5154832744f, 0.4976759489f, 0.4734098374f, 0.4387697334f, 0.3934220901f, 0.3367690187f, 0.2742732022f, 0.2114336281f, 0.1535541475f, 0.1063407965f, 0.0704419498f, 0.0459120639f, 0.0295347927f, 0.0192753862f, 0.0126804586f, 0.0084623824f, 0.0057690017f}; // Add multispectral bands to the temporary list const std::vector<float> vb0(b0, b0 + sizeof(b0) / sizeof(float)); const std::vector<float> vb1(b1, b1 + sizeof(b1) / sizeof(float)); const std::vector<float> vb2(b2, b2 + sizeof(b2) / sizeof(float)); const std::vector<float> vb3(b3, b3 + sizeof(b3) / sizeof(float)); // For Pleiades MS image the order of band in 1A product is: B2 B1 B0 B3 //(BandIndexToWavelength method could be used here) tmpSpectralBandList.push_back(vb2); tmpSpectralBandList.push_back(vb1); tmpSpectralBandList.push_back(vb0); tmpSpectralBandList.push_back(vb3); } else { itkExceptionMacro(<< "Invalid Pleiades Sensor ID"); } } else { itkExceptionMacro(<< "Invalid number of bands..."); } unsigned int j = 0; for (std::list<std::vector<float>>::const_iterator it = tmpSpectralBandList.begin(); it != tmpSpectralBandList.end(); ++it) { wavelengthSpectralBand->PushBack(FilterFunctionValues::New()); wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(*it); wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(0.430); wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(0.950); wavelengthSpectralBand->GetNthElement(j)->SetUserStep(0.0025); ++j; } return wavelengthSpectralBand; } void PleiadesImageMetadataInterface::Parse(const MetadataSupplierInterface *mds) { assert(mds); Fetch(MDStr::SensorID, *mds, "IMD/Dataset_Sources.Source_Identification.Strip_Source.MISSION"); if (boost::starts_with(m_Imd[MDStr::SensorID], "PHR")) { m_Imd.Add(MDStr::Mission, "Pléiades"); } else { otbGenericExceptionMacro(MissingMetadataException,<<"Sensor ID doesn't start with PHR : '"<<m_Imd[MDStr::SensorID]<<"'") } Fetch(MDStr::GeometricLevel, *mds, "IMD/Geoposition.Raster_CRS.RASTER_GEOMETRY"); // get radiometric metadata // fill RPC model if (m_Imd[MDStr::GeometricLevel] == "SENSOR") { FetchRPC(*mds); } } } // end namespace otb
45.033035
153
0.543212
[ "vector", "model" ]
de58e7c94b5fabf5e178e153123f435bbcdefcdc
18,545
cpp
C++
Doraemon.cpp
Hanbo-Sun/SGD-for-L1-regularized-Log-linear-Models
dca70d4b013c6384457de813c70a6cc95f87ae1b
[ "MIT" ]
1
2019-03-20T04:19:37.000Z
2019-03-20T04:19:37.000Z
Doraemon.cpp
Hanbo-Sun/SGD_L1regu_LogLinear_Models
dca70d4b013c6384457de813c70a6cc95f87ae1b
[ "MIT" ]
null
null
null
Doraemon.cpp
Hanbo-Sun/SGD_L1regu_LogLinear_Models
dca70d4b013c6384457de813c70a6cc95f87ae1b
[ "MIT" ]
null
null
null
// L1-regularized logistic regression implementation using stochastic gradient descent #include <iostream> #include <fstream> #include <iomanip> #include <random> #include <cstdlib> #include <cmath> #include <vector> #include <sstream> #include <numeric> #include <algorithm> #include <map> #include <set> #include <string> using namespace std; vector<string> split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { vector<string> elems; split(s, delim, elems); return elems; } void usage(const char* prog){ cout << "L1-regularized logistic regression implementation using stochastic gradient descent:\n" << endl; cout << "Options:" << endl; cout << "-s <int> Shuffle dataset after each iteration. default 1, and 0 indicates no Shuffle" << endl; cout<< "-sp <bool> The data file is stored as spase format. default 1"<<endl; cout << "-i <int> Maximum iterations. default 50000" << endl; cout << "-e <float> Convergence rate. default 0.005, larger than 1 not recommended" << endl; cout << "-l <float> L1 regularization weight. default 0.0001" << endl; cout << "-lr <float> Select adaptive learning rate methods,default 0 - exponential decay"<<endl; cout << "-a <float> Learning rate. default 0.001" << endl; cout << "-m <file> Read weights from file" << endl; cout << "-o <file> Write weights to file" << endl; cout << "-tr <file> Train file from source" << endl; cout << "-t <file> Test file to classify" << endl; cout << "-p <file> Write predictions to file" << endl; cout << "-sc Scale the data to the range of 0 to 1" << endl; cout << "-r Randomise weights between -1 and 1, otherwise 0" << endl; cout << "-v Verbose, showing more information" << endl << endl; } double vecnorm(map<int,double>& w1, map<int,double>& w2){ double sum = 0.0; for(auto it = w1.begin(); it != w1.end(); it++){ double minus = w1[it->first] - w2[it->first]; double r = minus * minus; sum += r; } return sqrt(sum); } double l1norm(map<int,double>& weights){ double sum = 0.0; for(auto it = weights.begin(); it != weights.end(); it++){ sum += fabs(it->second); } return sum; } double sigmoid(double x){ static double overflow = 20.0; if (x > overflow) x = overflow; if (x < -overflow) x = -overflow; return 1.0/(1.0 + exp(-x)); } double classify(map<int,double>& features, map<int,double>& weights){ double logit = 0.0; for(auto it = features.begin(); it != features.end(); it++){ if(it->first != 0){ logit += it->second * weights[it->first]; } } return sigmoid(logit); } void normalize(vector<map<int, double> > &data, int p){ vector<double> min; vector<double> max; int countzero = 0; for(int i=1; i<=p; i++){ set<double> temp; countzero = 0; for(int j=0; j<data.size(); j++){ if(data[j][i] == 0 && countzero <1){countzero++;temp.insert(data[j][i]);} if(data[j][i] !=0){ temp.insert(data[j][i]); } } set<double> ::iterator it1 = temp.begin(); set<double> ::iterator it2 = temp.end(); --it2; min.push_back(*it1); max.push_back(*it2); } for(int i=1; i<=p; i++){ for(int j=0; j<data.size(); j++){ if(((max[i-1] !=0 ) || (min[i-1]!=0 )) && data[j][i] !=0 ) data[j][i] = (data[j][i] - min[i-1]) / (max[i-1] - min[i-1]);; } //if(i%1000 == 0){ //cout <<"finished running 1000 lines" <<endl; //} } for(int j=0; j<data.size(); j++){ for(int i=1; i<=p; i++){ if(data[j][i] == 0){ data[j].erase(i); } } } } void readWeights(ifstream& fin, string line, map<int, double> &weights){ while (getline(fin, line)){ if(line.length()){ if(line[0] != '#' && line[0] != ' '){ vector<string> tokens2 = split(line,' '); if(tokens2.size() == 2){ weights[atoi(tokens2[0].c_str())] = atof(tokens2[1].c_str()); } } } } if(!weights.size()){ cout << "Failed to read weights from file!" << endl; fin.close(); exit(-1); }fin.close(); } void trainingWeights(ifstream &fin, string line,vector<map<int, double> > &data,map<int,double> &weights,map<int,double> &total_l1, int randw){ random_device rd; while (getline(fin, line)){ if(line.length()){ if(line[0] != '#' && line[0] != ' '){ vector<string> tokens = split(line,' '); map<int,double> example; if(atoi(tokens[0].c_str()) == 1){ example[0] = 1; }else{ example[0] = 0; } for(unsigned int i = 1; i < tokens.size(); i++){ //if(strstr (tokens[i],"#") == NULL){ vector<string> feat_val = split(tokens[i],':'); if(feat_val.size() == 2){ example[atoi(feat_val[0].c_str())] = atof(feat_val[1].c_str()); if(randw){ weights[atoi(feat_val[0].c_str())] = -1.0+2.0*(double)rd()/rd.max(); }else{ weights[atoi(feat_val[0].c_str())] = 0.0; } total_l1[atoi(feat_val[0].c_str())] = 0.0; } //} } data.push_back(example); //if(verbose) cout << "read example " << data.size() << " - found " << example.size()-1 << " features." << endl; } } } } void SGD(vector<map<int,double> >&data, map<int, double> &weights,map<int, double>&total_l1, double &alpha, double lro, double maxit,double eps,double norm,int n, double &mu,mt19937 g,int shuf,double l1,vector<int> &index){ while(norm > eps){ map<int,double> old_weights(weights); if(shuf) shuffle(index.begin(),index.end(),g); for (unsigned int i = 0; i < data.size(); i++){ mu += (l1*alpha); //cout<<l1<<endl; int label = data[index[i]][0]; double predicted = classify(data[index[i]],weights); for(auto it = data[index[i]].begin(); it != data[index[i]].end(); it++){ if(it->first != 0){ weights[it->first] += alpha * (label - predicted) * it->second; if(l1){ // Cumulative L1-regularization // Tsuruoka, Y., Tsujii, J., and Ananiadou, S., 2009 // http://aclweb.org/anthology/P/P09/P09-1054.pdf double z = weights[it->first]; if(weights[it->first] > 0.0){ weights[it->first] = max(0.0,(double)(weights[it->first] - (mu + total_l1[it->first]))); }else if(weights[it->first] < 0.0){ weights[it->first] = min(0.0,(double)(weights[it->first] + (mu - total_l1[it->first]))); } total_l1[it->first] += (weights[it->first] - z); } } } } //cout<<weights<<endl; //cout<<"old"<<old_weights<<endl; norm = vecnorm(weights,old_weights); if(n && n % 100 == 0){ double l1n = l1norm(weights); printf("# convergence: %1.4f l1-norm: %1.4e iterations: %i\n",norm,l1n,n); } if(++n > maxit){ break; } //Update learning rate if (lro==0) { alpha = alpha/(1+((int)n+1)/maxit); } else if(lro!=1 & lro != 0) { alpha = alpha*pow(lro,((int)n+1)/(float)maxit); //cout<<maxit<<endl; //cout<<-(n+1)<<endl; //cout<<((int)n+1)/(float)maxit<<endl; //cout<<lro<<endl; //cout<<pow(lro,((double)n+1)/(double)maxit)<<endl; } } } void testPredict(ifstream &fin, map<int,double> &weights, int verbose, string line, double& tp,double& fp,double& tn,double& fn,string predict_file,ofstream& outfile){ while (getline(fin, line)){ if(line.length()){ if(line[0] != '#' && line[0] != ' '){ vector<string> tokens = split(line,' '); map<int,double> example; int label = atoi(tokens[0].c_str()); for(unsigned int i = 1; i < tokens.size(); i++){ vector<string> feat_val = split(tokens[i],':'); example[atoi(feat_val[0].c_str())] = atof(feat_val[1].c_str()); } double predicted = classify(example,weights); if(verbose){ if(label > 0){ printf("label: +%i : prediction: %1.3f",label,predicted); }else{ printf("label: %i : prediction: %1.3f",label,predicted); } } if(predict_file.length()){ if(predicted > 0.5){ outfile << "1" << endl; }else{ outfile << "0" << endl; } } if(((label == -1 || label == 0) && predicted <= 0.5) || (label == 1 && predicted > 0.5)){ if(label == 1){tp++;}else{tn++;} if(verbose) cout << "\tcorrect" << endl; }else{ if(label == 1){fn++;}else{fp++;} if(verbose) cout << "\tincorrect" << endl; } } } } } void GenerateSparse(string train, int op) { ifstream file(train); vector<map<int,double> > dat; vector<int> y; string str; int n = 0; int m = 0; //cout<<stoi("-1")<<endl; while (getline(file, str)) { n++; map<int,double> example; vector<string> tokens = split(str,','); m=tokens.size(); if (stoi(tokens[m-1])==0) { y.push_back(-1); } else{ y.push_back(stoi(tokens[m-1])); } for (int i = 0; i<m-1; i++) { if (stod(tokens[i])!=0.0) { example[i+1] = stod(tokens[i]); } } dat.push_back(example); //map<int,double>::iterator it=dat[0].begin(); } ofstream myfile; if (op==0) { myfile.open ("sparseFormat.txt"); } else myfile.open("sparseFormatT.txt"); //myfile << "Writing this to a file.\n"; for (int i=0; i<n;i++) { myfile<<y[i]<<" "; for (map<int,double>::iterator it=dat[i].begin(); it!=dat[i].end(); ++it) { myfile<<it->first; myfile<<":"; myfile<<it->second; myfile<<" "; //if(++it != dat[i].end()) //{ // myfile<<","; //it--; //} if(it==dat[i].end()) it--; } myfile<<"\n"; } myfile.close(); } int main(int argc, const char* argv[]){ //Scale or not int scale = 0; //learning rate options double lro = 0; double alpha = 0.001; // Learning rate double l1 = 0.0001; // L1 penalty weight unsigned int maxit = 50000; // Max iterations int shuf = 1; // Shuffle data set double eps = 0.005; // Convergence threshold int verbose = 0; // Verbose int randw = 0; // Randomise weights bool spar = 1; //default as sparse format string model_in = ""; // Read model file string model_out = ""; // Write model file string test_file = ""; // Test file string predict_file = ""; // Predictions file string train = "train.dat"; usage(argv[0]); string Options; //cin.ignore(INT_MAX); cout << "Please input options:"; getline(cin, Options); vector<string> tokens = split(Options,' '); cout << "# called with: "; for(int i = 0; i < (int)tokens.size(); i++){ cout << i+1 << " "; if(tokens[i] == "-a" ) alpha = stof(tokens[i+1]); if(tokens[i] == "-m" ) model_in = string(tokens[i+1]); if(tokens[i] == "-o" ) model_out = string(tokens[i+1]); if(tokens[i] == "-t" ) test_file = string(tokens[i+1]); if(tokens[i] == "-p" ) predict_file = string(tokens[i+1]); if(tokens[i] == "-s" ) shuf = stoi(tokens[i+1]); if(tokens[i] == "-i" ) maxit = stoi(tokens[i+1]); if(tokens[i] == "-tr" ) train = string(tokens[i+1]); if(tokens[i] == "-lr") lro = stof(tokens[i+1]); if(tokens[i] == "-sc") scale = 1; if(tokens[i] == "-sp") spar = stoi(tokens[i+1]); if(tokens[i] == "-e" ) eps = stof(tokens[i+1]); if(tokens[i] == "-l" ) l1 = stof(tokens[i+1]); if(tokens[i] == "-v") verbose = 1; if(tokens[i] == "-r") randw = 1; if(tokens[i] == "-h"){ usage(argv[0]); return(1); } } cout << " Complete" <<endl << endl; if(!model_in.length()){ cout << "# Learning Rate update method: "<<lro<<endl; cout << "# Initial learning rate: " << alpha << endl; cout << "# convergence rate: " << eps << endl; cout << "# l1 penalty weight: " << l1 << endl; cout << "# max. iterations: " << maxit << endl; cout << "# training data: " << argv[argc-1] << endl; if(model_out.length()) cout << "# model output: " << model_out << endl; } if(model_in.length()) cout << "# model input: " << model_in << endl; if(test_file.length()) cout << "# test data: " << test_file << endl; if(spar==0) { //ifstream fte; //fte.open(test_file); //ofstream myte; //myte.open ("sparseFormatT.txt"); GenerateSparse(test_file,1); //fte.close(); } if(predict_file.length()) cout << "# predictions: " << predict_file << endl; vector<map<int,double> > data; map<int,double> weights; map<int,double> total_l1; random_device rd; mt19937 g(rd()); ifstream fin; string line; // Read weights from model file, if provided if(model_in.length()){ fin.open(model_in.c_str()); readWeights(fin, line, weights); } // If no weights file provided, read training file and calculate weights if(!weights.size()){ if (!spar) { GenerateSparse(train,0); train="sparseFormat.txt"; } fin.open(train); trainingWeights(fin, line, data, weights, total_l1, randw); fin.close(); cout << "# training examples: " << data.size() << endl; cout << "# features: " << weights.size() << endl; if(scale){ cout << "Normalizing..." <<endl; normalize(data,weights.size()); } double mu = 0.0; double norm = 1.0; int n = 0; vector<int> index(data.size()); iota(index.begin(),index.end(),0); cout << "# stochastic gradient descent" << endl; SGD(data, weights,total_l1, alpha, lro,maxit, eps, norm, n, mu,g,shuf,l1,index); unsigned int sparsity = 0; for(auto it = weights.begin(); it != weights.end(); it++){ if(it->second != 0) sparsity++; } printf("# sparsity: %1.4f (%i/%i)\n",(double)sparsity/weights.size(),sparsity,(int)weights.size()); if(model_out.length()){ ofstream outfile; outfile.open(model_out.c_str()); for(auto it = weights.begin(); it != weights.end(); it++){ outfile << it->first << " " << it->second << endl; } outfile.close(); cout << "# written weights to file " << model_out << endl; } } // If a test file is provided, classify it using either weights from // the provided weights file, or those just calculated from training if(test_file.length()){ ofstream outfile; if(predict_file.length()){ outfile.open(predict_file.c_str()); } cout << endl; cout << "Testing set classification:" << endl; double tp = 0.0, fp = 0.0, tn = 0.0, fn = 0.0; if (!spar) test_file = "sparseFormatT.txt"; fin.open(test_file.c_str()); testPredict(fin, weights, verbose, line, tp, fp, tn, fn,predict_file,outfile); fin.close(); printf ("# accuracy: %1.4f (%i/%i)\n",((tp+tn)/(tp+tn+fp+fn)),(int)(tp+tn),(int)(tp+tn+fp+fn)); printf ("# precision: %1.4f\n",tp/(tp+fp)); printf ("# recall: %1.4f\n",tp/(tp+fn)); printf ("# mcc: %1.4f\n",((tp*tn)-(fp*fn))/sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn))); printf ("# tp: %i\n",(int)tp); printf ("# tn: %i\n",(int)tn); printf ("# fp: %i\n",(int)fp); printf ("# fn: %i\n",(int)fn); if(predict_file.length()){ cout << "# written predictions to file " << predict_file << endl; outfile.close(); } } return(0); }
34.215867
133
0.458722
[ "vector", "model" ]
de5c76cb761d54c0d9ac3ac6178b2d787076ea6c
545
hh
C++
src/BGL/BGLSVG.hh
revarbat/Mandoline
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
[ "BSD-2-Clause-FreeBSD" ]
17
2015-01-07T10:32:06.000Z
2021-07-06T11:00:38.000Z
src/BGL/BGLSVG.hh
revarbat/Mandoline
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
[ "BSD-2-Clause-FreeBSD" ]
2
2017-08-17T17:44:42.000Z
2018-06-14T23:39:04.000Z
src/BGL/BGLSVG.hh
revarbat/Mandoline
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
[ "BSD-2-Clause-FreeBSD" ]
3
2015-01-07T10:32:06.000Z
2019-03-22T16:56:51.000Z
// // BGLSVG.hh // Part of the Belfry Geometry Library // // Created by GM on 10/13/10. // Copyright 2010 Belfry Software. All rights reserved. // #ifndef BGL_SVG_H #define BGL_SVG_H #include <iostream> using namespace std; namespace BGL { class SVG { public: // member variables double width, height; // Constructors SVG(double w, double h) : width(w), height(h) {} ostream &header(ostream &os) const; ostream &footer(ostream& os) const; }; } #endif // vim: set ts=4 sw=4 nowrap expandtab: settings
14.342105
56
0.655046
[ "geometry" ]
de708fc4b0fc91816f3b545e2f4d7635350f0a92
1,375
cpp
C++
src/main.cpp
bgorzsony/Kalk
6d86027cef7d61d589e806d3017c4c4bac0701cd
[ "MIT" ]
null
null
null
src/main.cpp
bgorzsony/Kalk
6d86027cef7d61d589e806d3017c4c4bac0701cd
[ "MIT" ]
null
null
null
src/main.cpp
bgorzsony/Kalk
6d86027cef7d61d589e806d3017c4c4bac0701cd
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "Token.h" #include "Registers.h" #include "Operator.h" #include "Tokenizer.h" #include "Expression.h" #include "Program.h" #include "memtrace.h" using std::cout; using std::endl; #define CPORTA int main(int argc, char** argv) { /*cout << sizeof(Token) << endl; cout << sizeof(Operand) << endl; cout << sizeof(Operator) << endl; cout << sizeof(Command) << endl; cout << sizeof(Expression) << endl;*/ #ifdef CPORTA std::istream& is = std::cin; #endif // CPORTA #ifndef CPORTA if (argc < 2) { std::cout << "Filename expected" << std::endl; return 1; } std::ifstream fs; fs.open(argv[1]); if (!fs.is_open()) { std::cerr << "Can't open file" << std::endl;return 1; } std::istream& is = fs; #endif // ! CPORTA std::string line; Program p = Program::getInstance(); try { while (getline(is, line)) { if (line == "") continue; std::vector<Token*> tokens = Tokenizer::tokenize(line); Command* cmd = Tokenizer::buildCommand(tokens); p.addNewCommand(cmd); } } catch (std::exception e) { std::cerr << e.what() << std::endl; } std::cin.clear(); try { p.Run(); } catch(std::exception e){ std::cerr << e.what() << std::endl; } #ifndef CPORTA fs.close(); #endif // ! CPORTA return 0; }
16.975309
78
0.576727
[ "vector" ]
de719bc5356d0cd4d1f42de378c426ad256075df
3,357
cpp
C++
android-31/java/io/StreamTokenizer.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/io/StreamTokenizer.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/io/StreamTokenizer.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JByteArray.hpp" #include "../../JCharArray.hpp" #include "./InputStream.hpp" #include "./Reader.hpp" #include "../../JString.hpp" #include "./StreamTokenizer.hpp" namespace java::io { // Fields jint StreamTokenizer::TT_EOF() { return getStaticField<jint>( "java.io.StreamTokenizer", "TT_EOF" ); } jint StreamTokenizer::TT_EOL() { return getStaticField<jint>( "java.io.StreamTokenizer", "TT_EOL" ); } jint StreamTokenizer::TT_NUMBER() { return getStaticField<jint>( "java.io.StreamTokenizer", "TT_NUMBER" ); } jint StreamTokenizer::TT_WORD() { return getStaticField<jint>( "java.io.StreamTokenizer", "TT_WORD" ); } jdouble StreamTokenizer::nval() { return getField<jdouble>( "nval" ); } JString StreamTokenizer::sval() { return getObjectField( "sval", "Ljava/lang/String;" ); } jint StreamTokenizer::ttype() { return getField<jint>( "ttype" ); } // QJniObject forward StreamTokenizer::StreamTokenizer(QJniObject obj) : JObject(obj) {} // Constructors StreamTokenizer::StreamTokenizer(java::io::InputStream arg0) : JObject( "java.io.StreamTokenizer", "(Ljava/io/InputStream;)V", arg0.object() ) {} StreamTokenizer::StreamTokenizer(java::io::Reader arg0) : JObject( "java.io.StreamTokenizer", "(Ljava/io/Reader;)V", arg0.object() ) {} // Methods void StreamTokenizer::commentChar(jint arg0) const { callMethod<void>( "commentChar", "(I)V", arg0 ); } void StreamTokenizer::eolIsSignificant(jboolean arg0) const { callMethod<void>( "eolIsSignificant", "(Z)V", arg0 ); } jint StreamTokenizer::lineno() const { return callMethod<jint>( "lineno", "()I" ); } void StreamTokenizer::lowerCaseMode(jboolean arg0) const { callMethod<void>( "lowerCaseMode", "(Z)V", arg0 ); } jint StreamTokenizer::nextToken() const { return callMethod<jint>( "nextToken", "()I" ); } void StreamTokenizer::ordinaryChar(jint arg0) const { callMethod<void>( "ordinaryChar", "(I)V", arg0 ); } void StreamTokenizer::ordinaryChars(jint arg0, jint arg1) const { callMethod<void>( "ordinaryChars", "(II)V", arg0, arg1 ); } void StreamTokenizer::parseNumbers() const { callMethod<void>( "parseNumbers", "()V" ); } void StreamTokenizer::pushBack() const { callMethod<void>( "pushBack", "()V" ); } void StreamTokenizer::quoteChar(jint arg0) const { callMethod<void>( "quoteChar", "(I)V", arg0 ); } void StreamTokenizer::resetSyntax() const { callMethod<void>( "resetSyntax", "()V" ); } void StreamTokenizer::slashSlashComments(jboolean arg0) const { callMethod<void>( "slashSlashComments", "(Z)V", arg0 ); } void StreamTokenizer::slashStarComments(jboolean arg0) const { callMethod<void>( "slashStarComments", "(Z)V", arg0 ); } JString StreamTokenizer::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } void StreamTokenizer::whitespaceChars(jint arg0, jint arg1) const { callMethod<void>( "whitespaceChars", "(II)V", arg0, arg1 ); } void StreamTokenizer::wordChars(jint arg0, jint arg1) const { callMethod<void>( "wordChars", "(II)V", arg0, arg1 ); } } // namespace java::io
16.455882
67
0.638963
[ "object" ]
de732b93a6635a1813ebbeff759fefe3de239962
5,135
hpp
C++
include/DREAM/Solver/Solver.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
include/DREAM/Solver/Solver.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
include/DREAM/Solver/Solver.hpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
#ifndef _DREAM_SOLVER_HPP #define _DREAM_SOLVER_HPP /* Definition of the abstract base class 'Solver', which * defines the interface for all equation solvers in DREAM. */ #include <vector> #include <softlib/SFile.h> #include "DREAM/ConvergenceChecker.hpp" #include "DREAM/DiagonalPreconditioner.hpp" #include "DREAM/Equations/CollisionQuantityHandler.hpp" #include "DREAM/Equations/RunawayFluid.hpp" #include "DREAM/UnknownQuantityEquation.hpp" #include "DREAM/Equations/SPIHandler.hpp" #include "FVM/BlockMatrix.hpp" #include "FVM/FVMException.hpp" #include "FVM/MatrixInverter.hpp" #include "FVM/TimeKeeper.hpp" #include "FVM/UnknownQuantityHandler.hpp" namespace DREAM { class Solver { protected: FVM::UnknownQuantityHandler *unknowns; // List of equations associated with unknowns (owned by the 'EquationSystem') std::vector<UnknownQuantityEquation*> *unknown_equations; std::vector<len_t> nontrivial_unknowns; // Mapping from EquationSystem 'unknown_quantity_id' to index // in the block matrix representing the system std::map<len_t, len_t> unknownToMatrixMapping; // Number of rows in any (jacobian) matrix built by // this solver (not counting unknowns which should // not appear in the matrix) len_t matrix_size; // Flag indicating which linear solver to use enum OptionConstants::linear_solver linearSolver = OptionConstants::LINEAR_SOLVER_LU; enum OptionConstants::linear_solver backupSolver = OptionConstants::LINEAR_SOLVER_NONE; CollisionQuantityHandler *cqh_hottail, *cqh_runaway; RunawayFluid *REFluid; IonHandler *ionHandler; // Convergence checker for linear solver (GMRES primarily) ConvergenceChecker *convChecker=nullptr; DiagonalPreconditioner *diag_prec=nullptr; FVM::MatrixInverter *inverter=nullptr; // Main matrix inverter to use FVM::MatrixInverter *mainInverter=nullptr; // Robust backup inverter to use if necessary FVM::MatrixInverter *backupInverter=nullptr; SPIHandler *SPI; /*FVM::DurationTimer timerTot, timerCqh, timerREFluid, timerRebuildTerms;*/ FVM::TimeKeeper *solver_timeKeeper; len_t timerTot, timerCqh, timerREFluid, timerSPIHandler, timerRebuildTerms; virtual void initialize_internal(const len_t, std::vector<len_t>&) {} public: Solver( FVM::UnknownQuantityHandler*, std::vector<UnknownQuantityEquation*>*, enum OptionConstants::linear_solver ls=OptionConstants::LINEAR_SOLVER_LU, enum OptionConstants::linear_solver bk=OptionConstants::LINEAR_SOLVER_NONE ); virtual ~Solver(); void BuildJacobian(const real_t, const real_t, FVM::BlockMatrix*); void BuildMatrix(const real_t, const real_t, FVM::BlockMatrix*, real_t*); void BuildVector(const real_t, const real_t, real_t*, FVM::BlockMatrix*); void RebuildTerms(const real_t, const real_t); void CalculateNonTrivial2Norm(const real_t*, real_t*); ConvergenceChecker *GetConvergenceChecker() { return convChecker; } len_t GetMatrixSize() { return this->matrix_size; } //virtual const real_t *GetSolution() const = 0; virtual void Initialize(const len_t, std::vector<len_t>&); std::vector<len_t> GetNonTrivials() { return this->nontrivial_unknowns; } virtual void SetCollisionHandlers( CollisionQuantityHandler *cqh_hottail, CollisionQuantityHandler *cqh_runaway, RunawayFluid *REFluid ) { this->cqh_hottail = cqh_hottail; this->cqh_runaway = cqh_runaway; this->REFluid = REFluid; } virtual void SetSPIHandler(SPIHandler *SPI){this->SPI=SPI;} virtual void SetIonHandler(IonHandler *ih) {this->ionHandler = ih;} virtual void SetInitialGuess(const real_t*) = 0; virtual void Solve(const real_t t, const real_t dt) = 0; void Precondition(FVM::Matrix*, Vec); void UnPrecondition(Vec); virtual void PrintTimings() = 0; void PrintTimings_rebuild(); virtual void SaveTimings(SFile*, const std::string& path="") = 0; void SaveTimings_rebuild(SFile*, const std::string& path=""); FVM::MatrixInverter *ConstructLinearSolver(const len_t, enum OptionConstants::linear_solver); void SetConvergenceChecker(ConvergenceChecker*); void SetPreconditioner(DiagonalPreconditioner*); void SelectLinearSolver(const len_t); virtual void SwitchToBackupInverter(); void SwitchToMainInverter(); virtual void WriteDataSFile(SFile*, const std::string&); }; class SolverException : public DREAM::FVM::FVMException { public: template<typename ... Args> SolverException(const std::string &msg, Args&& ... args) : FVMException(msg, std::forward<Args>(args) ...) { AddModule("Solver"); } }; } #endif/*_DREAM_SOLVER_HPP*/
38.037037
101
0.680818
[ "vector" ]
de7d9e341591a653c1dcf8edc38bf6469815482e
18,417
cxx
C++
com/ole32/stg/msf/vect.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/stg/msf/vect.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/stg/msf/vect.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1992. // // File: vect.cxx // // Contents: Vector common code. // // Classes: // // Functions: // // History: 27-Oct-92 PhilipLa Created // //---------------------------------------------------------------------------- #include "msfhead.cxx" #pragma hdrstop #include <msffunc.hxx> #include <vect.hxx> #include <ole.hxx> #include <entry.hxx> #include <smalloc.hxx> inline CVectBits * CPagedVector::GetNewVectBits(ULONG ulSize) { msfAssert(ulSize > 0); CVectBits *pfb = NULL; if (ulSize <= (_HEAP_MAXREQ / sizeof(CVectBits))) { pfb = (CVectBits *) _pmsParent->GetMalloc()->Alloc(ulSize * sizeof(CVectBits)); if (pfb) { memset(pfb, 0, (ulSize * sizeof(CVectBits))); } } return pfb; } inline CBasedMSFPagePtr* VECT_CLASS CPagedVector::GetNewPageArray(ULONG ulSize) { msfAssert(ulSize > 0); if (ulSize > (_HEAP_MAXREQ / sizeof(CMSFPage *))) { return NULL; } return (CBasedMSFPagePtr *) _pmsParent->GetMalloc()->Alloc(ulSize * sizeof(CMSFPage *)); } //+------------------------------------------------------------------------- // // Method: CPagedVector::Init, public // // Synopsis: CPagedVector initialization function // // Arguments: [ulSize] -- size of vector // [uFatEntries] -- number of entries in each table // // Algorithm: Allocate an array of pointer of size ulSize // For each cell in the array, allocate a CFatSect // // History: 27-Dec-91 PhilipLa Created. // // Notes: // //-------------------------------------------------------------------------- SCODE VECT_CLASS CPagedVector::Init(CMStream *pmsParent, ULONG ulSize) { msfDebugOut((DEB_ITRACE,"In CPagedVector::CPagedVector(%lu)\n",ulSize)); SCODE sc = S_OK; _pmsParent = P_TO_BP(CBasedMStreamPtr, pmsParent); CMSFPageTable *pmptTemp = _pmsParent->GetPageTable(); _pmpt = P_TO_BP(CBasedMSFPageTablePtr, pmptTemp); msfAssert(_pmpt != NULL); ULONG i; // We don't bother allocating more than necessary here _ulAllocSize = _ulSize = ulSize; if (_ulSize > 0) { CBasedMSFPagePtr *ampTemp; msfMem(ampTemp = GetNewPageArray(ulSize)); for (i = 0; i < _ulSize; i++) { ampTemp[i] = NULL; } _amp = P_TO_BP(CBasedMSFPagePtrPtr, ampTemp); CVectBits *avbTemp; msfMem(avbTemp = GetNewVectBits(ulSize)); _avb = P_TO_BP(CBasedVectBitsPtr, avbTemp); } msfDebugOut((DEB_ITRACE,"Out CPagedVector::CPagedVector()\n")); return S_OK; Err: //In the error case, discard whatever vectors we were able to allocate // and return S_OK. _pmsParent->GetMalloc()->Free(BP_TO_P(CBasedMSFPagePtr *, _amp)); _amp = NULL; _pmsParent->GetMalloc()->Free(BP_TO_P(CVectBits *,_avb)); _avb = NULL; return S_OK; } //+------------------------------------------------------------------------- // // Method: CPagedVector::~CPagedVector, public // // Synopsis: CPagedVector constructor // // Algorithm: Delete the pointer array. // // History: 27-Oct-92 PhilipLa Created. // 20-Jul-95 SusiA Changed Free to FreeNoMutex // // Notes: This function freed the SmAllocator object without first obtaining // the mutex. Callling functions should already have the DFMutex locked. // //-------------------------------------------------------------------------- VECT_CLASS CPagedVector::~CPagedVector() { if (_pmsParent != NULL) { #ifdef MULTIHEAP // Free is the same as FreeNoMutex now _pmsParent->GetMalloc()->Free(BP_TO_P(CBasedMSFPagePtr*, _amp)); _pmsParent->GetMalloc()->Free(BP_TO_P(CVectBits *,_avb)); #else g_smAllocator.FreeNoMutex(BP_TO_P(CBasedMSFPagePtr*, _amp)); g_smAllocator.FreeNoMutex(BP_TO_P(CVectBits *, _avb)); #endif } else msfAssert(_amp == NULL && _avb == NULL && aMsg("Can't free arrays without allocator")); } //+--------------------------------------------------------------------------- // // Member: CPagedVector::Empty, public // // Synopsis: Discard the storage associated with this vector. // // Arguments: None. // // Returns: void. // // History: 04-Dec-92 PhilipLa Created // //---------------------------------------------------------------------------- void CPagedVector::Empty(void) { if (_pmpt != NULL) { _pmpt->FreePages(this); } msfAssert(((_pmsParent != NULL) || ((_amp == NULL) && (_avb == NULL))) && aMsg("Can't get to IMalloc for vector memory.")); if (_pmsParent != NULL) { _pmsParent->GetMalloc()->Free(BP_TO_P(CBasedMSFPagePtr*, _amp)); _pmsParent->GetMalloc()->Free(BP_TO_P(CVectBits *, _avb)); } _amp = NULL; _avb = NULL; _pmpt = NULL; _ulAllocSize = _ulSize = 0; _pmsParent = NULL; } //+--------------------------------------------------------------------------- // // Member: CPagedVector::Flush, public // // Synopsis: Flush the dirty pages for this vector // // Arguments: None. // // Returns: Appropriate status code // // History: 02-Nov-92 PhilipLa Created // //---------------------------------------------------------------------------- SCODE CPagedVector::Flush(void) { #ifndef SORTPAGETABLE SCODE sc; SCODE scRet = S_OK; if (_ulSize > 0) { if (_amp != NULL) { for (ULONG i = 0; i < _ulSize; i++) { if ((_amp[i] != NULL) && (_amp[i]->IsDirty())) { sc = _pmpt->FlushPage(BP_TO_P(CMSFPage *, _amp[i])); if ((FAILED(sc)) && (SUCCEEDED(scRet))) { scRet = sc; } } } } else { scRet = _pmpt->Flush(); } } return scRet; #else return S_OK; #endif } //+------------------------------------------------------------------------- // // Method: CPagedVector::GetTable, public // // Synopsis: Return a pointer to a page for the given index // into the vector. // // Arguments: [iTable] -- index into vector // [ppmp] -- Pointer to return location // // Returns: S_OK if call completed OK. // // History: 27-Oct-92 PhilipLa Created. // // Notes: // //-------------------------------------------------------------------------- SCODE VECT_CLASS CPagedVector::GetTableWithSect( const FSINDEX iTable, DWORD dwFlags, SECT sectKnown, void **ppmp) { SCODE sc = S_OK; CMSFPage *pmp; msfAssert((_pmsParent->GetILB() != NULL) && aMsg("Null ILB found on GetTable - need SetAccess call?")); // docfile is corrupted with an invalid iTable size if (iTable >= _ulSize) { msfErr(Err, STG_E_DOCFILECORRUPT); } if ((_amp == NULL) || (_amp[iTable] == NULL)) { if (dwFlags & FB_NEW) { //We know that the page isn't in the page table, // so we can just get a free page an allocate it // ourselves. msfChk(_pmpt->GetFreePage(&pmp)); pmp->SetVector(this); pmp->SetSid(_sid); pmp->SetOffset(iTable); #ifdef SORTPAGETABLE _pmpt->SetSect(pmp, ENDOFCHAIN); #else pmp->SetSect(ENDOFCHAIN); #endif sc = STG_S_NEWPAGE; dwFlags = (dwFlags & ~FB_NEW) | FB_DIRTY; } else { msfChk(_pmpt->GetPage(this, _sid, iTable, sectKnown, &pmp)); msfAssert((pmp->GetVector() == this) && aMsg("GetPage returned wrong page.")); } if (_amp != NULL) { _amp[iTable] = P_TO_BP(CBasedMSFPagePtr, pmp); } } else { pmp = BP_TO_P(CMSFPage *, _amp[iTable]); msfAssert((pmp->GetVector() == this) && aMsg("Cached page has wrong vector pointer")); } pmp->AddRef(); if (((dwFlags & FB_DIRTY) && !(pmp->IsDirty())) && (sc != STG_S_NEWPAGE)) { //If we are not a newly created page, and we are being // dirtied for the first time, make sure that our // _sect field is correct. // //Newly created pages have to have their sect set manually // _before_ being released. This is very important. msfAssert(!_pmsParent->IsShadow() && aMsg("Dirtying page in shadow multistream.")); msfChkTo(Err_Rel, _pmsParent->GetFat()->QueryRemapped(pmp->GetSect())); if (sc == S_FALSE) { #ifdef SORTPAGETABLE _pmpt->SetSect(pmp, ENDOFCHAIN); #else pmp->SetSect(ENDOFCHAIN); #endif SECT sect; msfChkTo(Err_Rel, _pmsParent->GetESect( pmp->GetSid(), pmp->GetOffset(), &sect)); #ifdef SORTPAGETABLE _pmpt->SetSect(pmp, sect); #else pmp->SetSect(sect); #endif } } #if DBG == 1 else if ((pmp->IsDirty()) && (!pmp->IsInUse()) && (sc != STG_S_NEWPAGE)) { msfAssert((_pmsParent->GetFat()->QueryRemapped(pmp->GetSect()) == S_OK) && aMsg("Found unremapped dirty page.")); } #endif pmp->SetFlags(pmp->GetFlags() | dwFlags | FB_TOUCHED); msfAssert((pmp->GetVector() == this) && aMsg("GetTable returned wrong page.")); *ppmp = pmp->GetData(); Err: return sc; Err_Rel: pmp->Release(); return sc; } //+--------------------------------------------------------------------------- // // Member: CPagedVector::SetDirty, public // // Synopsis: Set the dirty bit on the specified page // // Arguments: [iTable] -- Table to set bit on // // History: 28-Oct-92 PhilipLa Created // // Notes: This function is always called on a page with an // open reference. Therefore, the page is // guaranteed to be in the page table, and that // FindPage call should never return an error. // //---------------------------------------------------------------------------- SCODE CPagedVector::SetDirty(ULONG iTable) { SCODE sc = S_OK; CMSFPage *pmp; msfAssert((!_pmsParent->IsShadow()) && aMsg("Dirtying page in shadow.")); if (_amp == NULL) { msfChk(_pmpt->FindPage(this, _sid, iTable, &pmp)); msfAssert(sc == STG_S_FOUND); msfAssert(pmp->IsInUse() && aMsg("Called SetDirty on page not in use.")); } else { msfAssert(_amp != NULL); msfAssert(_amp[iTable] != NULL); pmp = BP_TO_P(CMSFPage *, _amp[iTable]); } if (!pmp->IsDirty()) { //We are not a newly created page, and we are being // dirtied for the first time, make sure that our // _sect field is correct. // msfAssert(!_pmsParent->IsShadow() && aMsg("Dirtying page in shadow multistream.")); pmp->AddRef(); msfChkTo(Err_Rel, _pmsParent->GetFat()->QueryRemapped(pmp->GetSect())); if (sc == S_FALSE) { #ifdef SORTPAGETABLE _pmpt->SetSect(pmp, ENDOFCHAIN); #else pmp->SetSect(ENDOFCHAIN); #endif SECT sect; msfChkTo(Err_Rel, _pmsParent->GetESect( pmp->GetSid(), pmp->GetOffset(), &sect)); #ifdef SORTPAGETABLE _pmpt->SetSect(pmp, sect); #else pmp->SetSect(sect); #endif } pmp->Release(); } #if DBG == 1 else { pmp->AddRef(); sc = _pmsParent->GetFat()->QueryRemapped(pmp->GetSect()); msfAssert((SUCCEEDED(sc)) && aMsg("QueryRemapped returned error")); msfAssert((sc == S_OK) && aMsg("QueryRemapped returned non-TRUE value.")); pmp->Release(); } #endif pmp->SetDirty(); Err: return sc; Err_Rel: pmp->Release(); return sc; } //+------------------------------------------------------------------------- // // Method: CPagedVector::Resize, public // // Synopsis: Resize a CPagedVector // // Arguments: [ulSize] -- Size of new vector // // Algorithm: Create new pointer array of size ulSize. // For each entry in old array, copy the pointer over. // // History: 27-Oct-92 PhilipLa Created. // 08-Feb-93 AlexT Add LARGETHRESHOLD support // // Notes: // //-------------------------------------------------------------------------- #define LARGETHRESHOLD 1024 #define VECTORBLOCK 1024 // Must be power of 2 SCODE VECT_CLASS CPagedVector::Resize(FSINDEX ulSize) { msfDebugOut((DEB_ITRACE,"In CPagedVector::CPagedVector(%lu)\n",ulSize)); msfAssert(ulSize >= _ulSize); msfAssert(_ulSize <= _ulAllocSize); msfAssert(((VECTORBLOCK & (VECTORBLOCK - 1)) == 0) && aMsg("VECTORBLOCK must be power of 2")); msfAssert(!((_amp == NULL) && (_avb != NULL)) && aMsg("Resize precondition failed.")); if (ulSize > _ulAllocSize) { // We don't have room in the existing vector; grow it ULONG ulNewAllocSize = ulSize; if (ulNewAllocSize > LARGETHRESHOLD) { // We're dealing with a large vector; grow it a VECTORBLOCK // at a time ulNewAllocSize = (ulNewAllocSize + VECTORBLOCK - 1) & ~(VECTORBLOCK - 1); } CBasedMSFPagePtr *amp = GetNewPageArray(ulNewAllocSize); CVectBits *avb = GetNewVectBits(ulNewAllocSize); // Can't fail after this point _ulAllocSize = ulNewAllocSize; // Copy over the old entries if ((amp != NULL) && (avb != NULL)) { if ((_amp != NULL) && (_avb != NULL)) { // Both allocations succeeded for (ULONG iamp = 0; iamp < _ulSize; iamp++) { amp[iamp] = _amp[iamp]; avb[iamp] = _avb[iamp]; } } else if (_amp != NULL) { for (ULONG iamp = 0; iamp < _ulSize; iamp++) { amp[iamp] = _amp[iamp]; } } else { for (ULONG iamp = 0; iamp < _ulSize; iamp++) { amp[iamp] = NULL; } } } else { // At least one of the allocations failed _pmsParent->GetMalloc()->Free(avb); avb = NULL; _pmsParent->GetMalloc()->Free(amp); amp = NULL; } // Delete the old vector and put in the new one (if any). // In the error case, throw away the vectors we are currently // holding (since they are of insufficient size) and return S_OK. _pmsParent->GetMalloc()->Free(BP_TO_P(CBasedMSFPagePtr*, _amp)); _amp = P_TO_BP(CBasedMSFPagePtrPtr, amp); _pmsParent->GetMalloc()->Free(BP_TO_P(CVectBits *, _avb)); _avb = P_TO_BP(CBasedVectBitsPtr, avb); } if (_amp != NULL) { // Initialize the new elements in the vector for (ULONG iamp = _ulSize; iamp < ulSize; iamp++) _amp[iamp] = NULL; } _ulSize = ulSize; msfDebugOut((DEB_ITRACE,"Out CPagedVector resize constructor\n")); return S_OK; } //+------------------------------------------------------------------------- // // Method: CPagedVector::InitCopy, public // // Synopsis: CPagedVector Init function for copying // // Arguments: [vectOld] -- Reference to vector to be copied. // // Algorithm: *Finish This* // // History: 27-Oct-92 PhilipLa Created. // // Notes: // //-------------------------------------------------------------------------- void VECT_CLASS CPagedVector::InitCopy(CPagedVector *pvectOld) { msfDebugOut((DEB_ITRACE,"In CPagedVector copy constructor\n")); SCODE sc; ULONG i; _pmsParent = pvectOld->_pmsParent; CMSFPageTable *pmpt; pmpt = _pmsParent->GetPageTable(); _pmpt = P_TO_BP(CBasedMSFPageTablePtr, pmpt); _ulAllocSize = _ulSize = pvectOld->_ulSize; if (_ulSize > 0) { CBasedMSFPagePtr* amp; msfMem(amp = GetNewPageArray(_ulSize)); for (i = 0; i < _ulSize; i++) { amp[i] = NULL; if (pvectOld->_amp != NULL) { _pmpt->CopyPage(this, BP_TO_P(CMSFPage *, pvectOld->_amp[i]), &(amp[i])); } } _amp = P_TO_BP(CBasedMSFPagePtrPtr, amp); CVectBits *avb; msfMem(avb = GetNewVectBits(_ulSize)); if (pvectOld->_avb != NULL) { for (i = 0; i < _ulSize; i++) { avb[i] = ((CPagedVector *)pvectOld)->_avb[i]; } } _avb = P_TO_BP(CBasedVectBitsPtr, avb); } msfDebugOut((DEB_ITRACE,"Out CPagedVector copy constructor\n")); //In the error case, keep whatever vectors we managed to allocate // and return. Err: return; }
27.447094
81
0.481023
[ "object", "vector" ]
de80055d345fcd587cf8bc62da5d56f4b88adcb7
1,383
hpp
C++
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.hpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
23
2021-10-31T00:20:21.000Z
2022-03-26T07:24:40.000Z
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.hpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
5
2021-10-31T18:44:51.000Z
2022-03-25T18:04:26.000Z
Server Lib/Game Server/PANGYA_DB/cmd_my_room_item.hpp
CCasusensa/SuperSS-Dev
6c6253b0a56bce5dad150c807a9bbf310e8ff61b
[ "MIT" ]
18
2021-10-20T02:31:56.000Z
2022-02-01T11:44:36.000Z
// Arquivo cmd_my_room_item.hpp // Criado em 22/03/2018 as 20:39 por Acrisio // Defini��o da classe CmdMyRoomItem #pragma once #ifndef _STDA_CMD_MY_ROOM_ITEM_HPP #define _STDA_CMD_MY_ROOM_ITEM_HPP #include "../../Projeto IOCP/PANGYA_DB/pangya_db.h" #include "../TYPE/pangya_game_st.h" #include <vector> namespace stdA { class CmdMyRoomItem : public pangya_db { public: enum TYPE : unsigned char { ALL, ONE, }; public: explicit CmdMyRoomItem(bool _waiter = false); CmdMyRoomItem(uint32_t _uid, TYPE _type, int32_t _item_id = -1, bool _waiter = false); virtual ~CmdMyRoomItem(); std::vector< MyRoomItem >& getMyRoomItem(); uint32_t getUID(); void setUID(uint32_t _uid); int32_t getItemID(); void setItemID(int32_t _item_id); TYPE getType(); void setType(TYPE _type); protected: void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override; response* prepareConsulta(database& _db) override; // get Class name virtual std::string _getName() override { return "CmdMyRoomItem"; }; virtual std::wstring _wgetName() override { return L"CmdMyRoomItem"; }; private: uint32_t m_uid; int32_t m_item_id; TYPE m_type; std::vector< MyRoomItem > v_mri; const char* m_szConsulta[2] = { "pangya.ProcGetRoom", "pangya.ProcGetMyRoom_One" }; }; } #endif // !_STDA_CMD_MY_ROOM_ITEM_HPP
24.696429
89
0.711497
[ "vector" ]
de810dac3f126434a55a9161d7cbdebcf04d32c6
7,041
cpp
C++
iVS3D/src/iVS3D-core/model/automaticexecsettings.cpp
iVS3D/iVS3D
a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9
[ "MIT" ]
10
2021-08-05T09:47:11.000Z
2022-03-18T12:47:39.000Z
iVS3D/src/iVS3D-core/model/automaticexecsettings.cpp
iVS3D/iVS3D
a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9
[ "MIT" ]
null
null
null
iVS3D/src/iVS3D-core/model/automaticexecsettings.cpp
iVS3D/iVS3D
a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9
[ "MIT" ]
null
null
null
#include "automaticexecsettings.h" AutomaticExecSettings::AutomaticExecSettings(AutomaticWidget *autoWidget, SamplingWidget *samplingWidget, OutputWidget* outputWidget) : m_autoWidget(autoWidget), m_samplingWidget(samplingWidget), m_outputWidget(outputWidget) { connect(m_samplingWidget, &SamplingWidget::sig_addAuto, this, &AutomaticExecSettings::slot_addAuto); connect(m_autoWidget, &AutomaticWidget::sig_removedPlugin, this, &AutomaticExecSettings::slot_removedPlugin); connect(m_autoWidget, &AutomaticWidget::sig_saveConfiguration, this, &AutomaticExecSettings::slot_saveConfiguration); connect(m_autoWidget, &AutomaticWidget::sig_loadConfiguration, this, &AutomaticExecSettings::slot_loadConfiguration); connect(m_outputWidget, &OutputWidget::sig_addAuto, this, &AutomaticExecSettings::slot_addAutoOutput); connect(m_autoWidget, &AutomaticWidget::sig_doubleClickedItem, this, &AutomaticExecSettings::slot_doubleClickedItem); connect(m_autoWidget, &AutomaticWidget::sig_autoOrderChanged, this, &AutomaticExecSettings::slot_autoOrderChanged); } QList<QPair<QString, QMap<QString, QVariant>>> AutomaticExecSettings::getPluginList() { return m_algoList; } QStringList AutomaticExecSettings::getPluginNames() { QStringList usedPlugins; QString currentName; for (QPair<QString, QMap<QString, QVariant>> entry : m_algoList) { QString name; name = entry.first; if (entry.second.isEmpty()) { name.append(" - Generated settings"); } else { name.append(" - "); currentName = name; QMapIterator<QString, QVariant> iter(entry.second); while(iter.hasNext()) { iter.next(); QString identifier = iter.key() + " = " + iter.value().toString() + "; "; if (iter.value().toString() == "") { continue; } name.append(identifier); } name.chop(2); } usedPlugins.append(name); } return usedPlugins; } void AutomaticExecSettings::setExportController(ExportController* exportController) { m_exportController = exportController; } void AutomaticExecSettings::slot_addAuto(int idx, bool generate) { QString pluginName = AlgorithmManager::instance().getPluginNameToIndex(idx); QMap<QString, QVariant> settings; if (generate) { settings = QMap<QString, QVariant>(); } else { settings = AlgorithmManager::instance().getSettings(idx); } QPair<QString, QMap<QString, QVariant>> newEntry = QPair<QString, QMap<QString, QVariant>>(pluginName, settings); m_algoList.append(newEntry); updateShownAlgoList(); } void AutomaticExecSettings::slot_addAutoOutput() { QString pluginName = stringContainer::Export; QMap<QString, QVariant> settings = m_exportController->getOutputSettings(); QPair<QString, QMap<QString, QVariant>> newEntry = QPair<QString, QMap<QString, QVariant>>(pluginName, settings); m_algoList.append(newEntry); updateShownAlgoList(); } void AutomaticExecSettings::slot_removedPlugin(int row) { m_algoList.removeAt(row); updateShownAlgoList(); } void AutomaticExecSettings::slot_saveConfiguration() { QString savePath = QFileDialog::QFileDialog::getSaveFileName (m_autoWidget, "Save configuration", ApplicationSettings::instance().getStandardInputPath(), "*.json"); if (savePath == nullptr) { return; } savePluginList(savePath); } void AutomaticExecSettings::slot_loadConfiguration() { QString savePath = QFileDialog::getOpenFileName(m_autoWidget, "Choose configuration", ApplicationSettings::instance().getStandardInputPath(), "*.json"); if (savePath == nullptr) { return; } loadPluginList(savePath); } void AutomaticExecSettings::savePluginList(QString path) { QJsonObject fullSave; int i = 0; QListIterator<QPair<QString, QVariantMap>> iterator(m_algoList); while (iterator.hasNext()) { QPair<QString, QVariantMap> pair = iterator.next(); QJsonObject current; QString name = pair.first; current.insert(name, QJsonObject::fromVariantMap(pair.second)); fullSave.insert(QString::number(i), current); i++; } QFile file(path); QJsonDocument doc(fullSave); if (!file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) { return; } file.write(doc.toJson()); file.close(); return; } void AutomaticExecSettings::updateShownAlgoList() { QStringList usedPlugins = getPluginNames(); m_autoWidget->updateSelectedPlugins(usedPlugins); } void AutomaticExecSettings::loadPluginList(QString path) { m_algoList.clear(); //Open file QFile file(path); bool openSuccess = file.open(QIODevice::ReadOnly | QIODevice::Text); if (!openSuccess) { return; } QString data = file.readAll(); file.close(); //Get JsonDocoment from file QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8()); QJsonObject fullObject = doc.object(); for (int i = 0; i < INT_MAX; i++) { //Find Objects in correct order QJsonObject::iterator iter = fullObject.find(QString::number(i)); if (iter == fullObject.end()) { break; } //Step into the value of the found object QJsonObject innerObject = iter.value().toObject(); //value of the innerObject is the settings map QVariant settingsObject = innerObject.begin().value().toObject(); //Key of the innerObject is the plugin name QString pluginName = QString::fromStdString(innerObject.begin().key().toStdString()); QMap<QString, QVariant> pluginSettings = settingsObject.toMap(); QPair<QString, QMap<QString, QVariant>> pair = QPair<QString, QMap<QString, QVariant>>(pluginName, pluginSettings); m_algoList.append(pair); } //dont use ui, if command line is active if (QCoreApplication::arguments().size() < 2) { updateShownAlgoList(); } } void AutomaticExecSettings::slot_doubleClickedItem(int row) { //Signal ExportController to show the export settings if (m_algoList[row].first.compare(stringContainer::Export) == 0) { emit sig_showExportSettings(m_algoList[row].second); int iTransfromIndex = AlgorithmManager::instance().getAlgorithmCount() + 1; m_samplingWidget->setAlgorithm(iTransfromIndex); return; } QStringList pluginList = AlgorithmManager::instance().getAlgorithmList(); int idx = pluginList.indexOf(m_algoList[row].first); //If the settings map is empty (-> generated settings) don't update the plugins settings if (!m_algoList[row].second.isEmpty()) { AlgorithmManager::instance().setSettings(idx, m_algoList[row].second); } m_samplingWidget->setAlgorithm(idx); } void AutomaticExecSettings::slot_autoOrderChanged(int first, int second) { m_algoList.swap(first, second); updateShownAlgoList(); }
34.684729
168
0.690101
[ "object" ]
de8653a9b05c0522eae049603ab1774a4c2d6abd
1,767
cpp
C++
Tracker/src/Marker.cpp
marcelruhf/SoccerRL
afc9dcacf97ee2f3cc959329bd01d3f7fd815397
[ "Apache-2.0" ]
null
null
null
Tracker/src/Marker.cpp
marcelruhf/SoccerRL
afc9dcacf97ee2f3cc959329bd01d3f7fd815397
[ "Apache-2.0" ]
null
null
null
Tracker/src/Marker.cpp
marcelruhf/SoccerRL
afc9dcacf97ee2f3cc959329bd01d3f7fd815397
[ "Apache-2.0" ]
null
null
null
/** * @Author: Marcel Ruhf <marcelruhf> * @Email: m.ruhf@protonmail.ch * @Project: SoccerRL * @Filename: MarkerFinder.cpp * @License: Licensed under the Apache 2.0 license (see LICENSE.md) * @Copyright: Copyright (c) 2017 Marcel Ruhf */ #include <tuple> #include <vector> #include <boost/optional.hpp> #include <opencv2/opencv.hpp> #include <opencv2/aruco.hpp> #include <MarkerFinder.hpp> #include <Constants.hpp> namespace mr { void MarkerFinder::preprocess(const cv::Mat& image) { cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary( cv::aruco::DICT_7X7_50 ); cv::aruco::detectMarkers(image, dict, corners, ids); cv::aruco::estimatePoseSingleMarkers(corners, 0.05, CAMERA_MATRIX, DISTORTION_COEFFICIENTS, rvecs, tvecs); } boost::optional<std::vector<cv::Point2f>> MarkerFinder::getCorners(const int& markerId) { for (int i = 0; i < ids.size(); ++i) { if (ids.at(i) == markerId) { return corners.at(i); } } return boost::optional<std::vector<cv::Point2f>>{}; } boost::optional<cv::Vec3d> MarkerFinder::getRotationVector(const int& markerId) { for (int i = 0; i < ids.size(); ++i) { if (ids.at(i) == markerId) { return rvecs.at(i); } } return boost::optional<cv::Vec3d>{}; } boost::optional<cv::Vec3d> MarkerFinder::getTranslationVector(const int& markerId) { for (int i = 0; i < ids.size(); ++i) { if (ids.at(i) == markerId) { return tvecs.at(i); } } return boost::optional<cv::Vec3d>{}; } }
27.609375
114
0.560272
[ "vector" ]
de8937ab211bf23f349ab9654e5c46abf8473f35
17,692
cpp
C++
demo/cpp/train_HOG.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
57
2015-02-16T06:43:24.000Z
2022-03-16T06:21:36.000Z
demo/cpp/train_HOG.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
4
2016-03-08T09:51:09.000Z
2021-03-29T10:18:55.000Z
demo/cpp/train_HOG.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
27
2015-03-28T19:55:34.000Z
2022-01-09T15:03:15.000Z
#include <opencv2/opencv.hpp> #include <string> #include <iostream> #include <fstream> #include <vector> #include <time.h> using namespace cv; using namespace cv::ml; using namespace std; void get_svm_detector(const Ptr<SVM>& svm, vector< float > & hog_detector ); void convert_to_ml(const std::vector< cv::Mat > & train_samples, cv::Mat& trainData ); void load_images( const string & prefix, const string & filename, vector< Mat > & img_lst ); void sample_neg( const vector< Mat > & full_neg_lst, vector< Mat > & neg_lst, const Size & size, int neg_steps=1 ); Mat get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size ); void compute_hog( const vector< Mat > & img_lst, vector< Mat > & gradient_lst, const Size & size ); void train_svm( const vector< Mat > & gradient_lst, const vector< int > & labels ); void draw_locations( Mat & img, const vector< Rect > & locations, const Scalar & color ); void test_it( const Size & size ); void get_svm_detector(const Ptr<SVM>& svm, vector< float > & hog_detector ) { // get the support vectors Mat sv = svm->getSupportVectors(); const int sv_total = sv.rows; // get the decision function Mat alpha, svidx; double rho = svm->getDecisionFunction(0, alpha, svidx); CV_Assert( alpha.total() == 1 && svidx.total() == 1 && sv_total == 1 ); CV_Assert( (alpha.type() == CV_64F && alpha.at<double>(0) == 1.) || (alpha.type() == CV_32F && alpha.at<float>(0) == 1.f) ); CV_Assert( sv.type() == CV_32F ); hog_detector.clear(); hog_detector.resize(sv.cols + 1); memcpy(&hog_detector[0], sv.ptr(), sv.cols*sizeof(hog_detector[0])); hog_detector[sv.cols] = (float)-rho; } /* * Convert training/testing set to be used by OpenCV Machine Learning algorithms. * TrainData is a matrix of size (#samples x max(#cols,#rows) per samples), in 32FC1. * Transposition of samples are made if needed. */ void convert_to_ml(const std::vector< cv::Mat > & train_samples, cv::Mat& trainData ) { //--Convert data const int rows = (int)train_samples.size(); const int cols = (int)std::max( train_samples[0].cols, train_samples[0].rows ); cv::Mat tmp(1, cols, CV_32FC1); //< used for transposition if needed trainData = cv::Mat(rows, cols, CV_32FC1 ); vector< Mat >::const_iterator itr = train_samples.begin(); vector< Mat >::const_iterator end = train_samples.end(); for( int i = 0 ; itr != end ; ++itr, ++i ) { CV_Assert( itr->cols == 1 || itr->rows == 1 ); if( itr->cols == 1 ) { transpose( *(itr), tmp ); tmp.copyTo( trainData.row( i ) ); } else if( itr->rows == 1 ) { itr->copyTo( trainData.row( i ) ); } } } void load_images( const String & prefix, vector< Mat > & img_lst ) { vector<String> fileNames; glob( prefix, fileNames, true ); for ( size_t i=0; i<fileNames.size(); i++ ) { Mat img = imread( fileNames[i] ); // load the image if ( img.empty() ) // invalid image, just skip it. { cerr << "invalid image: " << fileNames[i] << endl; continue; } #ifdef _DEBUG imshow( "image", img ); waitKey( 10 ); #endif img_lst.push_back( img ); } } void sample_neg( const vector< Mat > & full_neg_lst, vector< Mat > & neg_lst, const Size & size, int neg_steps ) { Rect box(0, 0, size.width, size.height); vector< Mat >::const_iterator img = full_neg_lst.begin(); vector< Mat >::const_iterator end = full_neg_lst.end(); for( ; img != end ; ++img ) { if (neg_steps==0) { Mat roi = (*img)(box); neg_lst.push_back( roi.clone() ); continue; } for (int i=0; i < img->rows - neg_steps - box.height; i+=neg_steps) for (int j=0; j < img->cols - neg_steps - box.width; j+=neg_steps) { box.x = j; box.y = i; Mat roi = (*img)(box); neg_lst.push_back( roi.clone() ); #ifdef _DEBUG imshow( "img", roi.clone() ); waitKey( 10 ); #endif } } } // From http://www.juergenwiki.de/work/wiki/doku.php?id=public:hog_descriptor_computation_and_visualization Mat get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size ) { const int DIMX = size.width; const int DIMY = size.height; float zoomFac = 3; Mat visu; resize(color_origImg, visu, Size( (int)(color_origImg.cols*zoomFac), (int)(color_origImg.rows*zoomFac) ) ); int cellSize = 8; int gradientBinSize = 9; float radRangeForOneBin = (float)(CV_PI/(float)gradientBinSize); // dividing 180 into 9 bins, how large (in rad) is one bin? // prepare data structure: 9 orientation / gradient strenghts for each cell int cells_in_x_dir = DIMX / cellSize; int cells_in_y_dir = DIMY / cellSize; float*** gradientStrengths = new float**[cells_in_y_dir]; int** cellUpdateCounter = new int*[cells_in_y_dir]; for (int y=0; y<cells_in_y_dir; y++) { gradientStrengths[y] = new float*[cells_in_x_dir]; cellUpdateCounter[y] = new int[cells_in_x_dir]; for (int x=0; x<cells_in_x_dir; x++) { gradientStrengths[y][x] = new float[gradientBinSize]; cellUpdateCounter[y][x] = 0; for (int bin=0; bin<gradientBinSize; bin++) gradientStrengths[y][x][bin] = 0.0; } } // nr of blocks = nr of cells - 1 // since there is a new block on each cell (overlapping blocks!) but the last one int blocks_in_x_dir = cells_in_x_dir - 1; int blocks_in_y_dir = cells_in_y_dir - 1; // compute gradient strengths per cell int descriptorDataIdx = 0; int cellx = 0; int celly = 0; for (int blockx=0; blockx<blocks_in_x_dir; blockx++) { for (int blocky=0; blocky<blocks_in_y_dir; blocky++) { // 4 cells per block ... for (int cellNr=0; cellNr<4; cellNr++) { // compute corresponding cell nr cellx = blockx; celly = blocky; if (cellNr==1) celly++; if (cellNr==2) cellx++; if (cellNr==3) { cellx++; celly++; } for (int bin=0; bin<gradientBinSize; bin++) { float gradientStrength = descriptorValues[ descriptorDataIdx ]; descriptorDataIdx++; gradientStrengths[celly][cellx][bin] += gradientStrength; } // for (all bins) // note: overlapping blocks lead to multiple updates of this sum! // we therefore keep track how often a cell was updated, // to compute average gradient strengths cellUpdateCounter[celly][cellx]++; } // for (all cells) } // for (all block x pos) } // for (all block y pos) // compute average gradient strengths for (celly=0; celly<cells_in_y_dir; celly++) { for (cellx=0; cellx<cells_in_x_dir; cellx++) { float NrUpdatesForThisCell = (float)cellUpdateCounter[celly][cellx]; // compute average gradient strenghts for each gradient bin direction for (int bin=0; bin<gradientBinSize; bin++) { gradientStrengths[celly][cellx][bin] /= NrUpdatesForThisCell; } } } // draw cells for (celly=0; celly<cells_in_y_dir; celly++) { for (cellx=0; cellx<cells_in_x_dir; cellx++) { int drawX = cellx * cellSize; int drawY = celly * cellSize; int mx = drawX + cellSize/2; int my = drawY + cellSize/2; rectangle(visu, Point((int)(drawX*zoomFac), (int)(drawY*zoomFac)), Point((int)((drawX+cellSize)*zoomFac), (int)((drawY+cellSize)*zoomFac)), Scalar(100,100,100), 1); // draw in each cell all 9 gradient strengths for (int bin=0; bin<gradientBinSize; bin++) { float currentGradStrength = gradientStrengths[celly][cellx][bin]; // no line to draw? if (currentGradStrength==0) continue; float currRad = bin * radRangeForOneBin + radRangeForOneBin/2; float dirVecX = cos( currRad ); float dirVecY = sin( currRad ); float maxVecLen = (float)(cellSize/2.f); float scale = 2.5; // just a visualization scale, to see the lines better // compute line coordinates float x1 = mx - dirVecX * currentGradStrength * maxVecLen * scale; float y1 = my - dirVecY * currentGradStrength * maxVecLen * scale; float x2 = mx + dirVecX * currentGradStrength * maxVecLen * scale; float y2 = my + dirVecY * currentGradStrength * maxVecLen * scale; // draw gradient visualization line(visu, Point((int)(x1*zoomFac),(int)(y1*zoomFac)), Point((int)(x2*zoomFac),(int)(y2*zoomFac)), Scalar(0,255,0), 1); } // for (all bins) } // for (cellx) } // for (celly) // don't forget to free memory allocated by helper data structures! for (int y=0; y<cells_in_y_dir; y++) { for (int x=0; x<cells_in_x_dir; x++) { delete[] gradientStrengths[y][x]; } delete[] gradientStrengths[y]; delete[] cellUpdateCounter[y]; } delete[] gradientStrengths; delete[] cellUpdateCounter; return visu; } // get_hogdescriptor_visu void compute_hog( const vector< Mat > & img_lst, vector< Mat > & gradient_lst, const Size & size ) { HOGDescriptor hog; hog.winSize = size; Mat gray; vector< Point > location; vector< float > descriptors; vector< Mat >::const_iterator img = img_lst.begin(); vector< Mat >::const_iterator end = img_lst.end(); for( ; img != end ; ++img ) { cvtColor( *img, gray, COLOR_BGR2GRAY ); hog.compute( gray, descriptors, Size( 8, 8 ), Size( 0, 0 ), location ); gradient_lst.push_back( Mat( descriptors ).clone() ); #ifdef _DEBUG imshow( "gradient", get_hogdescriptor_visu( img->clone(), descriptors, size ) ); waitKey( 10 ); #endif } } void train_svm( const vector< Mat > & gradient_lst, const vector< int > & labels ) { Mat train_data; convert_to_ml( gradient_lst, train_data ); clog << "Start training..."; Ptr<SVM> svm = SVM::create(); /* Default values to train SVM */ //svm->setCoef0(0.0); //svm->setDegree(3); svm->setTermCriteria(TermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 1000, 1e-3 )); //svm->setGamma(0); svm->setKernel(SVM::LINEAR); //svm->setNu(0.5); svm->setP(0.1); // for EPSILON_SVR, epsilon in loss function? svm->setC(0.01); // From paper, soft classifier svm->setType(SVM::EPS_SVR); // C_SVC; // EPSILON_SVR; // may be also NU_SVR; // do regression task svm->train(train_data, ROW_SAMPLE, Mat(labels)); clog << "...[done]" << endl; svm->save( "my_people_detector.yml" ); } void draw_locations( Mat & img, const vector< Rect > & locations, const Scalar & color ) { if( !locations.empty() ) { vector< Rect >::const_iterator loc = locations.begin(); vector< Rect >::const_iterator end = locations.end(); for( ; loc != end ; ++loc ) { rectangle( img, *loc, color, 2 ); } } } void test_it( const Size & size , const vector< Mat > &pos_lst, const vector< Mat > &full_neg_lst, int n) { HOGDescriptor hog; hog.winSize = size; Scalar reference( 0, 255, 0 ); // Load the trained SVM. Ptr<ml::SVM> svm = StatModel::load<SVM>( "my_people_detector.yml" ); vector< float > hog_detector; get_svm_detector( svm, hog_detector ); hog.setSVMDetector( hog_detector ); for (int i=0; i<n; i++) { Mat img = full_neg_lst[i]; Rect box( rand() % (img.cols - size.width), rand() % (img.rows - size.height), size.width, size.height ); Mat roi(img, box); pos_lst[i].copyTo(roi); vector< Rect > locations; hog.detectMultiScale( img, locations, 0.004 ); Mat draw = img.clone(); rectangle( draw, box, Scalar(0,0,200), 3 ); draw_locations( draw, locations, reference ); int hits = 0; double minD=99999; double maxD=0; for (size_t j=0; j<locations.size(); j++) { /*Rect inter = locations[j] & box; double a = inter.area(); if (a==0) continue; minD = std::min(minD, a); maxD = std::max(maxD, a); hits += (inter.area() > (2*box.area())/3); //&& (abs(locations[j].area()-box.area())<(box.area()/4)); */ Point d1 = box.tl() - locations[j].tl(); Point d2 = box.br() - locations[j].br(); double d = sqrt(d1.x*d1.x + d1.y*d1.y) + sqrt(d2.x*d2.x + d2.y*d2.y); hits += (d < box.area()/20); if (d<minD) minD=d; if (d>=maxD) maxD=d; } cerr << hits << " true pos of " << locations.size() << " " << minD << " " << maxD << endl; imshow("m", draw); if (waitKey(5000) == 27) break; } } void test_it( const Size & size ) { cerr << "press 'd' to toggle the default person detector" << endl; char key = 27; Scalar reference( 0, 255, 0 ); Scalar trained( 0, 0, 255 ); Mat img, draw; Ptr<SVM> svm; HOGDescriptor hog; HOGDescriptor my_hog; my_hog.winSize = size; VideoCapture video; vector< Rect > locations; bool showDefault = false; // Load the trained SVM. svm = StatModel::load<SVM>( "my_people_detector.yml" ); // Set the trained svm to my_hog vector< float > hog_detector; get_svm_detector( svm, hog_detector ); my_hog.setSVMDetector( hog_detector ); // Set the people detector. hog.setSVMDetector( hog.getDefaultPeopleDetector() ); // Open the camera. video.open(0); if( !video.isOpened() ) { cerr << "Unable to open the device 0" << endl; exit( -1 ); } bool end_of_process = false; while( !end_of_process ) { video >> img; if( img.empty() ) break; draw = img.clone(); if (showDefault) { locations.clear(); hog.detectMultiScale( img, locations ); draw_locations( draw, locations, reference ); } locations.clear(); my_hog.detectMultiScale( img, locations ); draw_locations( draw, locations, trained ); imshow( "Video", draw ); key = 255 & (char)waitKey( 10 ); if( 27 == key ) end_of_process = true; if( 'd' == key ) showDefault = ! showDefault; } } int main( int argc, char** argv ) { cv::CommandLineParser parser(argc, argv, "{ help h || show help message }" "{ test t || test only }" "{ pos p || folder with pos images like ~/img/*.png }" "{ neg n || folder with neg images }" "{ steps s |0| step width for neg patches }" "{ mirror m || mirror pos patches }" "{ width W |64| window width }" "{ height H |96| window height }"); if (parser.has("help")) { parser.printMessage(); exit(0); } vector< Mat > pos_lst; vector< Mat > full_neg_lst; vector< Mat > neg_lst; vector< Mat > gradient_lst; vector< int > labels; string pos_dir = parser.get<string>("pos"); string neg_dir = parser.get<string>("neg"); Size windowSize( parser.get<int>("width"), parser.get<int>("height")); int neg_steps = parser.get<int>("steps"); // sample N images from a negative bool doTest = parser.has("test"); bool doMirror = parser.has("mirror"); if( pos_dir.empty() || neg_dir.empty() ) { cout << "Wrong number of parameters." << endl << "Usage: " << argv[0] << " --pos=pos_dir --neg=neg_dir" << endl << "example: " << argv[0] << " --pos=/INRIA_dataset/*.jpg --neg=/my/bgimages/*.png" << endl; exit( -1 ); } load_images( pos_dir, pos_lst ); if (doMirror) { std::vector<Mat> v(pos_lst.begin(), pos_lst.end()); for (Mat m : v) { Mat n; flip(m,n,1); pos_lst.push_back(n); } } labels.assign( pos_lst.size(), +1 ); const unsigned int old = (unsigned int)labels.size(); cout << (doTest?"testing":"training") << " with " << pos_lst.size() << " positive " << windowSize ; load_images( neg_dir, full_neg_lst ); if (!doTest) sample_neg( full_neg_lst, neg_lst, windowSize, neg_steps ); else neg_lst = full_neg_lst; labels.insert( labels.end(), neg_lst.size(), -1 ); cout << " and " << neg_lst.size() << " negative images" << endl; CV_Assert( old < labels.size() ); compute_hog( pos_lst, gradient_lst, windowSize ); compute_hog( neg_lst, gradient_lst, windowSize ); if (!doTest) train_svm( gradient_lst, labels ); //test_it( windowSize ); // change with your parameters test_it( windowSize, pos_lst, full_neg_lst, 100 ); // change with your parameters return 0; }
33.571157
176
0.565792
[ "vector" ]
de8a2d4bd1b9092591df09077a2441709cea1db7
5,788
cpp
C++
engine2d/src/sdl_engine2d.cpp
pakillottk/engine2d
44a1720c35a0c5b01c04457fd404fdd888182980
[ "MIT" ]
null
null
null
engine2d/src/sdl_engine2d.cpp
pakillottk/engine2d
44a1720c35a0c5b01c04457fd404fdd888182980
[ "MIT" ]
null
null
null
engine2d/src/sdl_engine2d.cpp
pakillottk/engine2d
44a1720c35a0c5b01c04457fd404fdd888182980
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include "../include/engine2d/application2d.h" #include "sdl_engine2d.h" #include "engine2d_rect.cpp" #include "engine2d_sprites.cpp" #include "stb_engine2d_text.cpp" #include "engine2d_layer.cpp" using namespace Engine2D; internal void mapRgbaToPixelFormat(SDL_PixelFormat *format, ColorRGBA32 *colors, u32 colorCount, u32 *buffer) { for(u32 i = 0; i < colorCount; ++i) { buffer[i] = SDL_MapRGBA(format, colors[i].r, colors[i].g, colors[i].b, colors[i].a); } } internal SDLContext makeSDLContext(EngineState *state, Size *screenSize) { SDLContext context; SDL_Init(SDL_INIT_VIDEO); context.window = SDL_CreateWindow( state->appTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenSize->width, screenSize->height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE ); context.renderer = SDL_CreateRenderer(context.window, 0, SDL_RENDERER_SOFTWARE); context.format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA32); context.screen = SDL_CreateTexture( context.renderer, context.format->format, SDL_TEXTUREACCESS_STREAMING, screenSize->width, screenSize->height ); context.framebuffer = (ColorRGBA32*)calloc(screenSize->width * screenSize->height, sizeof(ColorRGBA32)); context.screen_buffer = (u32*)calloc(screenSize->width * screenSize->height, sizeof(u32)); return(context); } internal bool8 updateInput(SDLContext *context, Size *screenSize, EngineState *state, UserInput *input) { SDL_Event event; while( SDL_PollEvent(&event) ) { // TODO(pgm) handle well the events and map the user input switch (event.type) { case SDL_QUIT: return(true); break; case SDL_WINDOWEVENT: if( event.window.event == SDL_WINDOWEVENT_RESIZED ) { screenSize->width = event.window.data1; screenSize->height = event.window.data2; // free the buffers free(context->framebuffer); free(context->screen_buffer); SDL_DestroyTexture(context->screen); // realloc buffers context->screen = SDL_CreateTexture( context->renderer, context->format->format, SDL_TEXTUREACCESS_STREAMING, screenSize->width, screenSize->height ); context->framebuffer = (ColorRGBA32*)calloc(screenSize->width * screenSize->height, sizeof(ColorRGBA32)); context->screen_buffer = (u32*)calloc(screenSize->width * screenSize->height, sizeof(u32)); } break; case SDL_KEYDOWN: context->keypressed = true; break; case SDL_KEYUP: context->keypressed = false; break; default: break; } // TODO(pgm) handle well the events and map the user input SDL_Keycode key = event.key.keysym.sym; switch (key) { case SDLK_LEFT: input->buttons.left = context->keypressed; break; case SDLK_UP: input->buttons.up = context->keypressed; break; case SDLK_RIGHT: input->buttons.right = context->keypressed; break; case SDLK_DOWN: input->buttons.down = context->keypressed; break; case SDLK_KP_PLUS: input->buttons.zoomPlus = context->keypressed; break; case SDLK_KP_MINUS: input->buttons.zoomMinus = context->keypressed; break; case SDLK_f: if( context->keypressed ) { SDL_SetWindowFullscreen(context->window, SDL_WINDOW_FULLSCREEN); } break; case SDLK_w: if( context->keypressed ) { SDL_SetWindowFullscreen(context->window, 0); } break; // TODO default: break; } } return(false); } internal void render(SDLContext *context, EngineState *state, Size *screenSize) { // blend the layer pixels into the framebuffer memset(context->framebuffer, 0, sizeof(ColorRGBA32)*screenSize->width*screenSize->height); for(i32 i = 0; i < state->layerCount; ++i) { renderLayer( &state->layers[i], context->framebuffer, screenSize, &state->visibleRegion, state->tilemaps, state->tilemapCount ); } // translate the framebuffer to the real u32 buffer mapRgbaToPixelFormat(context->format, context->framebuffer, screenSize->width * screenSize->height, context->screen_buffer); SDL_UpdateTexture(context->screen, NULL, context->screen_buffer, screenSize->width * sizeof(u32)); SDL_RenderClear(context->renderer); SDL_RenderCopy(context->renderer, context->screen, NULL, NULL); SDL_RenderPresent(context->renderer); } internal void releaseSDLContext(SDLContext *context) { SDL_DestroyWindow(context->window); SDL_DestroyTexture(context->screen); SDL_DestroyRenderer(context->renderer); SDL_FreeFormat(context->format); SDL_Quit(); free(context->framebuffer); free(context->screen_buffer); }
34.248521
136
0.565999
[ "render" ]
de92b2302daf7ada5fe98716028aba3fcc944748
4,259
cpp
C++
actividades/sesion8/jorgegil/main.cpp
GonzaCDZ/Programacion-I
860a39de6b6f337829358881bec5111f9ae25bad
[ "MIT" ]
null
null
null
actividades/sesion8/jorgegil/main.cpp
GonzaCDZ/Programacion-I
860a39de6b6f337829358881bec5111f9ae25bad
[ "MIT" ]
null
null
null
actividades/sesion8/jorgegil/main.cpp
GonzaCDZ/Programacion-I
860a39de6b6f337829358881bec5111f9ae25bad
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <math.h> using namespace std; class Vector{ public: // n = tamaño Vector(int n){ if (n<0){ // cualquier numero de coordenadas mayor que 0 throw string {"Numero de coordenadas incorrecto!"}; } size = n; for (int i=0; i<n; i++){ v.push_back(0); } } void setElement(int indice, float valor){ if(indice<0 || indice>size-1){ throw string {"El numero de coorenadas del vector es incorrecto"}; } v.at(indice) = valor; // v[indice]=valor } float module(){ float suma=0; for(int i=0; i<size; i++){ suma = suma +pow(v.at(i),2); } return sqrt(suma); } Vector unitVector(vector<float> z){ Vector result(size); float m = module(); for (int i=0; i<size; i++){ result.setElement(i, v.at(i)/m); } return result; } int getSize(){ return size; } float getElement(int i){ return v.at(i); } void print(){ cout << "["; for(auto elem:v){ cout << elem << ","; } cout << "]" << endl; } private: vector<float> v; int size; }; Vector add(Vector a, Vector b){ Vector suma(a.getSize()); if(a.getSize() != b.getSize()){ throw string{"Los dos vectores tienen que tener la misma longitud"}; } for(int i=0; i<a.getSize(); i++){ suma.setElement(i, a.getElement(i) + b.getElement(i)); } return suma; } float scalarMultiply(Vector a, Vector b){ if(a.getSize() != b.getSize()){ throw string{"Los dos vectores tienen que tener la misma longitud"}; } float result=0; for (int i=0; i<a.getSize(); i++){ result = result + a.getElement(i)*b.getElement(i); } return result; } bool sonPerpendiculares(Vector a, Vector b){ return (scalarMultiply(a,b) == 0); } float angulo(Vector a, Vector b){ float escalar,m1,m2,angle; if(a.getSize() != 3 || b.getSize() != 3){ throw string{"No se puede obtener el angulo"}; } escalar = scalarMultiply(a,b); m1 = a.module(); m2 = b.module(); angle = acos(escalar/(m1*m2)); return angle; } Vector productoVectorial(Vector a, Vector b){ Vector c(3); if(a.getSize() != 3 || b.getSize() != 3){ throw string{"No se puede reolver el producto vectorial."}; } c.setElement(0,a.getElement(1)*b.getElement(2)-b.getElement(1)*a.getElement(2)); c.setElement(1,a.getElement(2)*b.getElement(0)-b.getElement(2)*a.getElement(0)); c.setElement(2,a.getElement(0)*b.getElement(1)-b.getElement(0)*a.getElement(1)); return c; } int main() { try{ Vector v1(3); cout << "Introduce 3 valores para v1:" << endl; for (int i=0; i<3; i++){ float aux; cin >> aux; v1.setElement(i,aux); } cout << "El vector1 es = "; v1.print(); Vector v2(3); cout << "Introduce 3 valores para v2:" << endl; for (int i=0; i<3; i++){ float aux; cin >> aux; v2.setElement(i,aux); } cout << "El vector2 es = "; v2.print(); //Suma de v1 y v2 Vector v3(3); v3 = add(v1,v2); cout << "La suma de v1 y v2 es = "; v3.print(); //Multiplicacion de v1 y v2 float escalar; escalar = scalarMultiply(v1,v2); cout << "El productor escalar entre v1 y v2 es = "<< escalar << endl; //Para saber si son perpendiculares if(sonPerpendiculares(v1,v2)){ cout << "Los vectores v1 y v2 son perpendiculares!" << endl; }else{ cout << "Los vectores no son perpendiculares :(" << endl; } //Para saber el angulo que forman float angle; angle = angulo(v1,v2); cout << "El angulo que forman los vectores(R) = " << angle << endl; Vector v4(3); v4 = productoVectorial(v1,v2); cout << "El producto verctorial es = "; v4.print(); }catch(string e){ cout << e << endl; return -1; } return 0; }
22.897849
84
0.519606
[ "vector" ]
de92f9a6932bca3c29b21f86a03c2e4e4d2008ec
4,396
cpp
C++
src/lowl_audio_reader_wav.cpp
sebastian-heinz/lowl_audio
a81bd0f7b87f27b0de587bbc126e7b044c1f4dae
[ "MIT" ]
2
2021-04-02T18:55:00.000Z
2021-07-25T20:32:36.000Z
src/lowl_audio_reader_wav.cpp
sebastian-heinz/lowl_audio
a81bd0f7b87f27b0de587bbc126e7b044c1f4dae
[ "MIT" ]
5
2021-04-02T22:09:02.000Z
2021-04-21T03:35:24.000Z
src/lowl_audio_reader_wav.cpp
sebastian-heinz/lowl_audio
a81bd0f7b87f27b0de587bbc126e7b044c1f4dae
[ "MIT" ]
null
null
null
#include "lowl_audio_reader_wav.h" #include "lowl_audio_format.h" //#define DR_WAV_IMPLEMENTATION #include <lowl_dr_imp.h> std::unique_ptr<Lowl::AudioData> Lowl::AudioReaderWav::read(std::unique_ptr<uint8_t[]> p_buffer, size_t p_size, Error &error) { drwav wav; if (!drwav_init_memory(&wav, p_buffer.get(), p_size, nullptr)) { error.set_error(ErrorCode::Error); return nullptr; } /* Cannot use this function for compressed formats. */ if (LowlThirdParty::DrLib::lowl_drwav__is_compressed_format_tag(wav.translatedFormatTag)) { // todo uninit? return nullptr; } uint32_t bytes_per_frame = LowlThirdParty::DrLib::lowl_drwav_get_bytes_per_pcm_frame(&wav); if (bytes_per_frame == 0) { return nullptr; } /* Don't try to read more samples than can potentially fit in the output buffer. */ /* Intentionally uint64 instead of size_t so we can do a check that we're not reading too much on 32-bit builds. */ uint64_t bytes_to_read_test = wav.totalPCMFrameCount * bytes_per_frame; if (bytes_to_read_test > LowlThirdParty::DrLib::lowl_drwav_size_max()) { /* Round the number of bytes to read to a clean frame boundary. */ bytes_to_read_test = (LowlThirdParty::DrLib::lowl_drwav_size_max() / bytes_per_frame) * bytes_per_frame; } /* Doing an explicit check here just to make it clear that we don't want to be attempt to read anything if there's no bytes to read. There *could* be a time where it evaluates to 0 due to overflowing. */ if (bytes_to_read_test == 0) { return nullptr; } size_t bytes_to_read = bytes_to_read_test; std::unique_ptr<uint8_t[]> pcm_frames = std::make_unique<uint8_t[]>(bytes_to_read); size_t bytes_read = drwav_read_raw(&wav, bytes_to_read, pcm_frames.get()); size_t frames_read = bytes_read / bytes_per_frame; SampleRate sample_rate = wav.sampleRate; AudioChannel channel = get_channel(wav.channels); size_t bytes_per_sample = bytes_per_frame / wav.channels; /* Don't try to read more samples than can potentially fit in the output buffer. */ //if (framesToRead * pWav->channels * sizeof(float) > DRWAV_SIZE_MAX) { // framesToRead = DRWAV_SIZE_MAX / sizeof(float) / pWav->channels; //} AudioFormat audio_format = AudioFormat::Unknown; SampleFormat sample_format = SampleFormat::Unknown; switch (wav.translatedFormatTag) { case DR_WAVE_FORMAT_PCM: audio_format = AudioFormat::WAVE_FORMAT_PCM; switch (bytes_per_sample) { case 4: sample_format = SampleFormat::INT_32; break; case 3: sample_format = SampleFormat::INT_24; break; case 2: sample_format = SampleFormat::INT_16; break; case 1: sample_format = SampleFormat::U_INT_8; break; } break; case DR_WAVE_FORMAT_ADPCM: audio_format = AudioFormat::WAVE_FORMAT_ADPCM; break; case DR_WAVE_FORMAT_IEEE_FLOAT: audio_format = AudioFormat::WAVE_FORMAT_IEEE_FLOAT; switch (bytes_per_sample) { case 4: sample_format = SampleFormat::FLOAT_32; break; case 8: sample_format = SampleFormat::FLOAT_64; break; } break; case DR_WAVE_FORMAT_ALAW: audio_format = AudioFormat::WAVE_FORMAT_ALAW; break; case DR_WAVE_FORMAT_MULAW: audio_format = AudioFormat::WAVE_FORMAT_MULAW; break; case DR_WAVE_FORMAT_DVI_ADPCM: audio_format = AudioFormat::WAVE_FORMAT_DVI_ADPCM; break; } std::vector<AudioFrame> audio_frames = read_frames(audio_format, sample_format, channel, pcm_frames, bytes_read, error); if (error.has_error()) { return nullptr; } std::unique_ptr<AudioData> audio_data = std::make_unique<AudioData>(audio_frames, sample_rate, channel); drwav_uninit(&wav); return audio_data; } bool Lowl::AudioReaderWav::support(Lowl::FileFormat p_file_format) const { return p_file_format == FileFormat::WAV; }
36.633333
139
0.635578
[ "vector" ]
de94819a17ec66e8545e23c4af922397bcec8d46
2,724
cpp
C++
window.cpp
phycelot/loo
d7cf0931bbdd68e6ccd3b810835c86155f9a13df
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
window.cpp
phycelot/loo
d7cf0931bbdd68e6ccd3b810835c86155f9a13df
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
window.cpp
phycelot/loo
d7cf0931bbdd68e6ccd3b810835c86155f9a13df
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include <iostream> #include <chrono> #include "window.hpp" namespace s5loo { /* global functions définition */ double getTime() { const auto now{std::chrono::system_clock::now().time_since_epoch()}; return 1e-3*double(std::chrono::duration_cast <std::chrono::milliseconds>(now).count()); } /* member functions définition */ Window::Window(std::string n, double w, double h) : name_{n}, width_{w}, height_{h}, win_{sf::VideoMode{(unsigned int)width_, (unsigned int)height_}, name_.data()} { } void Window::addShape(std::unique_ptr<Shape> shape) { shapes_.emplace_back(std::move(shape)); } void Window::moveAll_(double dt){ for (auto &elem: shapes_) { elem->move(*this,dt); } } void Window::drawAll_(){ for (auto &elem: shapes_) { // elem->draw(*this); elem->draw(win_); } } void Window::left_click(int x,int y){ for (auto &elem: shapes_) { elem->click(win_,x,y); } } void Window::collideAll_() { for (auto &elem: shapes_) { for (auto &elem2: shapes_) { if (!(elem==elem2)) { if(elem->collide(elem2)) {} } } } } void Window::display() { double t=getTime(); while (win_.isOpen()) { win_.clear(sf::Color(100, 100, 100)); double dt = getTime()-t; const double step=1.0/60.0; // target 30 FPS if(dt<step) { sf::sleep(sf::seconds(float(step-dt))); } t+=dt; this->collideAll_(); this->moveAll_(dt); this->drawAll_(); // std::cout << dt << '\n'; win_.display(); sf::Event event; while(win_.pollEvent(event)) { switch (event.type) { case sf::Event::Closed : win_.close(); break; case sf::Event::MouseButtonPressed: if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { std::cout<< "left_button on (" << event.mouseButton.x << "," << event.mouseButton.y << ")\n"; this->left_click(event.mouseButton.x,event.mouseButton.y); } break; case sf::Event::KeyPressed: if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { std::cout<< "LEFT\n"; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { std::cout<< "RIGHT\n"; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { std::cout<< "UP\n"; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { std::cout<< "DOWN\n"; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { std::cout<< "A\n"; } break; default: break; } } } } } // namespace s5loo
24.540541
119
0.535242
[ "shape" ]
de949bfbc21deedbea47ca08c70ac2421ec47e46
2,496
cpp
C++
place_recognition/generate_signatures/src/SC/SC.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
38
2020-07-23T04:33:41.000Z
2022-03-07T03:41:38.000Z
place_recognition/generate_signatures/src/SC/SC.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
null
null
null
place_recognition/generate_signatures/src/SC/SC.cpp
IRVLab/so_dso_place_recognition
c330ee459bf3140fe2c117f0a3ad3535f8cad2ce
[ "Unlicense" ]
10
2020-10-19T01:00:43.000Z
2022-02-21T03:57:57.000Z
#include "SC.h" #include "place_recognition/generate_signatures/src/utils/pts_align.h" #include <cmath> SC::SC(double max_rho) { S_res_inv = numS / (2.0 * M_PI); R_res_inv = numR / max_rho; } unsigned int SC::getSignatureSize() { return numS * numR; } void SC::getSignature( const std::vector<std::pair<Eigen::Vector3d, float>> &pts_clr_raw, Eigen::VectorXd &structure_output, Eigen::VectorXd &intensity_output) { // align points by PCA std::vector<std::pair<Eigen::Vector3d, float>> pts_clr; align_points_PCA(pts_clr_raw, pts_clr); // signature matrix A Eigen::VectorXd pts_count = Eigen::VectorXd::Zero(getSignatureSize()); // pts count Eigen::VectorXd height_lowest = Eigen::VectorXd::Zero(getSignatureSize()); // height lowest Eigen::VectorXd height_highest = Eigen::VectorXd::Zero(getSignatureSize()); // height highest Eigen::VectorXd pts_intensity = Eigen::VectorXd::Zero(getSignatureSize()); // intensity for (int i = 0; i < pts_clr.size(); i++) // loop on pts { // projection to polar coordinate // After PCA, x: up; y: left; z:back double yp = pts_clr[i].first(1); double zp = pts_clr[i].first(2); // get projection bin w.r.t. theta and rho int si = static_cast<int>(floor((atan2(zp, yp) + M_PI) * S_res_inv)); int ri = static_cast<int>(floor(std::sqrt(yp * yp + zp * zp) * R_res_inv)); int idx = si * numR + ri; // PCA moves the points if (idx >= getSignatureSize()) { continue; } if (pts_count(idx) == 0) { pts_intensity(idx) = pts_clr[i].second; height_lowest(idx) = pts_clr[i].first(0); height_highest(idx) = pts_clr[i].first(0); } else { pts_intensity(idx) += double(pts_clr[i].second); height_lowest(idx) = std::min(height_lowest(idx), pts_clr[i].first(0)); height_highest(idx) = std::max(height_highest(idx), pts_clr[i].first(0)); } pts_count(idx)++; } // average intensity float ave_intensity = 0; for (int i = 0; i < pts_clr.size(); i++) { ave_intensity += pts_clr[i].second; } ave_intensity = ave_intensity / pts_clr.size(); // binarize average intensity for each bin for (int i = 0; i < getSignatureSize(); i++) { if (pts_count(i)) { pts_intensity(i) = pts_intensity(i) / pts_count(i); pts_intensity(i) = pts_intensity(i) > ave_intensity ? 1 : 0; } } structure_output = height_highest - height_lowest; // height difference intensity_output = pts_intensity; }
32.415584
79
0.649439
[ "vector" ]
dea39d9ab559c8ae1053367f99292a2e66c7ce91
1,960
cpp
C++
code/p01.cpp
SuperV1234/cppcon2014
32fcf0d263976219f31c3b44bec35e3534dfe4b7
[ "AFL-3.0" ]
72
2015-01-09T19:35:15.000Z
2021-07-02T22:23:25.000Z
code/p01.cpp
vittorioromeo/cppcon2014
32fcf0d263976219f31c3b44bec35e3534dfe4b7
[ "AFL-3.0" ]
1
2017-10-28T10:54:29.000Z
2017-10-29T10:03:23.000Z
code/p01.cpp
vittorioromeo/cppcon2014
32fcf0d263976219f31c3b44bec35e3534dfe4b7
[ "AFL-3.0" ]
23
2015-01-09T19:35:25.000Z
2021-01-14T15:44:32.000Z
// Copyright (c) 2014 Vittorio Romeo // License: MIT License | http://opensource.org/licenses/MIT // http://vittorioromeo.info | vittorio.romeo@outlook.com // Let's begin the development of our arkanoid clone. // We'll start by creating a blank window using the SFML library. // The window will obtain input and display the game graphics. // The <SFML/Graphics.hpp> module is required to deal with graphics. // It also includes common STL classes such as `std::vector` and // the <SFML/Window.hpp> module required for window management. #include <SFML/Graphics.hpp> // Let's define some constants for the window. constexpr unsigned int wndWidth{800}, wndHeight{600}; int main() { // Now we'll create the window. // The class is named `sf::RenderWindow`, and the constructor // requires an `sf::Vector2u` (size of the window), and an // `std::string` (title of the window). sf::RenderWindow window{{wndWidth, wndHeight}, "Arkanoid - 1"}; // Instead of explicitly specifying the `sf::Vector2u` type, // we used the {...} uniform initialization syntax. // We'll also set a limit to the framerate, ensuring that the // game logic will run at a constant speed. window.setFramerateLimit(60); // The next step is "keeping the window alive". // This is where the "game loop" comes into play. // {Info: game loop} while(true) { // Every iteration of this loop is a "frame" of our game. // We'll begin our frame by clearing the window from previously // drawn graphics. window.clear(sf::Color::Black); // Then we'll check the input state. In this case, if the // player presses the "Escape" key, we'll jump outside of the // loop, destroying the window and terminating the program. if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) break; // Show the window's contents. window.display(); } return 0; }
35.636364
72
0.671429
[ "vector" ]
dea4047481434c31ef7e2b2b4e0af5cd1ae6d96e
12,215
cpp
C++
emulador/src/common/ers.cpp
dattebayoonline/Dattebayo
09526566f63e76b9a5ce80f1f4e3d1918e26cf01
[ "DOC", "OLDAP-2.2.1" ]
1
2022-03-24T17:24:12.000Z
2022-03-24T17:24:12.000Z
emulador/src/common/ers.cpp
eluvju/Dattebayo
cc0fc92d8827f4890a8595bc3be0a71ef98767c1
[ "DOC" ]
null
null
null
emulador/src/common/ers.cpp
eluvju/Dattebayo
cc0fc92d8827f4890a8595bc3be0a71ef98767c1
[ "DOC" ]
null
null
null
/*****************************************************************************\ * Copyright (c) rAthena Dev Teams - Licensed under GNU GPL * * For more information, see LICENCE in the main folder * * * * <H1>Entry Reusage System</H1> * * * * There are several root entry managers, each with a different entry size. * * Each manager will keep track of how many instances have been 'created'. * * They will only automatically destroy themselves after the last instance * * is destroyed. * * * * Entries can be allocated from the managers. * * If it has reusable entries (freed entry), it uses one. * * So no assumption should be made about the data of the entry. * * Entries should be freed in the manager they where allocated from. * * Failure to do so can lead to unexpected behaviors. * * * * <H2>Advantages:</H2> * * - The same manager is used for entries of the same size. * * So entries freed in one instance of the manager can be used by other * * instances of the manager. * * - Much less memory allocation/deallocation - program will be faster. * * - Avoids memory fragmentation - program will run better for longer. * * * * <H2>Disadvantages:</H2> * * - Unused entries are almost inevitable - memory being wasted. * * - A manager will only auto-destroy when all of its instances are * * destroyed so memory will usually only be recovered near the end. * * - Always wastes space for entries smaller than a pointer. * * * * WARNING: The system is not thread-safe at the moment. * * * * HISTORY: * * 0.1 - Initial version * * 1.0 - ERS Rework * * * * @version 1.0 - ERS Rework * * @author GreenBox @ rAthena Project * * @encoding US-ASCII * * @see common#ers.hpp * \*****************************************************************************/ #include "ers.hpp" #include <stdlib.h> #include <string.h> #include "cbasetypes.hpp" #include "malloc.hpp" // CREATE, RECREATE, aMalloc, aFree #include "nullpo.hpp" #include "showmsg.hpp" // ShowMessage, ShowError, ShowFatalError, CL_BOLD, CL_NORMAL #ifndef DISABLE_ERS #define ERS_BLOCK_ENTRIES 2048 struct ers_list { struct ers_list *Next; }; struct ers_instance_t; typedef struct ers_cache { // Allocated object size, including ers_list size unsigned int ObjectSize; // Number of ers_instances referencing this int ReferenceCount; // Reuse linked list struct ers_list *ReuseList; // Memory blocks array unsigned char **Blocks; // Max number of blocks unsigned int Max; // Free objects count unsigned int Free; // Used blocks count unsigned int Used; // Objects in-use count unsigned int UsedObjs; // Default = ERS_BLOCK_ENTRIES, can be adjusted for performance for individual cache sizes. unsigned int ChunkSize; // Misc options, some options are shared from the instance enum ERSOptions Options; // Linked list struct ers_cache *Next, *Prev; } ers_cache_t; struct ers_instance_t { // Interface to ERS struct eri VTable; // Name, used for debugging purposes char *Name; // Misc options enum ERSOptions Options; // Our cache ers_cache_t *Cache; // Count of objects in use, used for detecting memory leaks unsigned int Count; struct ers_instance_t *Next, *Prev; }; // Array containing a pointer for all ers_cache structures static ers_cache_t *CacheList = NULL; static struct ers_instance_t *InstanceList = NULL; /** * @param Options the options from the instance seeking a cache, we use it to give it a cache with matching configuration **/ static ers_cache_t *ers_find_cache(unsigned int size, enum ERSOptions Options) { ers_cache_t *cache; for (cache = CacheList; cache; cache = cache->Next) if ( cache->ObjectSize == size && cache->Options == ( Options & ERS_CACHE_OPTIONS ) ) return cache; CREATE(cache, ers_cache_t, 1); cache->ObjectSize = size; cache->ReferenceCount = 0; cache->ReuseList = NULL; cache->Blocks = NULL; cache->Free = 0; cache->Used = 0; cache->UsedObjs = 0; cache->Max = 0; cache->ChunkSize = ERS_BLOCK_ENTRIES; cache->Options = (enum ERSOptions)(Options & ERS_CACHE_OPTIONS); if (CacheList == NULL) { CacheList = cache; } else { cache->Next = CacheList; cache->Next->Prev = cache; CacheList = cache; CacheList->Prev = NULL; } return cache; } static void ers_free_cache(ers_cache_t *cache, bool remove) { unsigned int i; for (i = 0; i < cache->Used; i++) aFree(cache->Blocks[i]); if (cache->Next) cache->Next->Prev = cache->Prev; if (cache->Prev) cache->Prev->Next = cache->Next; else CacheList = cache->Next; aFree(cache->Blocks); aFree(cache); } static void *ers_obj_alloc_entry(ERS *self) { struct ers_instance_t *instance = (struct ers_instance_t *)self; void *ret; if (instance == NULL) { ShowError("ers_obj_alloc_entry: NULL object, aborting entry freeing.\n"); return NULL; } if (instance->Cache->ReuseList != NULL) { ret = (void *)((unsigned char *)instance->Cache->ReuseList + sizeof(struct ers_list)); instance->Cache->ReuseList = instance->Cache->ReuseList->Next; } else if (instance->Cache->Free > 0) { instance->Cache->Free--; ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)]; } else { if (instance->Cache->Used == instance->Cache->Max) { instance->Cache->Max = (instance->Cache->Max * 4) + 3; RECREATE(instance->Cache->Blocks, unsigned char *, instance->Cache->Max); } CREATE(instance->Cache->Blocks[instance->Cache->Used], unsigned char, instance->Cache->ObjectSize * instance->Cache->ChunkSize); instance->Cache->Used++; instance->Cache->Free = instance->Cache->ChunkSize -1; ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)]; } instance->Count++; instance->Cache->UsedObjs++; return ret; } static void ers_obj_free_entry(ERS *self, void *entry) { struct ers_instance_t *instance = (struct ers_instance_t *)self; struct ers_list *reuse = (struct ers_list *)((unsigned char *)entry - sizeof(struct ers_list)); if (instance == NULL) { ShowError("ers_obj_free_entry: NULL object, aborting entry freeing.\n"); return; } else if (entry == NULL) { ShowError("ers_obj_free_entry: NULL entry, nothing to free.\n"); return; } if( instance->Cache->Options & ERS_OPT_CLEAN ) memset((unsigned char*)reuse + sizeof(struct ers_list), 0, instance->Cache->ObjectSize - sizeof(struct ers_list)); reuse->Next = instance->Cache->ReuseList; instance->Cache->ReuseList = reuse; instance->Count--; instance->Cache->UsedObjs--; } static size_t ers_obj_entry_size(ERS *self) { struct ers_instance_t *instance = (struct ers_instance_t *)self; if (instance == NULL) { ShowError("ers_obj_entry_size: NULL object, aborting entry freeing.\n"); return 0; } return instance->Cache->ObjectSize; } static void ers_obj_destroy(ERS *self) { struct ers_instance_t *instance = (struct ers_instance_t *)self; if (instance == NULL) { ShowError("ers_obj_destroy: NULL object, aborting entry freeing.\n"); return; } if (instance->Count > 0) if (!(instance->Options & ERS_OPT_CLEAR)) ShowWarning("Memory leak detected at ERS '%s', %d objects not freed.\n", instance->Name, instance->Count); if (--instance->Cache->ReferenceCount <= 0) ers_free_cache(instance->Cache, true); if (instance->Next) instance->Next->Prev = instance->Prev; if (instance->Prev) instance->Prev->Next = instance->Next; else InstanceList = instance->Next; if( instance->Options & ERS_OPT_FREE_NAME ) aFree(instance->Name); aFree(instance); } void ers_cache_size(ERS *self, unsigned int new_size) { struct ers_instance_t *instance = (struct ers_instance_t *)self; nullpo_retv(instance); if( !(instance->Cache->Options&ERS_OPT_FLEX_CHUNK) ) { ShowWarning("ers_cache_size: '%s' has adjusted its chunk size to '%d', however ERS_OPT_FLEX_CHUNK is missing!\n",instance->Name,new_size); } instance->Cache->ChunkSize = new_size; } ERS *ers_new(uint32 size, const char *name, enum ERSOptions options) { struct ers_instance_t *instance; CREATE(instance,struct ers_instance_t, 1); size += sizeof(struct ers_list); #if ERS_ALIGNED > 1 // If it's aligned to 1-byte boundaries, no need to bother. if (size % ERS_ALIGNED) size += ERS_ALIGNED - size % ERS_ALIGNED; #endif instance->VTable.alloc = ers_obj_alloc_entry; instance->VTable.free = ers_obj_free_entry; instance->VTable.entry_size = ers_obj_entry_size; instance->VTable.destroy = ers_obj_destroy; instance->VTable.chunk_size = ers_cache_size; instance->Name = ( options & ERS_OPT_FREE_NAME ) ? (char *)aStrdup(name) : (char *)name; instance->Options = options; instance->Cache = ers_find_cache(size,instance->Options); instance->Cache->ReferenceCount++; if (InstanceList == NULL) { InstanceList = instance; } else { instance->Next = InstanceList; instance->Next->Prev = instance; InstanceList = instance; InstanceList->Prev = NULL; } instance->Count = 0; return &instance->VTable; } void ers_report(void) { ers_cache_t *cache; unsigned int cache_c = 0, blocks_u = 0, blocks_a = 0, memory_b = 0, memory_t = 0; for (cache = CacheList; cache; cache = cache->Next) { cache_c++; ShowMessage(CL_BOLD"[ERS Cache of size '" CL_NORMAL "" CL_WHITE "%u" CL_NORMAL "" CL_BOLD "' report]\n" CL_NORMAL, cache->ObjectSize); ShowMessage("\tinstances : %u\n", cache->ReferenceCount); ShowMessage("\tblocks in use : %u/%u\n", cache->UsedObjs, cache->UsedObjs+cache->Free); ShowMessage("\tblocks unused : %u\n", cache->Free); ShowMessage("\tmemory in use : %.2f MB\n", cache->UsedObjs == 0 ? 0. : (double)((cache->UsedObjs * cache->ObjectSize)/1024)/1024); ShowMessage("\tmemory allocated : %.2f MB\n", (cache->Free+cache->UsedObjs) == 0 ? 0. : (double)(((cache->UsedObjs+cache->Free) * cache->ObjectSize)/1024)/1024); blocks_u += cache->UsedObjs; blocks_a += cache->UsedObjs + cache->Free; memory_b += cache->UsedObjs * cache->ObjectSize; memory_t += (cache->UsedObjs+cache->Free) * cache->ObjectSize; } ShowInfo("ers_report: '" CL_WHITE "%u" CL_NORMAL "' caches in use\n",cache_c); ShowInfo("ers_report: '" CL_WHITE "%u" CL_NORMAL "' blocks in use, consuming '" CL_WHITE "%.2f MB" CL_NORMAL "'\n",blocks_u,(double)((memory_b)/1024)/1024); ShowInfo("ers_report: '" CL_WHITE "%u" CL_NORMAL "' blocks total, consuming '" CL_WHITE "%.2f MB" CL_NORMAL "' \n",blocks_a,(double)((memory_t)/1024)/1024); } /** * Call on shutdown to clear remaining entries **/ void ers_final(void) { struct ers_instance_t *instance = InstanceList, *next; while( instance ) { next = instance->Next; ers_obj_destroy((ERS*)instance); instance = next; } } #endif
33.192935
165
0.608678
[ "object" ]
dea5336925222c7ca23e8f76c11a42da02f95587
11,833
cpp
C++
SOGM-3D-2D-Net/cpp_wrappers/cpp_slam/wrap_slam.cpp
liuxinren456852/Deep-Collison-Checker
1d96415fd865361e22a6f25547707c47628dcfbe
[ "MIT" ]
7
2021-09-09T15:03:36.000Z
2022-03-15T16:33:33.000Z
SOGM-3D-2D-Net/cpp_wrappers/cpp_slam/wrap_slam.cpp
liuxinren456852/Deep-Collison-Checker
1d96415fd865361e22a6f25547707c47628dcfbe
[ "MIT" ]
null
null
null
SOGM-3D-2D-Net/cpp_wrappers/cpp_slam/wrap_slam.cpp
liuxinren456852/Deep-Collison-Checker
1d96415fd865361e22a6f25547707c47628dcfbe
[ "MIT" ]
1
2021-09-10T01:46:50.000Z
2021-09-10T01:46:50.000Z
#include <Python.h> #include <numpy/arrayobject.h> #include "../src/pointmap_slam/pointmap_slam.h" #include <string> // docstrings for our module // ************************* static char module_docstring[] = "This module provides a method to compute a Pointmap SLAM"; static char map_sim_sequence_docstring[] = "Method that calls the SLAM on a list of frames"; //static char TODO_docstring[] = "Method that ???"; // Declare the functions // ********************* static PyObject* map_sim_sequence(PyObject* self, PyObject* args, PyObject* keywds); //static PyObject* TODO(PyObject* self, PyObject* args, PyObject* keywds); // Specify the members of the module // ********************************* static PyMethodDef module_methods[] = { { "map_sim_sequence", (PyCFunction)map_sim_sequence, METH_VARARGS | METH_KEYWORDS, map_sim_sequence_docstring }, //{ "TODO", (PyCFunction)TODO, METH_VARARGS | METH_KEYWORDS, TODO_docstring }, {NULL, NULL, 0, NULL} }; // Initialize the module // ********************* static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "pointmap_slam", // m_name module_docstring, // m_doc -1, // m_size module_methods, // m_methods NULL, // m_reload NULL, // m_traverse NULL, // m_clear NULL, // m_free }; PyMODINIT_FUNC PyInit_pointmap_slam(void) { import_array(); return PyModule_Create(&moduledef); } // Definition of the map_sim_sequence method // ***************************************** static PyObject* map_sim_sequence(PyObject* self, PyObject* args, PyObject* keywds) { // Manage inputs // ************* // Args containers const char* fnames_str; PyObject* ftimes_obj = NULL; PyObject* gt_H_obj = NULL; PyObject* gt_t_obj = NULL; PyObject* init_points_obj = NULL; PyObject* init_normals_obj = NULL; PyObject* init_scores_obj = NULL; PyObject* velo_base_obj = NULL; PyObject* odom_obj = NULL; SLAM_params slam_params; const char* save_path; // Keywords containers static char* kwlist[] = { (char*)"frame_names", (char*)"frame_times", (char*)"gt_poses", (char*)"gt_times", (char*)"save_path", (char*)"init_points", (char*)"init_normals", (char*)"init_scores", (char*)"map_voxel_size", (char*)"frame_voxel_size", (char*)"motion_distortion", (char*)"filtering", (char*)"verbose_time", (char*)"icp_samples", (char*)"icp_pairing_dist", (char*)"icp_planar_dist", (char*)"icp_avg_steps", (char*)"icp_max_iter", (char*)"H_velo_base", (char*)"odom_H", NULL }; // Parse the input if (!PyArg_ParseTupleAndKeywords(args, keywds, "sOOOsOOO|$ffppflffllOO", kwlist, &fnames_str, &ftimes_obj, &gt_H_obj, &gt_t_obj, &save_path, &init_points_obj, &init_normals_obj, &init_scores_obj, &slam_params.map_voxel_size, &slam_params.frame_voxel_size, &slam_params.motion_distortion, &slam_params.filtering, &slam_params.verbose_time, &slam_params.icp_params.n_samples, &slam_params.icp_params.max_pairing_dist, &slam_params.icp_params.max_planar_dist, &slam_params.icp_params.avg_steps, &slam_params.icp_params.max_iter, &velo_base_obj, &odom_obj)) { PyErr_SetString(PyExc_RuntimeError, "Error parsing arguments"); return NULL; } slam_params.icp_params.motion_distortion = slam_params.motion_distortion; // Interpret the input objects as numpy arrays. PyObject* ftimes_array = PyArray_FROM_OTF(ftimes_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject* gt_H_array = PyArray_FROM_OTF(gt_H_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject* gt_t_array = PyArray_FROM_OTF(gt_t_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject* init_points_array = PyArray_FROM_OTF(init_points_obj, NPY_FLOAT, NPY_IN_ARRAY); PyObject* init_normals_array = PyArray_FROM_OTF(init_normals_obj, NPY_FLOAT, NPY_IN_ARRAY); PyObject* init_scores_array = PyArray_FROM_OTF(init_scores_obj, NPY_FLOAT, NPY_IN_ARRAY); PyObject* velo_base_array = PyArray_FROM_OTF(velo_base_obj, NPY_DOUBLE, NPY_IN_ARRAY); // Check if odometry is given bool use_odom = true; PyObject* odom_array = NULL; if (odom_obj == NULL) use_odom = false; else odom_array = PyArray_FROM_OTF(odom_obj, NPY_DOUBLE, NPY_IN_ARRAY); // Data verification // ***************** vector<bool> conditions; vector<string> error_messages; // Verify data was load correctly. conditions.push_back(ftimes_array == NULL); error_messages.push_back("Error converting frame times to numpy arrays of type int64"); conditions.push_back(gt_H_array == NULL); error_messages.push_back("Error converting gt poses to numpy arrays of type float64 (double)"); conditions.push_back(gt_t_array == NULL); error_messages.push_back("Error converting gt times to numpy arrays of type int64"); conditions.push_back(init_points_array == NULL); error_messages.push_back("Error converting initial map points to numpy arrays of type float32"); conditions.push_back(init_normals_array == NULL); error_messages.push_back("Error converting initial map normals to numpy arrays of type float32"); conditions.push_back(init_scores_array == NULL); error_messages.push_back("Error converting initial map scores to numpy arrays of type float32"); conditions.push_back(velo_base_array == NULL); error_messages.push_back("Error converting H_velo_base to numpy arrays of type double"); conditions.push_back(use_odom && (odom_array == NULL)); error_messages.push_back("Error converting odom_H to numpy arrays of type double"); // Verify conditions for (size_t i = 0; i < conditions.size(); i++) { if (conditions[i]) { Py_XDECREF(ftimes_array); Py_XDECREF(gt_H_array); Py_XDECREF(gt_t_array); Py_XDECREF(init_points_array); Py_XDECREF(init_normals_array); Py_XDECREF(init_scores_array); Py_XDECREF(velo_base_array); Py_XDECREF(odom_array); PyErr_SetString(PyExc_RuntimeError, error_messages[i].c_str()); return NULL; } } // Check that the input array respect the dims conditions.push_back((int)PyArray_NDIM(ftimes_array) != 1); error_messages.push_back("Error, wrong dimensions : ftimes.shape is not (N1,)"); conditions.push_back((int)PyArray_NDIM(gt_H_array) != 3 || (int)PyArray_DIM(gt_H_array, 1) != 4 || (int)PyArray_DIM(gt_H_array, 2) != 4); error_messages.push_back("Error, wrong dimensions : weights.shape is not (N2, 4, 4)"); conditions.push_back((int)PyArray_NDIM(gt_t_array) != 1); error_messages.push_back("Error, wrong dimensions : map_points.shape is not (N2,)"); conditions.push_back((int)PyArray_NDIM(init_points_array) != 2 || (int)PyArray_DIM(init_points_array, 1) != 3); error_messages.push_back("Error, wrong dimensions : init_points.shape is not (N3, 3)"); conditions.push_back((int)PyArray_NDIM(init_normals_array) != 2 || (int)PyArray_DIM(init_normals_array, 1) != 3); error_messages.push_back("Error, wrong dimensions : init_normals.shape is not (N3, 3)"); conditions.push_back((int)PyArray_NDIM(init_scores_array) != 1); error_messages.push_back("Error, wrong dimensions : init_scores.shape is not (N3,)"); conditions.push_back((int)PyArray_NDIM(velo_base_array) != 2 || (int)PyArray_DIM(velo_base_array, 0) != 4 || (int)PyArray_DIM(velo_base_array, 1) != 4); error_messages.push_back("Error, wrong dimensions : H_velo_base.shape is not (4, 4)"); conditions.push_back(use_odom && ((int)PyArray_NDIM(odom_array) != 3 || (int)PyArray_DIM(odom_array, 1) != 4 || (int)PyArray_DIM(odom_array, 2) != 4)); error_messages.push_back("Error, wrong dimensions : odom_H.shape is not (N1, 4, 4)"); // Check number of points size_t N_f = (size_t)PyArray_DIM(ftimes_array, 0); size_t N_gt = (size_t)PyArray_DIM(gt_t_array, 0); conditions.push_back((size_t)PyArray_DIM(gt_H_array, 0) != N_gt); error_messages.push_back("Error: number of gt_H not equal to the number of gt_t"); conditions.push_back(use_odom && ((size_t)PyArray_DIM(odom_array, 0) != N_f)); error_messages.push_back("Error: number of odom_H not equal to the number of frames"); // Dimension of the features size_t N_map = (size_t)PyArray_DIM(init_points_array, 0); conditions.push_back((size_t)PyArray_DIM(init_normals_array, 0) != N_map); error_messages.push_back("Error: number of map normals not equal to the number of map points"); conditions.push_back((size_t)PyArray_DIM(init_scores_array, 0) != N_map); error_messages.push_back("Error: number of map scores not equal to the number of map points"); // Verify conditions for (size_t i = 0; i < conditions.size(); i++) { if (conditions[i]) { Py_XDECREF(ftimes_array); Py_XDECREF(gt_H_array); Py_XDECREF(gt_t_array); Py_XDECREF(init_points_array); Py_XDECREF(init_normals_array); Py_XDECREF(init_scores_array); Py_XDECREF(velo_base_array); Py_XDECREF(odom_array); PyErr_SetString(PyExc_RuntimeError, error_messages[i].c_str()); return NULL; } } // Call the C++ function // ********************* // Convert frame names to string string frame_names(fnames_str); // Convert data to std vectors vector<double> f_t((double*)PyArray_DATA(ftimes_array), (double*)PyArray_DATA(ftimes_array) + N_f); vector<double> gt_t((double*)PyArray_DATA(gt_t_array), (double*)PyArray_DATA(gt_t_array) + N_gt); vector<double> gt_H_vec((double*)PyArray_DATA(gt_H_array), (double*)PyArray_DATA(gt_H_array) + N_gt * 4 * 4); vector<PointXYZ> init_points((PointXYZ*)PyArray_DATA(init_points_array), (PointXYZ*)PyArray_DATA(init_points_array) + N_map); vector<PointXYZ> init_normals((PointXYZ*)PyArray_DATA(init_normals_array), (PointXYZ*)PyArray_DATA(init_normals_array) + N_map); vector<float> init_scores((float*)PyArray_DATA(init_scores_array), (float*)PyArray_DATA(init_scores_array) + N_map); vector<double> velo_base_vec((double*)PyArray_DATA(velo_base_array), (double*)PyArray_DATA(velo_base_array) + 4 * 4); vector<double> odom_H_vec; if (use_odom) odom_H_vec = vector<double>((double*)PyArray_DATA(odom_array), (double*)PyArray_DATA(odom_array) + N_f * 4 * 4); else odom_H_vec = vector<double>(N_f * 4 * 4, 0.0); // Convert gt poses to Eigen matrices Eigen::Map<Eigen::MatrixXd> gt_H_T((double*)gt_H_vec.data(), 4, N_gt * 4); Eigen::MatrixXd gt_H = gt_H_T.transpose(); // Convert odometry to Eigen matrices Eigen::Map<Eigen::MatrixXd> odom_H_T((double*)odom_H_vec.data(), 4, N_f * 4); Eigen::MatrixXd odom_H = odom_H_T.transpose(); // Convert H_velo_base to Eigen matrices Eigen::Map<Eigen::Matrix4d> H_velo_base((double*)velo_base_vec.data(), 4, 4); slam_params.H_velo_base = H_velo_base.transpose(); // Call main function Eigen::MatrixXd res_H; res_H = call_on_sim_sequence(frame_names, f_t, gt_H, gt_t, odom_H, init_points, init_normals, init_scores, slam_params, string(save_path)); // Manage outputs // ************** // Dimension of output containers npy_intp* H_dims = new npy_intp[2]; H_dims[0] = 4; H_dims[1] = 4 * N_f; // Create output array PyObject* res_H_obj = PyArray_SimpleNew(2, H_dims, NPY_DOUBLE); // cout << res_H.block(0, 0, 4, 4) << endl; // cout << res_H.block(4, 0, 4, 4) << endl; //// Fill transform array with values size_t size_in_bytes = N_f * 4 * 4 * sizeof(double); memcpy(PyArray_DATA(res_H_obj), res_H.data(), size_in_bytes); // Merge results PyObject* ret = Py_BuildValue("N", res_H_obj); // Clean up // ******** Py_XDECREF(ftimes_array); Py_XDECREF(gt_H_array); Py_XDECREF(gt_t_array); Py_XDECREF(init_points_array); Py_XDECREF(init_normals_array); Py_XDECREF(init_scores_array); Py_XDECREF(velo_base_array); Py_XDECREF(odom_array); return ret; }
38.669935
154
0.706837
[ "shape", "vector", "transform" ]
dea6ac0a57fe2062da219a88ee1b703243fcd9d8
1,278
cpp
C++
test/steiner_tree/dreyfus_wagner_long_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/steiner_tree/dreyfus_wagner_long_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/steiner_tree/dreyfus_wagner_long_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) // // 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) //======================================================================= /** * @file dreyfus_wagner_long_test.cpp * @brief * @author Maciej Andrejczuk * @version 1.0 * @date 2013-08-04 */ #include "test_utils/logger.hpp" #include "test_utils/read_steinlib.hpp" #include "test_utils/test_result_check.hpp" #include "paal/steiner_tree/dreyfus_wagner.hpp" #include <boost/test/unit_test.hpp> #include <boost/range/adaptor/sliced.hpp> #include <vector> #include <fstream> using namespace paal; BOOST_AUTO_TEST_CASE(dreyfus_wagner_steinlib_long_test) { std::vector<steiner_tree_test_with_metric> data; LOGLN("READING INPUT..."); read_steinlib_tests(data); // Smaller tests only for (auto const &test : data | boost::adaptors::sliced(0, 50)) { LOGLN("TEST " << test.test_name); auto dw = paal::make_dreyfus_wagner( test.metric, test.terminals, test.steiner_points); dw.solve(); int res = dw.get_cost(); BOOST_CHECK_EQUAL(res, test.optimal); } }
29.045455
73
0.616588
[ "vector" ]
dea9fd0f549ad56398dfc93f731c505657daed8a
875
hpp
C++
options/connector.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
1
2021-06-14T09:00:47.000Z
2021-06-14T09:00:47.000Z
options/connector.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
null
null
null
options/connector.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
null
null
null
#pragma once #include <map> #include <vector> #include <QString> #include <QMutex> #include <QMutexLocker> #include "export.hpp" namespace options { class base_value; namespace detail { class OPENTRACK_OPTIONS_EXPORT connector { friend class ::options::base_value; std::map<QString, std::vector<const base_value*>> connected_values; void on_bundle_destructed(const QString& name, const base_value* val); void on_bundle_created(const QString& name, const base_value* val); protected: void notify_values(const QString& name) const; void notify_all_values() const; virtual QMutex* get_mtx() = 0; public: connector(); virtual ~connector(); connector(const connector&) = default; connector& operator=(const connector&) = default; connector(connector&&) = default; connector& operator=(connector&&) = default; }; } }
20.348837
74
0.713143
[ "vector" ]