hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a97d92a56aa7408d7e8a5b17ee7f970b0be21218
5,243
hpp
C++
tests/test_utilities.hpp
Felix-Rm/iac
59bfc7e859d4cc0b923c75dd34316ae2fafd9097
[ "BSD-2-Clause" ]
null
null
null
tests/test_utilities.hpp
Felix-Rm/iac
59bfc7e859d4cc0b923c75dd34316ae2fafd9097
[ "BSD-2-Clause" ]
null
null
null
tests/test_utilities.hpp
Felix-Rm/iac
59bfc7e859d4cc0b923c75dd34316ae2fafd9097
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "ftest/test_logging.hpp" #include "iac.hpp" #define TEST_UTILS_CREATE_NODE_WITH_ENDPOINT(node_name, ep_name, name, id) \ iac::LocalNode node_name{}; \ iac::LocalEndpoint ep_name{id, name}; \ node_name.add_local_endpoint(ep_name); #define TEST_UTILS_CONNECT_NODES_WITH_LOOPBACK(tr_name, node1_name, node2_name) \ iac::LoopbackConnectionPackage<iac::LoopbackConnection> tr_name; \ tr_name.connect(node1_name, node2_name) class TestUtilities { private: static bool all_nodes_connected() { return true; }; static void update_all_nodes(){}; public: template <typename F, typename... Args> static void update_til_connected(F after_update, iac::LocalNode& node, Args&... nodes) { while (!all_nodes_connected(node, nodes...)) { update_all_nodes(node, nodes...); after_update(); } }; template <typename... Args> static bool all_nodes_connected(const iac::LocalNode& node, const Args&... nodes) { return node.all_routes_connected() && all_nodes_connected(nodes...); } template <typename... Args> static void update_all_nodes(iac::LocalNode& node, Args&... nodes) { node.update(); update_all_nodes(nodes...); } static bool test_networks_equal(const std::vector<iac::LocalNode*>& nodes) { for (const auto* node : nodes) { for (const auto* compare_node : nodes) { if (node == compare_node) continue; for (const auto& entry : node->network().node_mapping()) { auto node_res = compare_node->network().node_mapping().find(entry.first); if (node_res == compare_node->network().node_mapping().end()) { TestLogging::test_printf("node %d in node %d not in compare_node listing %d", entry.first, node->id(), compare_node->id()); return false; } const iac::Node& node_result = node_res->second.element(); for (auto ep_id : entry.second.element().endpoints()) { auto ep_res = node_result.endpoints().find(ep_id); if (ep_res == node_result.endpoints().end()) { TestLogging::test_printf("ep %d has mismatch in ep between node %d not and compare_node %d", ep_id, node->id(), compare_node->id()); return false; } } for (auto tr_id : entry.second.element().routes()) { auto tr_res = node_result.routes().find(tr_id); if (tr_res == node_result.routes().end()) { TestLogging::test_printf("tr %d has mismatch in tr between node %d not and compare_node %d", tr_id, node->id(), compare_node->id()); return false; } } } for (const auto& entry : node->network().endpoint_mapping()) { auto ep_res = compare_node->network().endpoint_mapping().find(entry.first); if (ep_res == compare_node->network().endpoint_mapping().end()) return false; if (entry.second.element().node() != ep_res->second.element().node()) { TestLogging::test_printf("node %d not and compare_node %d have mismatch in ep %d", node->id(), compare_node->id(), entry.first); return false; } } for (const auto& entry : node->network().route_mapping()) { auto tr_res = compare_node->network().route_mapping().find(entry.first); if (tr_res == compare_node->network().route_mapping().end()) { TestLogging::test_printf("node %d not and compare_node %d have mismatch tr %d", node->id(), compare_node->id(), entry.first); return false; } auto a_min_node = std::min(entry.second.element().node1(), entry.second.element().node2()); auto a_max_node = std::max(entry.second.element().node1(), entry.second.element().node2()); auto b_min_node = std::min(tr_res->second.element().node1(), tr_res->second.element().node2()); auto b_max_node = std::max(tr_res->second.element().node1(), tr_res->second.element().node2()); if (a_min_node != b_min_node) { TestLogging::test_printf("node %d not and compare_node %d have mismatch in node %d != %d", node->id(), compare_node->id(), a_min_node, b_min_node); return false; } if (a_max_node != b_max_node) { TestLogging::test_printf("node %d not and compare_node %d have mismatch in node %d", node->id(), compare_node->id(), a_max_node, b_max_node); return false; } } } } return true; } };
47.663636
171
0.536716
Felix-Rm
a97f0873aa383a1ce0cb699ac69f6bab0d48c4f5
505
cpp
C++
cppprimer_anwser/8.9.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
cppprimer_anwser/8.9.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
cppprimer_anwser/8.9.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <vector> int main( int argv, char *argc[] ) { using namespace std; string tmpLine; ifstream infile { argc[1] }; vector<string> vline; while( getline(infile, tmpLine ) ) { vline.push_back(tmpLine); tmpLine.clear(); } for( auto itr = vline.begin(); itr != vline.end(); itr++) { istringstream line { *itr }; std::string tmpWord; while( line >> tmpWord ){ std::cout <<"This is word:" << tmpWord << std::endl; } } }
18.703704
60
0.631683
iusyu
a97f1c4fe24c012b0c6a95f403c693fcae040720
62
cpp
C++
unit_test/threads/Test_Threads_Blas1_team_scal.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
156
2017-03-01T23:38:10.000Z
2022-03-27T21:28:03.000Z
unit_test/threads/Test_Threads_Blas1_team_scal.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
1,257
2017-03-03T15:25:16.000Z
2022-03-31T19:46:09.000Z
unit_test/threads/Test_Threads_Blas1_team_scal.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
76
2017-03-01T17:03:59.000Z
2022-03-03T21:04:41.000Z
#include<Test_Threads.hpp> #include<Test_Blas1_team_scal.hpp>
20.666667
34
0.83871
dialecticDolt
a981dc23d05ebe3dbbb4942ae81b9a4f5361926b
3,366
cpp
C++
misc/lcs.cpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
misc/lcs.cpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
misc/lcs.cpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
/* LCS - Longest Common Substring * between two strings. */ #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> void dump_array(int A[], int size) { for (int i=0; i<size; ++i) printf("%i\t", A[i]); printf("\n"); return; } void dump_array2(char A[], int size) { for (int i=0; i<size; ++i) printf("%c\t", A[i]); printf("\n"); return; } void dump_matrix(int** A, int m, int n) { for(int j=0; j<n; ++j) printf ("\t%i",j); printf("\n"); for (int i=0; i<m; ++i){ printf ("%i\t",i); for(int j=0; j<n; ++j) printf("%i\t", A[i][j]); printf("\n"); } printf("\n"); return; } /* Find the occurrence of the first longest common substring between X and Y. */ void lcs(char *X, int m, char *Y, int n) { int** C = new int*[m+1]; for (int i=0; i<m+1; ++i) C[i] = new int[n+1]; for (int i=0; i<m+1; ++i) C[i][0]=0; for (int j=1; j<n+1; ++j) C[0][j]=0; int zi=0; // lcs start int zl=0; // lcs length for (int i=1; i<m+1; ++i) { for (int j=1; j<n+1; ++j) { if (X[i-1]==Y[j-1]) { C[i][j] = C[i-1][j-1]+1; if (C[i][j]>zl) { zl = C[i][j]; zi = (i-1)-(zl-1); } } else { C[i][j] = 0; } } } printf("\n"); dump_matrix(C,m+1,n+1); if (zl>0) dump_array2(X+zi, zl); } /* Find the occurrence of the first longest common substring between X and Y. You don't actually need the whole matrix m+1 * n+1, you just need the last two rows. Don't use matrix m+1 * n+1, use just 2 * n+1. */ void lcs2(char *X, int m, char *Y, int n, size_t &lcs_start, size_t &lcs_len) { // Init matrix to save already solved sub-problems. // We only need the last two row of a (m+1) * (n+1) matrix. // Allocate memory. int** C = new int*[2]; for (int i=0; i<2; ++i) C[i] = new int[n+1]; // Init first column to zero. for (int i=0; i<2; ++i) C[i][0]=0; // Init first row to zero. for (int j=1; j<n+1; ++j) C[0][j]=0; // Variables to store the longest common substring found so far. lcs_start = 0; // lcs start lcs_len = 0; // lcs length for (int i=1; i<m+1; ++i) { for (int j=1; j<n+1; ++j) { if (X[i-1]==Y[j-1]) { C[1][j] = C[0][j-1]+1; if (C[1][j]>lcs_len) { lcs_len = C[1][j]; // actual index in the X string // to get the index in the Y string replace i with j lcs_start = (i-1)-(lcs_len-1); } } else { C[1][j] = 0; } } std::swap(C[1],C[0]); } } #define MAX 6 int main(int argc, char* argv[]) { //int seed = 1281811359;//time(NULL); //srand(seed); //printf("seed= %i\n",seed); char X[] = "xabxxcdexxx"; char Y[] = "yyabycdeyy"; //char X[] = "xabx"; //char Y[] = "yaby"; int lenx = sizeof(X)-1; int leny = sizeof(Y)-1; // -- Print input START int leni = std::max(lenx, leny); printf("lenx=%d, leny=%d, leni=%d\n", lenx, leny, leni); int * I = new int[leni]; for (int i=0; i<leni; ++i) { I[i]=i; //X[i]=48+rand()%10; //Y[i]=48+rand()%10; } dump_array(I,leni); dump_array2(X,lenx); dump_array2(Y,leny); // -- Print input END // -- Actually find longest common substring. size_t lcs_start, lcs_len; lcs2(X, lenx, Y, leny, lcs_start, lcs_len); printf("\n"); if (lcs_len>0) dump_array2(X+lcs_start, lcs_len); return 0; }
22.44
78
0.521687
arupa-loka
a984a7326ed18131076a35092f409932d8d84658
4,478
cxx
C++
DreamDaq/macro_root/cu_dream_avg_gioca.cxx
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
3
2021-07-22T12:17:48.000Z
2021-07-27T07:22:54.000Z
DreamDaq/macro_root/cu_dream_avg_gioca.cxx
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
38
2021-07-14T15:41:04.000Z
2022-03-29T14:18:20.000Z
DreamDaq/macro_root/cu_dream_avg_gioca.cxx
ivivarel/DREMTubes
ac768990b4c5e2c23d986284ed10189f31796b38
[ "MIT" ]
7
2021-07-21T12:00:33.000Z
2021-11-13T10:45:30.000Z
void cu_dream_avg(TString runfile, float *res = 0){ TFile *f = TFile::Open(runfile); float SAM = 2; //sigmas_around_mean TH1F * h; TF1 *g = new TF1("g","gaus"); f->GetObject("Cu_Dream/Cu_dream_S_tot",h); new TCanvas("S","S",12,10,700,500); h->GetXaxis()->SetRange(1400,2100); h->Fit(g,"q","",1500,2000); float muS = g->GetParameter(1); float sigmaS = g->GetParameter(2); h->Fit(g,"q","",muS-SAM*sigmaS,muS+SAM*sigmaS); muS = g->GetParameter(1); sigmaS = g->GetParameter(2); h->Fit(g,"q","",muS-SAM*sigmaS,muS+SAM*sigmaS); muS = g->GetParameter(1); sigmaS = g->GetParameter(2); float pedS = 897; new TCanvas("C","C",714,10,700,500); f->GetObject("Cu_Dream/Cu_dream_C_tot",h); h->GetXaxis()->SetRange(1400,2100); h->Fit(g,"q","",1500,2000); float muC = g->GetParameter(1); float sigmaC = g->GetParameter(2); h->Fit(g,"q","",muC-SAM*sigmaC,muC+SAM*sigmaC); muC = g->GetParameter(1); sigmaC = g->GetParameter(2); h->Fit(g,"q","",muC-SAM*sigmaC,muC+SAM*sigmaC); muC = g->GetParameter(1); sigmaC = g->GetParameter(2); float pedC = 869; cout << std::setprecision(3) << "<Stot> = " << muS-pedS << " +- " << sigmaS << " ("<< sigmaS/(muS-pedS)*100 << "%)\n"; cout << "<Ctot> = " << muC-pedC << " +- " << sigmaC << " (" << sigmaC/ (muC-pedC)*100 << "%)\n"; if (res!=0) { res[0]= sigmaS/(muS-pedS)*100; res[1]= sigmaC/(muC-pedC)*100; res[2]= muS; res[3]= sigmaS; res[4]= muC; res[5]= sigmaC; } } void cu_dream_avg(int run, float *res = 0){ cu_dream_avg(Form("~/storage/hbook/datafile_histo_run%d.root",run),res); } void cu_dream_res(int run, int n_theta, float *thetas, TString type){ TMultiGraph *mg = new TMultiGraph("mg","#theta scan ("+type+"); #theta [deg]; #sigma / #mu [%]"); TGraph* gS = new TGraph(); gS->SetNameTitle("gS","S"); gS->SetMarkerStyle(20); gS->SetMarkerColor(kBlue); gS->SetFillColor(0); TGraph* gC = new TGraph(); gC->SetNameTitle("gC","C"); gC->SetMarkerStyle(21); gC->SetMarkerColor(kRed); gC->SetFillColor(0); mg->Add(gS); mg->Add(gC); int j=0; for(int i=0; i<n_theta; i++){ if (thetas[i]<1000){ cout << "run: " << run+i << " theta: " << thetas[i] << endl; float res[20]; cu_dream_avg(run+i,res); gS->SetPoint(j,thetas[i],res[0]); gC->SetPoint(j,thetas[i],res[1]); j++; } } TCanvas* c=new TCanvas("thetascan"+type,"res vs theta"); c->SetGridx();c->SetGridy(); // mg->Draw("alp"); mg->Draw("ap"); TLegend *lg = c->BuildLegend(0.6); lg->SetFillStyle(0); lg->Draw(); } void cu_dream_mu(int run, int n_theta, float *thetas, TString type){ TMultiGraph *mg = new TMultiGraph("mg","#theta scan ("+type+"); #theta [deg]; #mu [ADC counts]"); TGraph* gS = new TGraph(); gS->SetNameTitle("gS","S"); gS->SetMarkerStyle(20); gS->SetMarkerColor(kBlue); gS->SetFillColor(0); TGraph* gC = new TGraph(); gC->SetNameTitle("gC","C"); gC->SetMarkerStyle(21); gC->SetMarkerColor(kRed); gC->SetFillColor(0); mg->Add(gS); mg->Add(gC); int j=0; for(int i=0; i<n_theta; i++){ if (thetas[i]<1000){ cout << "run: " << run+i << " theta: " << thetas[i] << endl; float res[20]; cu_dream_avg(run+i,res); gS->SetPoint(j,thetas[i],res[2]); gC->SetPoint(j,thetas[i],res[4]); j++; } } TCanvas* c=new TCanvas("thetascan_mu_"+type,"mu vs theta"); c->SetGridx();c->SetGridy(); //mg->Draw("alp"); mg->Draw("ap"); TLegend *lg = c->BuildLegend(0.6); lg->SetFillStyle(0); lg->Draw(); } void cu_dream_PS(){ const int n_theta = 23; float thetas[n_theta]={5,4,3,2.5,2,1.5,1,0.8,0.6,0.4,0.2,0,-0.2,-0.4,-0.6,-.8,-1,-1.5,-2,-2.5,-3,-4,-5}; float thetas[n_theta]={5,4,3,2.5,2,1.5,1,0.8,0.6,0.4,0.2,0,-0.2,-0.4,-0.6,-0.8,-1.0,-1.5,-2,-2.5,-3,-4,-5}; int run = 10148; cu_dream_res(run, n_theta, thetas, "with PS"); cu_dream_mu(run, n_theta, thetas, "with PS"); } void cu_dream_no_PS(){ const int n_theta = 26; // float thetas[30]={-5,-4,-3,-2.5,-2,-1.5,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,.8,1,1.5,2,2.5,3,4,5}; float thetas[29]={5,4,3,2.5,2,1.5,1,0.8,0.6,0.4,0.2,0,-0.2,-0.4,-0.6,-.8,-1,-1.5,1000,-2,-2.5,-3,1000,-4,-5,-0.5,1000,-0.3,-0.1}; // float thetas[18]={5,4,3,2.5,2,1.5,1,0.8,0.6,0.4,0.2,0,-0.2,-0.4,-0.6,-.8,-1,-1.5}; int run = 10148; cu_dream_res(run, n_theta, thetas, "no PS"); cu_dream_mu(run, n_theta, thetas, "no PS"); } void cu_dream_avg_gioca(){ cu_dream_no_PS(); }
28.705128
131
0.575033
ivivarel
a985679b523f5591398ff126a25890c1fa881f22
9,030
hpp
C++
native/external-libraries/boost/boost/log/utility/init/formatter_parser.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
null
null
null
native/external-libraries/boost/boost/log/utility/init/formatter_parser.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
null
null
null
native/external-libraries/boost/boost/log/utility/init/formatter_parser.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
null
null
null
/* * Copyright Andrey Semashev 2007 - 2010. * 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 formatter_parser.hpp * \author Andrey Semashev * \date 07.04.2008 * * The header contains definition of a formatter parser function, along with facilities to * add support for custom formatters. */ #if (defined(_MSC_VER) && _MSC_VER > 1000) #pragma once #endif // _MSC_VER > 1000 #ifndef BOOST_LOG_UTILITY_INIT_FORMATTER_PARSER_HPP_INCLUDED_ #define BOOST_LOG_UTILITY_INIT_FORMATTER_PARSER_HPP_INCLUDED_ #include <new> // std::nothrow #include <iosfwd> #include <map> #include <string> #include <boost/function/function2.hpp> #include <boost/log/detail/setup_prologue.hpp> #include <boost/log/core/record.hpp> #include <boost/log/formatters/attr.hpp> #ifdef _MSC_VER #pragma warning(push) // 'm_A' : class 'A' needs to have dll-interface to be used by clients of class 'B' #pragma warning(disable: 4251) // non dll-interface class 'A' used as base for dll-interface class 'B' #pragma warning(disable: 4275) #endif // _MSC_VER namespace boost { namespace BOOST_LOG_NAMESPACE { /*! * \brief Auxiliary formatter traits * * The structure generates commonly used types related to formatters and formatter factories. */ template< typename CharT > struct formatter_types { //! Character type typedef CharT char_type; //! String type typedef std::basic_string< char_type > string_type; //! Output stream type typedef std::basic_ostream< char_type > ostream_type; //! Log record type typedef basic_record< char_type > record_type; //! The formatter function object typedef function2< void, ostream_type&, record_type const& > formatter_type; /*! * Type of the map of formatter factory arguments [argument name -> argument value]. * This type of maps will be passed to formatter factories on attempt to create a formatter. */ typedef std::map< string_type, string_type > formatter_factory_args; /*! * \brief The type of a function object that constructs formatter instance * \param name Attribute name * \param args Formatter arguments * \return The constructed formatter. The formatter must not be empty. * * \b Throws: An <tt>std::exception</tt>-based If an exception is thrown from the method, * the exception is propagated to the parse_formatter caller */ typedef function2< formatter_type, string_type const&, formatter_factory_args const& > formatter_factory; //! Map of formatter factory function objects typedef std::map< string_type, formatter_factory > factories_map; }; namespace aux { /*! * A simple formatter factory function. Provides an easy way to add user-defined types support to * the formatter parser. The factory does not consider any formatter arguments, if specified, * but produces the formatter that uses the native \c operator<< to format the attribute value. * * \param attr_name Attribute name to create formatter for. */ template< typename CharT, typename AttributeValueT > typename formatter_types< CharT >::formatter_type make_simple_formatter( typename formatter_types< CharT >::string_type const& attr_name, typename formatter_types< CharT >::formatter_factory_args const&) { typedef typename formatter_types< CharT >::formatter_type formatter_type; return formatter_type(boost::log::formatters::attr< AttributeValueT >(attr_name, std::nothrow)); } } // namespace aux /*! * \brief The function registers a user-defined formatter factory * * The function registers a user-defined formatter factory. The registered factory function will be * called when the formatter parser detects the specified attribute name in the formatter string. * * \pre <tt>attr_name != NULL && !factory.empty()</tt>, \c attr_name must point to a zero-terminated sequence of characters. * * \param attr_name Attribute name * \param factory Formatter factory function */ template< typename CharT > BOOST_LOG_SETUP_EXPORT void register_formatter_factory( const CharT* attr_name, #ifndef BOOST_LOG_BROKEN_TEMPLATE_DEFINITION_MATCHING typename formatter_types< CharT >::formatter_factory const& factory #else function2< function2< void, std::basic_ostream< CharT >&, basic_record< CharT > const& >, std::basic_string< CharT > const&, std::map< std::basic_string< CharT >, std::basic_string< CharT > > const& > const& factory #endif // BOOST_LOG_BROKEN_TEMPLATE_DEFINITION_MATCHING ); /*! * \brief The function registers a user-defined formatter factory * * The function registers a user-defined formatter factory. The registered factory function will be * called when the formatter parser detects the specified attribute name in the formatter string. * * \pre <tt>!factory.empty()</tt> * * \param attr_name Attribute name * \param factory Formatter factory function */ template< typename CharT, typename TraitsT, typename AllocatorT > inline void register_formatter_factory( std::basic_string< CharT, TraitsT, AllocatorT > const& attr_name, typename formatter_types< CharT >::formatter_factory const& factory) { register_formatter_factory(attr_name.c_str(), factory); } /*! * \brief The function registers a simple formatter factory * * The function registers a simple formatter factory. The registered factory will generate formatters * that will be equivalent to the <tt>log::formatters::attr</tt> formatter (i.e. that will use the * native \c operator<< to format the attribute value). The factory does not use any arguments, * if specified. * * \pre <tt>attr_name != NULL</tt>, \c attr_name must point to a zero-terminated sequence of characters. * * \param attr_name Attribute name */ template< typename AttributeValueT, typename CharT > inline void register_simple_formatter_factory(const CharT* attr_name) { register_formatter_factory(attr_name, &boost::log::aux::make_simple_formatter< CharT, AttributeValueT >); } /*! * \brief The function registers a simple formatter factory * * The function registers a simple formatter factory. The registered factory will generate formatters * that will be equivalent to the <tt>log::formatters::attr</tt> formatter (i.e. that will use the * native \c operator<< to format the attribute value). The factory does not use any arguments, * if specified. * * \param attr_name Attribute name */ template< typename AttributeValueT, typename CharT, typename TraitsT, typename AllocatorT > inline void register_simple_formatter_factory(std::basic_string< CharT, TraitsT, AllocatorT > const& attr_name) { register_formatter_factory(attr_name.c_str(), &boost::log::aux::make_simple_formatter< CharT, AttributeValueT >); } /*! * The function parses a formatter from the sequence of characters * * \pre <tt>begin <= end</tt>, both pointers must not be NULL * \param begin Pointer to the first character of the sequence * \param end Pointer to the after-the-last character of the sequence * \return A function object that can be used as a formatter. * * \b Throws: An <tt>std::exception</tt>-based exception, if a formatter cannot be recognized in the character sequence. */ template< typename CharT > BOOST_LOG_SETUP_EXPORT #ifndef BOOST_LOG_BROKEN_TEMPLATE_DEFINITION_MATCHING typename formatter_types< CharT >::formatter_type #else function2< void, std::basic_ostream< CharT >&, basic_record< CharT > const& > #endif parse_formatter(const CharT* begin, const CharT* end); /*! * The function parses a formatter from the string * * \param str A string that contains format description * \return A function object that can be used as a formatter. * * \b Throws: An <tt>std::exception</tt>-based exception, if a formatter cannot be recognized in the character sequence. */ template< typename CharT, typename TraitsT, typename AllocatorT > inline typename formatter_types< CharT >::formatter_type parse_formatter(std::basic_string< CharT, TraitsT, AllocatorT > const& str) { const CharT* p = str.c_str(); return parse_formatter(p, p + str.size()); } /*! * The function parses a formatter from the string * * \pre <tt>str != NULL</tt>, <tt>str</tt> points to a zero-terminated string * \param str A string that contains format description. * \return A function object that can be used as a formatter. * * \b Throws: An <tt>std::exception</tt>-based exception, if a formatter cannot be recognized in the character sequence. */ template< typename CharT > inline typename formatter_types< CharT >::formatter_type parse_formatter(const CharT* str) { return parse_formatter(str, str + std::char_traits< CharT >::length(str)); } } // namespace log } // namespace boost #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // BOOST_LOG_UTILITY_INIT_FORMATTER_PARSER_HPP_INCLUDED_
37.625
124
0.739978
l3dlp-sandbox
a98bf9d1fe00309110362eb8fc84f838c4cec862
54,393
cpp
C++
src/Base/ViewArea.cpp
team-FisMa/choreonoid
83265e8ffe96eb0aec977be7a43cd8c218fc5905
[ "MIT" ]
66
2020-03-11T14:06:01.000Z
2022-03-23T23:18:27.000Z
src/Base/ViewArea.cpp
team-FisMa/choreonoid
83265e8ffe96eb0aec977be7a43cd8c218fc5905
[ "MIT" ]
12
2020-07-23T06:13:11.000Z
2022-01-13T14:25:01.000Z
src/Base/ViewArea.cpp
team-FisMa/choreonoid
83265e8ffe96eb0aec977be7a43cd8c218fc5905
[ "MIT" ]
18
2020-07-17T15:57:54.000Z
2022-03-29T13:18:59.000Z
/** @author Shin'ichiro Nakaoka */ #include "ViewArea.h" #include "View.h" #include "ViewManager.h" #include "MenuManager.h" #include "MessageView.h" #include "MainWindow.h" #include "Timer.h" #include <QApplication> #include <QBoxLayout> #include <QSplitter> #include <QTabWidget> #include <QTabBar> #include <QRubberBand> #include <QMouseEvent> #include <QDesktopWidget> #include <QLabel> #include <memory> #include <bitset> #include "gettext.h" using namespace std; using namespace cnoid; namespace { enum DropArea { OVER = -1, LEFT = 0, TOP, RIGHT, BOTTOM, NUM_DROP_AREAS }; const int SPLIT_DISTANCE_THRESHOLD = 35; vector<ViewArea*> viewAreas; bool isBeforeDoingInitialLayout = true; class TabWidget : public QTabWidget { public: TabWidget(QWidget* parent) : QTabWidget(parent) { } QTabBar* tabBar() { return QTabWidget::tabBar(); } }; class ViewPane : public QWidget { public: ViewPane(ViewArea::Impl* viewAreaImpl, QWidget* parent = nullptr); int addView(View* view); void onViewTitleChanged(const QString &title); void removeView(View* view); void setTabVisible(bool on); void makeDirect(); QTabBar* tabBar() { return tabWidget->tabBar(); } const QTabBar* tabBar() const { return tabWidget->tabBar(); } int currentIndex() const { return directView ? 0 : tabWidget->currentIndex(); } void setCurrentIndex(int index) { if(!directView){ tabWidget->setCurrentIndex(index); } } View* currentView() const { return directView ? directView : static_cast<View*>(tabWidget->currentWidget()); } int count() const { return directView ? 1 : tabWidget->count(); } View* view(int index) const { if(directView){ if(index == 0){ return directView; } return nullptr; } else { return static_cast<View*>(tabWidget->widget(index)); } } virtual bool eventFilter(QObject* object, QEvent* event); virtual QSize minimumSizeHint () const { QSize s = QWidget::minimumSizeHint(); if(!tabBar()->isVisible()){ s.rheight() -= tabBar()->minimumSizeHint().height(); } return s; } TabWidget* tabWidget; QVBoxLayout* vbox; View* directView; ViewArea::Impl* viewAreaImpl; }; } namespace cnoid { class ViewArea::Impl { public: Impl(ViewArea* self); ~Impl(); ViewArea* self; QVBoxLayout* vbox; QSplitter* topSplitter; int numViews; bool viewTabsVisible; bool isMaximizedBeforeFullScreen; bool needToUpdateDefaultPaneAreas; std::unique_ptr<vector<View*>> defaultViewsToShow; ViewPane* areaToPane[View::NumLayoutAreas]; struct AreaDetectionInfo { AreaDetectionInfo() { for(int i=0; i < View::NumLayoutAreas; ++i){ scores[i] = 0; } } ViewPane* pane; int scores[View::NumLayoutAreas]; }; typedef bitset<NUM_DROP_AREAS> EdgeContactState; QPoint tabDragStartPosition; bool isViewDragging; View* draggedView; QSize draggedViewWindowSize; ViewArea* dragDestViewArea; ViewPane* dragSrcPane; ViewPane* dragDestPane; bool isViewDraggingOnOuterEdge; int dropEdge; QRubberBand* rubberBand; vector<QLabel*> viewSizeLabels; Timer viewSizeLabelTimer; MenuManager viewMenuManager; void setSingleView(View* view); void createDefaultPanes(); void detectExistingPaneAreas(); ViewPane* updateAreaDetectionInfos(QSplitter* splitter, const EdgeContactState& edge, vector<AreaDetectionInfo>& infos); void setBestAreaMatchPane(vector<AreaDetectionInfo>& infos, View::LayoutArea area, ViewPane* firstPane); void setViewTabsVisible(QSplitter* splitter, bool on); void setFullScreen(bool on); bool addView(View* view); void addView(ViewPane* pane, View* view, bool makeCurrent); bool removeView(View* view); bool removeView(ViewPane* pane, View* view, bool isMovingInViewArea); View* findFirstView(QSplitter* splitter); void getVisibleViews(vector<View*>& out_views, QSplitter* splitter = nullptr); void getVisibleViewsIter(QSplitter* splitter, vector<View*>& out_views); void showViewSizeLabels(QSplitter* splitter); void hideViewSizeLabels(); bool viewTabMousePressEvent(ViewPane* pane, QMouseEvent* event); bool viewTabMouseMoveEvent(ViewPane* pane, QMouseEvent* event); bool viewTabMouseReleaseEvent(QMouseEvent *event); void showRectangle(QRect r); void dragView(QMouseEvent* event); void dragViewInsidePane(const QPoint& posInDestPane); void dropViewInsidePane(ViewPane* pane, View* view, int dropEdge); void dragViewOnOuterEdge(); void dropViewToOuterEdge(View* view); void dragViewOutside(const QPoint& pos); void dropViewOutside(const QPoint& pos); void separateView(View* view); void clearAllPanes(); void clearAllPanesSub(QSplitter* splitter); void getAllViews(vector<View*>& out_views); void getAllViewsSub(QSplitter* splitter, vector<View*>& out_views); void storeLayout(Archive* archive); MappingPtr storeSplitterState(QSplitter* splitter, Archive* archive); MappingPtr storePaneState(ViewPane* pane, Archive* archive); void restoreLayout(Archive* archive); QWidget* restoreViewContainer(const Mapping& state, Archive* archive); QWidget* restoreSplitter(const Mapping& state, Archive* archive); ViewPane* restorePane(const Mapping& state, Archive* archive); void resetLayout(); void removePaneIfEmpty(ViewPane* pane); void removePaneSub(QWidget* widgetToRemove, QWidget* widgetToRaise); void clearEmptyPanes(); QWidget* clearEmptyPanesSub(QSplitter* splitter); }; } namespace { class CustomSplitter : public QSplitter { public: ViewArea::Impl* viewAreaImpl; bool defaultOpaqueResize; CustomSplitter(ViewArea::Impl* viewAreaImpl, QWidget* parent = nullptr) : QSplitter(parent), viewAreaImpl(viewAreaImpl) { defaultOpaqueResize = opaqueResize(); } CustomSplitter(ViewArea::Impl* viewAreaImpl, Qt::Orientation orientation, QWidget* parent = nullptr) : QSplitter(orientation, parent), viewAreaImpl(viewAreaImpl) { defaultOpaqueResize = opaqueResize(); } bool moveSplitterPosition(int d){ QList<int> s = sizes(); if(s.size() >= 2){ s[0] += d; s[1] -= d; } if(s[0] >= 0 && s[1] >= 0){ setSizes(s); } return true; } QSplitterHandle* createHandle(); }; class CustomSplitterHandle : public QSplitterHandle { CustomSplitter* splitter; bool isDragging; public: CustomSplitterHandle(CustomSplitter* splitter) : QSplitterHandle(splitter->orientation(), splitter), splitter(splitter) { setFocusPolicy(Qt::WheelFocus); isDragging = false; } virtual void mousePressEvent(QMouseEvent* event){ if(event->button() == Qt::LeftButton){ isDragging = true; splitter->viewAreaImpl->showViewSizeLabels(splitter); if(event->modifiers() & Qt::ShiftModifier){ splitter->setOpaqueResize(!splitter->defaultOpaqueResize); } else { splitter->setOpaqueResize(splitter->defaultOpaqueResize); } } QSplitterHandle::mouseMoveEvent(event); } virtual void mouseMoveEvent(QMouseEvent* event){ QSplitterHandle::mouseMoveEvent(event); if(isDragging){ splitter->viewAreaImpl->showViewSizeLabels(splitter); } } virtual void mouseReleaseEvent(QMouseEvent* event) { QSplitterHandle::mouseReleaseEvent(event); isDragging = false; splitter->setOpaqueResize(splitter->defaultOpaqueResize); } virtual void keyPressEvent(QKeyEvent* event) { bool processed = false; int r = 1; if(event->modifiers() & Qt::ShiftModifier){ r = 10; } int key = event->key(); if(orientation() == Qt::Horizontal){ if(key == Qt::Key_Left){ processed = splitter->moveSplitterPosition(-r); } else if(key == Qt::Key_Right){ processed = splitter->moveSplitterPosition( r); } } else { if(key == Qt::Key_Up){ processed = splitter->moveSplitterPosition(-r); } else if(key == Qt::Key_Down){ processed = splitter->moveSplitterPosition( r); } } if(processed){ splitter->viewAreaImpl->showViewSizeLabels(splitter); } else { QSplitterHandle::keyPressEvent(event); } } }; QSplitterHandle* CustomSplitter::createHandle() { return new CustomSplitterHandle(this); } ViewPane::ViewPane(ViewArea::Impl* viewAreaImpl, QWidget* parent) : QWidget(parent), viewAreaImpl(viewAreaImpl) { vbox = new QVBoxLayout(this); vbox->setSpacing(0); vbox->setContentsMargins(0, 0, 0, 0); tabWidget = new TabWidget(this); tabWidget->setMovable(true); tabWidget->setUsesScrollButtons(true); tabWidget->tabBar()->installEventFilter(this); if(!viewAreaImpl->viewTabsVisible){ tabWidget->tabBar()->hide(); } vbox->addWidget(tabWidget); directView = nullptr; } int ViewPane::addView(View* view) { int index = 0; if(viewAreaImpl->viewTabsVisible){ index = tabWidget->addTab(view, view->windowTitle()); } else { if(viewAreaImpl->self->isWindow() && tabWidget->count() == 0 && !directView){ tabWidget->hide(); directView = view; directView->setParent(this); vbox->addWidget(directView); directView->show(); } else { tabWidget->show(); if(directView){ tabWidget->addTab(directView, directView->windowTitle()); directView = nullptr; } index = tabWidget->addTab(view, view->windowTitle()); } } connect(view, &QWidget::windowTitleChanged, this, &ViewPane::onViewTitleChanged); return index; } /** \todo Implement this in View.cpp. See the View::bringToFront function. */ void ViewPane::onViewTitleChanged(const QString &title) { if(auto view = dynamic_cast<View*>(sender())){ int index = tabWidget->indexOf(view); tabWidget->setTabText(index, view->windowTitle()); } } void ViewPane::removeView(View* view) { if(view == directView){ vbox->removeWidget(directView); directView = nullptr; } else { tabWidget->removeTab(tabWidget->indexOf(view)); if(viewAreaImpl->self->isWindow() && tabWidget->count() == 1 && !viewAreaImpl->viewTabsVisible){ makeDirect(); } } disconnect(view, &QWidget::windowTitleChanged, this, &ViewPane::onViewTitleChanged); } void ViewPane::setTabVisible(bool on) { if(on){ if(directView){ tabWidget->addTab(directView, directView->windowTitle()); directView = nullptr; tabWidget->show(); } tabBar()->show(); } else { if(!directView){ if(viewAreaImpl->self->isWindow() && tabWidget->count() == 1){ makeDirect(); } else { tabBar()->hide(); } } } } void ViewPane::makeDirect() { if(!directView && tabWidget->count() == 1){ directView = static_cast<View*>(tabWidget->widget(0)); tabWidget->removeTab(0); directView->setParent(this); directView->show(); vbox->addWidget(directView); tabWidget->hide(); } } bool ViewPane::eventFilter(QObject* object, QEvent* event) { if(object == tabWidget->tabBar()){ switch(event->type()){ case QEvent::MouseButtonPress: return viewAreaImpl->viewTabMousePressEvent(this, static_cast<QMouseEvent*>(event)); case QEvent::MouseButtonDblClick: break; case QEvent::MouseButtonRelease: return viewAreaImpl->viewTabMouseReleaseEvent(static_cast<QMouseEvent*>(event)); case QEvent::MouseMove: return viewAreaImpl->viewTabMouseMoveEvent(this, static_cast<QMouseEvent*>(event)); default: break; } } return false; } } ViewArea::ViewArea(QWidget* parent) : QWidget(parent) { if(!parent){ //setParent(MainWindow::instance()); //setWindowFlags(Qt::Tool); setAttribute(Qt::WA_DeleteOnClose); } impl = new Impl(this); } ViewArea::Impl::Impl(ViewArea* self) : self(self) { numViews = 0; viewTabsVisible = true; isMaximizedBeforeFullScreen = false; isViewDragging = false; draggedView = nullptr; dragSrcPane = nullptr; dragDestViewArea = nullptr; dragDestPane = nullptr; vbox = new QVBoxLayout(self); vbox->setSpacing(0); vbox->setContentsMargins(0, 0, 0, 0); rubberBand = new QRubberBand(QRubberBand::Rectangle, self); rubberBand->hide(); viewSizeLabelTimer.setSingleShot(true); viewSizeLabelTimer.setInterval(1000); viewSizeLabelTimer.sigTimeout().connect([&](){ hideViewSizeLabels(); }); topSplitter = nullptr; needToUpdateDefaultPaneAreas = true; viewAreas.push_back(self); } ViewArea::~ViewArea() { viewAreas.erase(std::find(viewAreas.begin(), viewAreas.end(), this)); delete impl; } ViewArea::Impl::~Impl() { clearAllPanes(); delete rubberBand; } void ViewArea::setSingleView(View* view) { impl->setSingleView(view); } void ViewArea::Impl::setSingleView(View* view) { clearAllPanes(); viewTabsVisible = false; topSplitter = new CustomSplitter(this, self); vbox->addWidget(topSplitter); ViewPane* pane = new ViewPane(this, topSplitter); topSplitter->addWidget(pane); for(int i=0; i < View::NumLayoutAreas; ++i){ areaToPane[i] = pane; } needToUpdateDefaultPaneAreas = false; addView(pane, view, true); defaultViewsToShow.reset(); } void ViewArea::createDefaultPanes() { impl->createDefaultPanes(); } void ViewArea::Impl::createDefaultPanes() { clearAllPanes(); topSplitter = new CustomSplitter(this, self); vbox->addWidget(topSplitter); topSplitter->setOrientation(Qt::Horizontal); auto vSplitter0 = new CustomSplitter(this, Qt::Vertical, topSplitter); topSplitter->addWidget(vSplitter0); auto topLeftPane = new ViewPane(this, vSplitter0); vSplitter0->addWidget(topLeftPane); auto bottomLeftPane = new ViewPane(this, vSplitter0); vSplitter0->addWidget(bottomLeftPane); auto vSplitter1 = new CustomSplitter(this, Qt::Vertical, topSplitter); topSplitter->addWidget(vSplitter1); auto hSplitter1 = new CustomSplitter(this, Qt::Horizontal, vSplitter1); vSplitter1->addWidget(hSplitter1); auto bottomCenterPane = new ViewPane(this, vSplitter1); vSplitter1->addWidget(bottomCenterPane); auto centerPane = new ViewPane(this, hSplitter1); hSplitter1->addWidget(centerPane); auto rightPane = new ViewPane(this, hSplitter1); hSplitter1->addWidget(rightPane); areaToPane[View::TopLeftArea] = topLeftPane; areaToPane[View::MiddleLeftArea] = topLeftPane; areaToPane[View::BottomLeftArea] = bottomLeftPane; areaToPane[View::TopCenterArea] = centerPane; areaToPane[View::CenterArea] = centerPane; areaToPane[View::BottomCenterArea] = bottomCenterPane; areaToPane[View::TopRightArea] = rightPane; areaToPane[View::MiddleRightArea] = rightPane; areaToPane[View::BottomRightArea] = rightPane; QList<int> sizes; sizes << 100 << 600; topSplitter->setSizes(sizes); sizes.last() = 100; vSplitter0->setSizes(sizes); sizes.last() = 40; vSplitter1->setSizes(sizes); sizes.last() = 160; hSplitter1->setSizes(sizes); needToUpdateDefaultPaneAreas = false; } void ViewArea::Impl::detectExistingPaneAreas() { for(int i=0; i < View::NumLayoutAreas; ++i){ areaToPane[i] = nullptr; } vector<AreaDetectionInfo> infos; EdgeContactState edge; edge.set(); ViewPane* firstPane = updateAreaDetectionInfos(topSplitter, edge, infos); if(infos.empty()){ createDefaultPanes(); } else { setBestAreaMatchPane(infos, View::CenterArea, firstPane); setBestAreaMatchPane(infos, View::TopLeftArea, firstPane); setBestAreaMatchPane(infos, View::BottomLeftArea, firstPane); setBestAreaMatchPane(infos, View::TopRightArea, firstPane); setBestAreaMatchPane(infos, View::BottomCenterArea, firstPane); areaToPane[View::MiddleLeftArea] = areaToPane[View::TopLeftArea]; areaToPane[View::TopCenterArea] = areaToPane[View::CenterArea]; areaToPane[View::MiddleRightArea] = areaToPane[View::TopRightArea]; areaToPane[View::BottomRightArea] = areaToPane[View::TopRightArea]; } needToUpdateDefaultPaneAreas = false; } /** @return The first found pane */ ViewPane* ViewArea::Impl::updateAreaDetectionInfos (QSplitter* splitter, const EdgeContactState& edge, vector<AreaDetectionInfo>& infos) { ViewPane* firstPane = nullptr; QWidget* childWidgets[2]; childWidgets[0] = (splitter->count() > 0) ? splitter->widget(0) : 0; childWidgets[1] = (splitter->count() > 1) ? splitter->widget(1) : 0; bool isSingle = !(childWidgets[0] && childWidgets[1]); for(int i=0; i < 2; ++i){ EdgeContactState currentEdge(edge); if(!isSingle){ if(splitter->orientation() == Qt::Vertical){ currentEdge.reset((i == 0) ? BOTTOM : TOP); } else { currentEdge.reset((i == 0) ? RIGHT : LEFT); } } if(childWidgets[i]){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(childWidgets[i]); if(childSplitter){ ViewPane* pane = updateAreaDetectionInfos(childSplitter, currentEdge, infos); if(!firstPane){ firstPane = pane; } } else { ViewPane* pane = dynamic_cast<ViewPane*>(childWidgets[i]); if(pane){ AreaDetectionInfo info; info.pane = pane; // calculate scores for area matching static const int offset = 100000000; int width = pane->width(); int height = pane->height(); info.scores[View::CenterArea] = (4 - currentEdge.count()) * offset + width * height; if(currentEdge.test(LEFT) && !currentEdge.test(RIGHT)){ info.scores[View::TopLeftArea] = offset + height; info.scores[View::BottomLeftArea] = offset + height; if(currentEdge.test(TOP) && !currentEdge.test(BOTTOM)){ info.scores[View::TopLeftArea] += 100; } else if(currentEdge.test(BOTTOM) && !currentEdge.test(TOP)){ info.scores[View::BottomLeftArea] += 100; } } if(currentEdge.test(RIGHT) && !currentEdge.test(LEFT)){ info.scores[View::TopRightArea] = offset + height; } if(currentEdge.test(BOTTOM) && !currentEdge.test(TOP)){ info.scores[View::BottomCenterArea] = offset + width; } infos.push_back(info); if(!firstPane){ firstPane = pane; } } } } } return firstPane; } void ViewArea::Impl::setBestAreaMatchPane(vector<AreaDetectionInfo>& infos, View::LayoutArea area, ViewPane* firstPane) { int topScore = 0; int topIndex = -1; for(int i=0; i < (signed)infos.size(); ++i){ int s = infos[i].scores[area]; if(s > topScore){ topScore = s; topIndex = i; } } if(topIndex >= 0){ areaToPane[area] = infos[topIndex].pane; } else { areaToPane[area] = firstPane; } } bool ViewArea::viewTabsVisible() const { return impl->viewTabsVisible; } void ViewArea::setViewTabsVisible(bool on) { if(impl->viewTabsVisible != on){ if(impl->topSplitter){ impl->setViewTabsVisible(impl->topSplitter, on); } impl->viewTabsVisible = on; } } void ViewArea::Impl::setViewTabsVisible(QSplitter* splitter, bool on) { for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ setViewTabsVisible(childSplitter, on); } else { ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane){ pane->setTabVisible(on); } } } } void ViewArea::Impl::setFullScreen(bool on) { if(self->isWindow()){ if(on){ if(!self->isFullScreen()){ isMaximizedBeforeFullScreen = self->windowState() & Qt::WindowMaximized; self->showFullScreen(); } } else if(self->isFullScreen()){ self->showNormal(); if(isMaximizedBeforeFullScreen){ self->showMaximized(); } } } } bool ViewArea::addView(View* view) { return impl->addView(view); } bool ViewArea::Impl::addView(View* view) { if(view->viewArea() == self){ return false; } if(isBeforeDoingInitialLayout){ if(!defaultViewsToShow){ defaultViewsToShow.reset(new vector<View*>()); } defaultViewsToShow->push_back(view); } else { if(needToUpdateDefaultPaneAreas){ detectExistingPaneAreas(); } addView(areaToPane[view->defaultLayoutArea()], view, false); } return true; } void ViewArea::Impl::addView(ViewPane* pane, View* view, bool makeCurrent) { if(view->viewArea()){ view->viewArea()->impl->removeView(view); } int index = pane->addView(view); if(makeCurrent){ pane->setCurrentIndex(index); } view->setViewArea(self); ++numViews; if(numViews == 1){ self->setWindowTitle(view->windowTitle()); } else if(numViews == 2){ self->setWindowTitle("Views"); self->setViewTabsVisible(true); } } bool ViewArea::removeView(View* view) { return impl->removeView(view); } bool ViewArea::Impl::removeView(View* view) { bool removed = false; if(view->viewArea() == self){ ViewPane* pane = nullptr; for(QWidget* widget = view->parentWidget(); widget; widget = widget->parentWidget()){ pane = dynamic_cast<ViewPane*>(widget); if(pane){ break; } } if(pane){ removed = removeView(pane, view, false); } } return removed; } bool ViewArea::Impl::removeView(ViewPane* pane, View* view, bool isMovingInViewArea) { bool removed = false; //! \todo check if the owner view area is same as this if(view->viewArea() == self){ pane->removeView(view); if(pane->count() > 0){ pane->setCurrentIndex(0); } --numViews; removed = true; if(!isMovingInViewArea){ view->hide(); view->setParent(0); removePaneIfEmpty(pane); if(self->isWindow()){ if(numViews == 1){ View* existingView = findFirstView(topSplitter); if(existingView){ self->setWindowTitle(existingView->windowTitle()); } } else if(numViews == 0){ self->deleteLater(); } } } view->setViewArea(0); } return removed; } View* ViewArea::Impl::findFirstView(QSplitter* splitter) { View* view = nullptr; for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ view = findFirstView(childSplitter); } else { ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane && pane->count() > 0){ view = pane->view(0); } } if(view){ break; } } return view; } int ViewArea::numViews() const { return impl->numViews; } void ViewArea::Impl::getVisibleViews(vector<View*>& out_views, QSplitter* splitter) { getVisibleViewsIter(splitter ? splitter : topSplitter, out_views); } void ViewArea::Impl::getVisibleViewsIter(QSplitter* splitter, vector<View*>& out_views) { QList<int> sizes = splitter->sizes(); for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ getVisibleViewsIter(childSplitter, out_views); } else { if(sizes[i] > 0){ ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane){ View* view = pane->currentView(); if(view){ out_views.push_back(view); } } } } } } void ViewArea::Impl::showViewSizeLabels(QSplitter* splitter) { vector<View*> views; getVisibleViews(views, splitter); for(size_t i=0; i < views.size(); ++i){ View* view = views[i]; QLabel* label = nullptr; if(i < viewSizeLabels.size()){ label = viewSizeLabels[i]; } else { label = new QLabel(self); label->setFrameStyle(QFrame::Box | QFrame::Raised); label->setLineWidth(0); label->setMidLineWidth(1); label->setAutoFillBackground(true); label->setAlignment(Qt::AlignCenter); viewSizeLabels.push_back(label); } label->setText(QString("%1 x %2").arg(view->width()).arg(view->height())); QPoint p = view->viewAreaPos(); QSize s = label->size(); int x = p.x() + view->width() / 2 - s.width() / 2; int y = p.y() + view->height() / 2 - s.height() / 2; label->move(x, y); label->show(); } viewSizeLabelTimer.start(); } void ViewArea::Impl::hideViewSizeLabels() { for(size_t i=0; i < viewSizeLabels.size(); ++i){ viewSizeLabels[i]->hide(); } } void ViewArea::keyPressEvent(QKeyEvent* event) { event->ignore(); switch(event->key()){ case Qt::Key_F12: setViewTabsVisible(!impl->viewTabsVisible); event->accept(); break; } if(isWindow()){ switch(event->key()){ case Qt::Key_F11: impl->setFullScreen(!isFullScreen()); event->accept(); break; } } } void ViewArea::restoreAllViewAreaLayouts(ArchivePtr archive) { Impl* mainViewAreaImpl = MainWindow::instance()->viewArea()->impl; if(archive){ Listing& layouts = *archive->findListing("viewAreas"); if(layouts.isValid()){ QDesktopWidget* desktop = QApplication::desktop(); const int numScreens = desktop->screenCount(); for(int i=0; i < layouts.size(); ++i){ Mapping& layout = *layouts[i].toMapping(); Archive* contents = dynamic_cast<Archive*>(layout.get("contents").toMapping()); if(contents){ contents->inheritSharedInfoFrom(*archive); const string type = layout.get("type").toString(); if(type == "embedded"){ mainViewAreaImpl->restoreLayout(contents); mainViewAreaImpl->self->setViewTabsVisible(layout.get("tabs", mainViewAreaImpl->viewTabsVisible)); } else if(type == "independent"){ ViewArea* viewWindow = new ViewArea; viewWindow->impl->viewTabsVisible = layout.get("tabs", true); viewWindow->impl->restoreLayout(contents); if(viewWindow->impl->numViews == 0){ delete viewWindow; } else { const Listing& geo = *layout.findListing("geometry"); if(geo.isValid() && geo.size() == 4){ // -1 means the primary screen int screen = -1; if(layout.read("screen", screen)){ if(screen >= numScreens){ screen = -1; } } const QRect s = desktop->screenGeometry(screen); const QRect r(geo[0].toInt(), geo[1].toInt(), geo[2].toInt(), geo[3].toInt()); viewWindow->setGeometry(r.translated(s.x(), s.y())); } if(layout.get("fullScreen", false)){ layout.read("maximized", viewWindow->impl->isMaximizedBeforeFullScreen); viewWindow->showFullScreen(); } else { if(layout.get("maximized"), false){ viewWindow->showMaximized(); } else { viewWindow->show(); } } } } } } } } if(isBeforeDoingInitialLayout){ mainViewAreaImpl->resetLayout(); } } void ViewArea::restoreLayout(ArchivePtr archive) { impl->restoreLayout(archive.get()); } void ViewArea::Impl::restoreLayout(Archive* archive) { clearAllPanes(); QWidget* topWidget = restoreViewContainer(*archive, archive); topSplitter = dynamic_cast<QSplitter*>(topWidget); if(!topSplitter){ topSplitter = new CustomSplitter(this); ViewPane* topPane = dynamic_cast<ViewPane*>(topWidget); if(!topPane){ topPane = new ViewPane(this); } topSplitter->addWidget(topPane); } vbox->addWidget(topSplitter); needToUpdateDefaultPaneAreas = true; isBeforeDoingInitialLayout = false; defaultViewsToShow.reset(); } void ViewArea::Impl::clearAllPanes() { if(topSplitter){ clearAllPanesSub(topSplitter); delete topSplitter; topSplitter = nullptr; } numViews = 0; needToUpdateDefaultPaneAreas = true; } void ViewArea::Impl::clearAllPanesSub(QSplitter* splitter) { for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ clearAllPanesSub(childSplitter); } else { ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane){ while(pane->count() > 0){ int index = pane->count() - 1; View* view = pane->view(index); if(view){ pane->removeView(view); view->hide(); view->setParent(0); view->setViewArea(0); } } } } } } void ViewArea::Impl::getAllViews(vector<View*>& out_views) { getAllViewsSub(topSplitter, out_views); } void ViewArea::Impl::getAllViewsSub(QSplitter* splitter, vector<View*>& out_views) { for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ getAllViewsSub(childSplitter, out_views); } else { ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane){ for(int i=0; i < pane->count(); ++i){ View* view = pane->view(i); if(view){ out_views.push_back(view); } } } } } } QWidget* ViewArea::Impl::restoreViewContainer(const Mapping& state, Archive* archive) { QWidget* widget = nullptr; string type; if(state.read("type", type)){ if(type == "splitter"){ widget = restoreSplitter(state, archive); } else if(type == "pane"){ widget = restorePane(state, archive); } } return widget; } QWidget* ViewArea::Impl::restoreSplitter(const Mapping& state, Archive* archive) { QWidget* widget = nullptr; QWidget* childWidgets[2] = { 0, 0 }; const Listing& children = *state.findListing("children"); if(children.isValid()){ int numChildren = std::min(children.size(), 2); for(int i=0; i < numChildren; ++i){ if(children[i].isMapping()){ const Mapping& childState = *children[i].toMapping(); childWidgets[i] = restoreViewContainer(childState, archive); } } if(!childWidgets[0] || !childWidgets[1]){ for(int i=0; i < 2; ++i){ if(childWidgets[i]){ widget = childWidgets[i]; break; } } } else { QSplitter* splitter = new CustomSplitter(this); string orientation; if(state.read("orientation", orientation)){ splitter->setOrientation((orientation == "vertical") ? Qt::Vertical : Qt::Horizontal); } splitter->addWidget(childWidgets[0]); splitter->addWidget(childWidgets[1]); const Listing& sizes = *state.findListing("sizes"); if(sizes.isValid() && sizes.size() == 2){ QList<int> s; int size; for(int i=0; i < 2; ++i){ if(sizes[i].read(size)){ s.push_back(size); } } splitter->setSizes(s); } widget = splitter; } } return widget; } ViewPane* ViewArea::Impl::restorePane(const Mapping& state, Archive* archive) { ViewPane* pane = nullptr; const Listing& views = *state.findListing("views"); if(views.isValid() && !views.empty()){ pane = new ViewPane(this); int currentId = 0; state.read("current", currentId); for(int i=0; i < views.size(); ++i){ const ValueNode& node = views[i]; View* view = nullptr; int id; bool isCurrent = false; if(node.read(id)){ view = archive->findView(id); if(view){ isCurrent = (id == currentId); } } if(view){ addView(pane, view, isCurrent); } } if(pane->count() == 0){ delete pane; pane = nullptr; } } return pane; } void ViewArea::storeAllViewAreaLayouts(ArchivePtr archive) { ListingPtr layouts = new Listing; for(size_t i=0; i < viewAreas.size(); ++i){ ArchivePtr layout = new Archive; layout->inheritSharedInfoFrom(*archive); viewAreas[i]->storeLayout(layout); layouts->append(layout); } if(!layouts->empty()){ archive->insert("viewAreas", layouts); } } void ViewArea::storeLayout(ArchivePtr archive) { impl->storeLayout(archive.get()); } void ViewArea::Impl::storeLayout(Archive* archive) { QDesktopWidget* desktop = QApplication::desktop(); const int primaryScreen = desktop->primaryScreen(); try { MappingPtr state = storeSplitterState(topSplitter, archive); if(state){ if(!self->isWindow()){ archive->write("type", "embedded"); } else { archive->write("type", "independent"); const int screen = desktop->screenNumber(self->pos()); if(screen != primaryScreen){ archive->write("screen", screen); } const QRect s = desktop->screenGeometry(screen); const QRect r = self->geometry().translated(-s.x(), -s.y()); Listing* geometry = archive->createFlowStyleListing("geometry"); geometry->append(r.x()); geometry->append(r.y()); geometry->append(r.width()); geometry->append(r.height()); if(self->isFullScreen()){ archive->write("fullScreen", true); archive->write("maximized", isMaximizedBeforeFullScreen); } else { archive->write("fullScreen", false); archive->write("maximized", self->isMaximized()); } } archive->write("tabs", viewTabsVisible); archive->insert("contents", state); } } catch(const ValueNode::Exception& ex){ MessageView::instance()->putln(ex.message()); } } MappingPtr ViewArea::Impl::storeSplitterState(QSplitter* splitter, Archive* archive) { // The actual state object must be the Archive type if it is directly used to restore the state MappingPtr state = new Archive; ListingPtr children = new Listing; for(int i=0; i < splitter->count(); ++i){ QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i)); if(childSplitter){ if(auto childState = storeSplitterState(childSplitter, archive)){ children->append(childState); } } else { ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i)); if(pane && pane->count() > 0){ if(auto childState = storePaneState(pane, archive)){ children->append(childState); } } } } const int numChildren = children->size(); if(numChildren == 0){ state.reset(); } else if(numChildren == 1){ state = children->at(0)->toMapping(); } else if(numChildren == 2){ state->write("type", "splitter"); state->write("orientation", (splitter->orientation() == Qt::Vertical) ? "vertical" : "horizontal"); Listing* sizeSeq = state->createFlowStyleListing("sizes"); QList<int> sizes = splitter->sizes(); for(int i=0; i < sizes.size(); ++i){ sizeSeq->append(sizes[i]); } state->insert("children", children); } return state; } MappingPtr ViewArea::Impl::storePaneState(ViewPane* pane, Archive* archive) { // The actual state object must be the Archive type if it is directly used to restore the state MappingPtr state = new Archive; state->write("type", "pane"); Listing* views = state->createFlowStyleListing("views"); const int n = pane->count(); for(int i=0; i < n; ++i){ View* view = pane->view(i); int id = archive->getViewId(view); if(id >= 0){ views->append(id); if(n >= 2 && (i == pane->currentIndex())){ state->write("current", id); } } } if(views->empty()){ state.reset(); } return state; } void ViewArea::resetAllViewAreaLayouts() { ViewArea* mainViewArea = MainWindow::instance()->viewArea(); mainViewArea->impl->resetLayout(); //! \todo close all the independent view windows } void ViewArea::resetLayout() { impl->resetLayout(); } void ViewArea::Impl::resetLayout() { if(isBeforeDoingInitialLayout){ isBeforeDoingInitialLayout = false; createDefaultPanes(); if(defaultViewsToShow){ for(size_t i=0; i < defaultViewsToShow->size(); ++i){ addView((*defaultViewsToShow)[i]); } defaultViewsToShow.reset(); } } else { vector<View*> views; getAllViews(views); clearAllPanes(); createDefaultPanes(); for(size_t i=0; i < views.size(); ++i){ addView(views[i]); } } } bool ViewArea::Impl::viewTabMousePressEvent(ViewPane* pane, QMouseEvent* event) { if(event->button() == Qt::LeftButton){ tabDragStartPosition = event->pos(); } else if(event->button() == Qt::RightButton){ if(View* view = pane->currentView()){ viewMenuManager.setNewPopupMenu(self); view->onAttachedMenuRequest(viewMenuManager); if(viewMenuManager.numItems() > 0){ viewMenuManager.addSeparator(); } viewMenuManager.addItem(_("Separate the view")) ->sigTriggered().connect([this, view](){ separateView(view); }); viewMenuManager.popupMenu()->popup(event->globalPos()); } } return false; } bool ViewArea::Impl::viewTabMouseMoveEvent(ViewPane* pane, QMouseEvent* event) { if(!isViewDragging){ if(event->buttons() & Qt::LeftButton){ if((event->pos() - tabDragStartPosition).manhattanLength() > QApplication::startDragDistance()){ if(!pane->tabBar()->geometry().contains(event->pos())){ draggedView = pane->currentView(); if(draggedView){ isViewDragging = true; dragSrcPane = pane; QWidget* toplevel = pane; while(toplevel->parentWidget()){ toplevel = toplevel->parentWidget(); } QSize s = toplevel->frameGeometry().size(); draggedViewWindowSize.setWidth(draggedView->width() + s.width() - toplevel->width()); draggedViewWindowSize.setHeight(draggedView->height() + s.height() - toplevel->height()); QApplication::setOverrideCursor(Qt::ClosedHandCursor); } } } } } else { ViewArea* prevViewArea = dragDestViewArea; dragDestViewArea = nullptr; dragDestPane = nullptr; // find a window other than the rubber band QPoint p = event->globalPos(); QWidget* window = nullptr; for(int i=0; i < 3; ++i){ window = QApplication::topLevelAt(p); if(window && !dynamic_cast<QRubberBand*>(window)){ break; } p += QPoint(-1, -1); } if(window){ dragDestViewArea = dynamic_cast<ViewArea*>(window); if(!dragDestViewArea){ if(MainWindow* mainWindow = dynamic_cast<MainWindow*>(window)){ ViewArea* viewArea = mainWindow->viewArea(); if(viewArea->rect().contains(viewArea->mapFromGlobal(event->globalPos()))){ dragDestViewArea = viewArea; } } } } if(dragDestViewArea){ QWidget* pointed = dragDestViewArea->childAt(dragDestViewArea->mapFromGlobal(event->globalPos())); while(pointed){ dragDestPane = dynamic_cast<ViewPane*>(pointed); if(dragDestPane){ dragView(event); break; } pointed = pointed->parentWidget(); } } else { dragViewOutside(event->globalPos()); } if(prevViewArea != dragDestViewArea){ if(prevViewArea){ prevViewArea->impl->rubberBand->hide(); } else { rubberBand->hide(); } } } return false; } bool ViewArea::Impl::viewTabMouseReleaseEvent(QMouseEvent *event) { if(isViewDragging){ bool isMovingInViewArea = (self == dragDestViewArea); removeView(dragSrcPane, draggedView, isMovingInViewArea); if(!dragDestPane){ rubberBand->hide(); dropViewOutside(event->globalPos()); } else { Impl* destImpl = dragDestViewArea->impl; destImpl->rubberBand->hide(); destImpl->needToUpdateDefaultPaneAreas = true; if(isViewDraggingOnOuterEdge){ destImpl->dropViewToOuterEdge(draggedView); } else { destImpl->dropViewInsidePane(dragDestPane, draggedView, dropEdge); } } if(isMovingInViewArea){ removePaneIfEmpty(dragSrcPane); } QApplication::restoreOverrideCursor(); } isViewDragging = false; draggedView = nullptr; dragDestViewArea = nullptr; dragDestPane = nullptr; return false; } void ViewArea::Impl::showRectangle(QRect r) { rubberBand->setParent(self); rubberBand->setGeometry(r); rubberBand->show(); } void ViewArea::Impl::dragView(QMouseEvent* event) { dropEdge = LEFT; QPoint p = dragDestViewArea->mapFromGlobal(event->globalPos()); const int w = dragDestViewArea->width(); const int h = dragDestViewArea->height(); int distance[4]; distance[LEFT] = p.x(); distance[TOP] = p.y(); distance[RIGHT] = w - p.x(); distance[BOTTOM] = h - p.y(); for(int i=TOP; i <= BOTTOM; ++i){ if(distance[dropEdge] > distance[i]){ dropEdge = i; } } if(distance[dropEdge] < 8){ isViewDraggingOnOuterEdge = true; dragViewOnOuterEdge(); } else { isViewDraggingOnOuterEdge = false; dragViewInsidePane(dragDestPane->mapFromGlobal(event->globalPos())); } } void ViewArea::Impl::dragViewInsidePane(const QPoint& posInDestPane) { dropEdge = LEFT; const int w = dragDestPane->width(); const int h = dragDestPane->height(); int distance[4]; distance[LEFT] = posInDestPane.x(); distance[TOP] = posInDestPane.y(); distance[RIGHT] = w - posInDestPane.x(); distance[BOTTOM] = h - posInDestPane.y(); for(int i=TOP; i <= BOTTOM; ++i){ if(distance[dropEdge] > distance[i]){ dropEdge = i; } } QRect r; if(SPLIT_DISTANCE_THRESHOLD < distance[dropEdge]){ r.setRect(0, 0, w, h); dropEdge = OVER; } else if(dropEdge == LEFT){ r.setRect(0, 0, w / 2, h); } else if(dropEdge == TOP){ r.setRect(0, 0, w, h /2); } else if(dropEdge == RIGHT){ r.setRect(w / 2, 0, w / 2, h); } else if(dropEdge == BOTTOM){ r.setRect(0, h / 2, w, h / 2); } r.translate(dragDestViewArea->mapFromGlobal(dragDestPane->mapToGlobal(QPoint(0, 0)))); dragDestViewArea->impl->showRectangle(r); } void ViewArea::Impl::dropViewInsidePane(ViewPane* pane, View* view, int dropEdge) { if(dropEdge == OVER){ addView(pane, view, true); } else { QSize destSize = pane->size(); QSplitter* parentSplitter = static_cast<QSplitter*>(pane->parentWidget()); if(parentSplitter->count() >= 2){ QList<int> sizes = parentSplitter->sizes(); QSplitter* newSplitter = new CustomSplitter(this, parentSplitter); parentSplitter->insertWidget(parentSplitter->indexOf(pane), newSplitter); newSplitter->addWidget(pane); parentSplitter->setSizes(sizes); parentSplitter = newSplitter; } ViewPane* newViewPane = new ViewPane(this, parentSplitter); if(dropEdge == LEFT){ parentSplitter->setOrientation(Qt::Horizontal); parentSplitter->insertWidget(0, newViewPane); } else if(dropEdge == RIGHT){ parentSplitter->setOrientation(Qt::Horizontal); parentSplitter->insertWidget(1, newViewPane); } else if(dropEdge == TOP){ parentSplitter->setOrientation(Qt::Vertical); parentSplitter->insertWidget(0, newViewPane); } else { parentSplitter->setOrientation(Qt::Vertical); parentSplitter->insertWidget(1, newViewPane); } addView(newViewPane, view, true); int half; if(parentSplitter->orientation() == Qt::Horizontal){ half = destSize.height() / 2; } else { half = destSize.width() / 2; } QList<int> sizes; sizes << half << half; parentSplitter->setSizes(sizes); } } void ViewArea::Impl::dragViewOnOuterEdge() { QRect r; int w = dragDestViewArea->width(); int h = dragDestViewArea->height(); if(dropEdge == LEFT){ r.setRect(0, 0, w / 2, h); } else if(dropEdge == TOP){ r.setRect(0, 0, w, h /2); } else if(dropEdge == RIGHT){ r.setRect(w / 2, 0, w / 2, h); } else if(dropEdge == BOTTOM){ r.setRect(0, h / 2, w, h / 2); } dragDestViewArea->impl->showRectangle(r); } void ViewArea::Impl::dropViewToOuterEdge(View* view) { QSize size = topSplitter->size(); if(topSplitter->count() >= 2){ QSplitter* newTopSplitter = new CustomSplitter(this, self); newTopSplitter->addWidget(topSplitter); topSplitter = newTopSplitter; vbox->addWidget(topSplitter); } ViewPane* newViewPane = new ViewPane(this, topSplitter); if(dropEdge == LEFT){ topSplitter->setOrientation(Qt::Horizontal); topSplitter->insertWidget(0, newViewPane); } else if(dropEdge == RIGHT){ topSplitter->setOrientation(Qt::Horizontal); topSplitter->addWidget(newViewPane); } else if(dropEdge == TOP){ topSplitter->setOrientation(Qt::Vertical); topSplitter->insertWidget(0, newViewPane); } else { topSplitter->setOrientation(Qt::Vertical); topSplitter->addWidget(newViewPane); } addView(newViewPane, view, true); int half; if(topSplitter->orientation() == Qt::Horizontal){ half = size.height() / 2; } else { half = size.width() / 2; } QList<int> sizes; sizes << half << half; topSplitter->setSizes(sizes); } void ViewArea::Impl::dragViewOutside(const QPoint& pos) { rubberBand->setParent(0); rubberBand->setGeometry(QRect(pos, draggedViewWindowSize)); rubberBand->show(); } void ViewArea::Impl::dropViewOutside(const QPoint& pos) { ViewArea* viewWindow = new ViewArea; viewWindow->setSingleView(draggedView); viewWindow->move(pos); viewWindow->resize(draggedViewWindowSize); viewWindow->show(); } void ViewArea::Impl::separateView(View* view) { QPoint pos = view->mapToGlobal(QPoint(0, 0)); removeView(view); ViewArea* viewWindow = new ViewArea; viewWindow->setSingleView(view); viewWindow->setGeometry(pos.x(), pos.y(), view->width(), view->height()); viewWindow->show(); } void ViewArea::Impl::removePaneIfEmpty(ViewPane* pane) { if(pane->count() == 0){ removePaneSub(pane, nullptr); needToUpdateDefaultPaneAreas = true; } } void ViewArea::Impl::removePaneSub(QWidget* widgetToRemove, QWidget* widgetToRaise) { if(QSplitter* splitter = dynamic_cast<QSplitter*>(widgetToRemove->parentWidget())){ QList<int> sizes; if(widgetToRaise){ sizes = splitter->sizes(); splitter->insertWidget(splitter->indexOf(widgetToRemove), widgetToRaise); } widgetToRemove->hide(); widgetToRemove->setParent(nullptr); widgetToRemove->deleteLater(); if(splitter->count() >= 2){ splitter->setSizes(sizes); } else if(splitter->count() == 1){ removePaneSub(splitter, splitter->widget(0)); } else { removePaneSub(splitter, 0); } } } void ViewArea::Impl::clearEmptyPanes() { QWidget* widget = clearEmptyPanesSub(topSplitter); if(widget != topSplitter){ if(widget){ if(QSplitter* splitter = dynamic_cast<QSplitter*>(widget)){ splitter->setParent(self); topSplitter->hide(); topSplitter->deleteLater(); vbox->addWidget(splitter); topSplitter = splitter; } } } } QWidget* ViewArea::Impl::clearEmptyPanesSub(QSplitter* splitter) { QList<int> sizes = splitter->sizes(); int i = 0; while(i < splitter->count()){ if(QSplitter* childSplitter = dynamic_cast<QSplitter*>(splitter->widget(i))){ QWidget* widget = clearEmptyPanesSub(childSplitter); if(widget == childSplitter){ ++i; } else { if(widget){ splitter->insertWidget(i++, widget); } // "delete childSplitter" causes a crash childSplitter->hide(); childSplitter->setParent(0); childSplitter->deleteLater(); } } else if(ViewPane* pane = dynamic_cast<ViewPane*>(splitter->widget(i))){ if(pane->count() > 0){ ++i; } else { // "delete pane" causes a crash pane->hide(); pane->setParent(0); pane->deleteLater(); needToUpdateDefaultPaneAreas = true; } } } QWidget* validWidget = nullptr; if(splitter->count() >= 2){ splitter->setSizes(sizes); validWidget = splitter; } else if(splitter->count() == 1){ validWidget = splitter->widget(0); needToUpdateDefaultPaneAreas = true; } return validWidget; }
29.354021
124
0.569338
team-FisMa
a98c6659e7e2d09cd339050f1085f6014755868e
1,532
cpp
C++
test/bdev/bdevc++/common/DefaultAllocStrategy.cpp
janlt/spdk
263a281579bd956acf596cd3587872c209050816
[ "BSD-3-Clause" ]
1
2020-04-15T12:13:35.000Z
2020-04-15T12:13:35.000Z
test/bdev/bdevc++/common/DefaultAllocStrategy.cpp
janlt/spdk
263a281579bd956acf596cd3587872c209050816
[ "BSD-3-Clause" ]
null
null
null
test/bdev/bdevc++/common/DefaultAllocStrategy.cpp
janlt/spdk
263a281579bd956acf596cd3587872c209050816
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DefaultAllocStrategy.h" namespace BdevCpp { DefaultAllocStrategy::DefaultAllocStrategy(const DefaultAllocStrategy &right) : AllocStrategy() {} AllocStrategy *DefaultAllocStrategy::copy() const { return new DefaultAllocStrategy(*this); } unsigned int DefaultAllocStrategy::preallocateCount() const { return defaultPreallocCount; } unsigned int DefaultAllocStrategy::incrementQuant() const { return defaultIncCount; } unsigned int DefaultAllocStrategy::decrementQuant() const { return defaultDecCount; } unsigned int DefaultAllocStrategy::minIncQuant() const { return defaultMinIncQuant; } unsigned int DefaultAllocStrategy::maxIncQuant() const { return defaultMaxIncQuant; } unsigned int DefaultAllocStrategy::minDecQuant() const { return defaultMinDecQuant; } unsigned int DefaultAllocStrategy::maxDecQuant() const { return defaultMaxDecQuant; } } // namespace BdevCpp
27.357143
77
0.762402
janlt
a98cf83342e38836ba0b91c858fd5f2a5ef5dad5
50
cpp
C++
KonvDateiNeu.cpp
jbxplan/GMLToolbox-src
fec35558787db18d222598e376bc7c1071c69a55
[ "Apache-2.0" ]
2
2021-05-04T06:23:46.000Z
2022-02-04T21:40:07.000Z
KonvDateiNeu.cpp
jbxplan/GMLToolbox-src
fec35558787db18d222598e376bc7c1071c69a55
[ "Apache-2.0" ]
null
null
null
KonvDateiNeu.cpp
jbxplan/GMLToolbox-src
fec35558787db18d222598e376bc7c1071c69a55
[ "Apache-2.0" ]
2
2020-07-13T12:14:11.000Z
2021-05-04T06:23:49.000Z
#include "StdAfx.h" #include "KonvDateiNeu.h"
12.5
26
0.68
jbxplan
a98de385549e00f2d6b052025a8762437b3ef5ed
5,714
hpp
C++
src/oatpp/core/collection/ListMap.hpp
swarkentin/oatpp
6838f37c04277e44b22e23df33e8eded70701f3c
[ "Apache-2.0" ]
1
2019-11-19T17:46:28.000Z
2019-11-19T17:46:28.000Z
src/oatpp/core/collection/ListMap.hpp
swarkentin/oatpp
6838f37c04277e44b22e23df33e8eded70701f3c
[ "Apache-2.0" ]
1
2019-11-22T15:42:39.000Z
2019-11-22T15:42:39.000Z
src/oatpp/core/collection/ListMap.hpp
swarkentin/oatpp
6838f37c04277e44b22e23df33e8eded70701f3c
[ "Apache-2.0" ]
1
2019-11-22T00:45:50.000Z
2019-11-22T00:45:50.000Z
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_collection_ListMap_hpp #define oatpp_collection_ListMap_hpp #include "oatpp/core/base/memory/ObjectPool.hpp" #include "oatpp/core/base/Countable.hpp" namespace oatpp { namespace collection { template<class K, class V> class ListMap : public oatpp::base::Countable { public: OBJECT_POOL(ListMap_Pool, ListMap, 32) SHARED_OBJECT_POOL(Shared_ListMap_Pool, ListMap, 32) public: //-------------------------------------------------------------------------------------- // Entry class Entry{ friend ListMap; public: OBJECT_POOL_THREAD_LOCAL(ListMap_Entry_Pool, Entry, 64) private: K key; V value; Entry* next; protected: Entry(const K& pKey, const V& pValue, Entry* pNext) : key(pKey) , value(pValue) , next(pNext) {} ~Entry(){ } public: const K& getKey() const{ return key; } const V& getValue() const{ return value; } Entry* getNext() const{ return next; } }; private: Entry* m_first; Entry* m_last; v_int32 m_count; oatpp::base::memory::MemoryPool& m_itemMemoryPool; private: Entry* createEntry(const K& pKey, const V& pValue, Entry* pNext){ return new (m_itemMemoryPool.obtain()) Entry(pKey, pValue, pNext); } void destroyEntry(Entry* entry){ entry->~Entry(); oatpp::base::memory::MemoryPool::free(entry); } private: Entry* getEntry(v_int32 index) const{ if(index >= m_count){ return nullptr; } v_int32 i = 0; Entry* curr = m_first; while(curr != nullptr){ if(i == index){ return curr; } curr = curr->next; i++; } return nullptr; } template<class Key> Entry* getEntryByKey(const Key& key) const{ Entry* curr = m_first; while(curr != nullptr){ if(key == curr->key){ return curr; } curr = curr->next; } return nullptr; } void addOneEntry(Entry* entry){ if(m_last == nullptr){ m_first = entry; m_last = entry; }else{ m_last->next = entry; m_last = entry; } m_count++; } public: ListMap() : m_first(nullptr) , m_last(nullptr) , m_count(0) , m_itemMemoryPool(Entry::ListMap_Entry_Pool::getPool()) {} public: static std::shared_ptr<ListMap> createShared(){ return Shared_ListMap_Pool::allocateShared(); } ~ListMap() override { clear(); } Entry* put(const K& key, const V& value){ Entry* entry = getEntryByKey(key); if(entry != nullptr){ if(entry->value != value){ entry->value = value; } }else{ entry = createEntry(key, value, nullptr); addOneEntry(entry); } return entry; } bool putIfNotExists(const K& key, const V& value){ Entry* entry = getEntryByKey(key); if(entry == nullptr){ entry = createEntry(key, value, nullptr); addOneEntry(entry); return true; } return false; } const Entry* find(const K& key) const{ Entry* entry = getEntryByKey<K>(key); if(entry != nullptr){ return entry; } return nullptr; } const V& get(const K& key, const V& defaultValue) const { Entry* entry = getEntryByKey<K>(key); if(entry != nullptr){ return entry->getValue(); } return defaultValue; } /* template <class Key> const Entry* getByKeyTemplate(const Key& key) const{ Entry* entry = getEntryByKey(key); if(entry != nullptr){ return entry; } return nullptr; } */ V remove(const K& key){ if(m_first != nullptr){ if(m_first->key->equals(key)){ Entry* next = m_first->next; V result = m_first->value; destroyEntry(m_first); m_first = next; return result; } Entry* curr = m_first; Entry* next = m_first->next; while(next != nullptr){ if(next->key->equals(key)){ V result = next->value; curr->next = next->next; destroyEntry(next); return result; } curr = next; next = curr->next; } } return V::empty(); } Entry* getFirstEntry() const { return m_first; } v_int32 count() const{ return m_count; } void clear(){ Entry* curr = m_first; while(curr != nullptr){ Entry* next = curr->next; destroyEntry(curr); curr = next; } m_first = nullptr; m_last = nullptr; m_count = 0; } }; }} #endif /* oatpp_collection_ListMap_hpp */
20.553957
90
0.543052
swarkentin
a98dff33bb3eecd4a229af12682359bbf2f87ffc
14,672
cpp
C++
src/api/processors/thumbnail.cpp
sucangit/images
6171702646129b3dadbbeb7bfe75e4ac9379b714
[ "BSD-3-Clause" ]
826
2018-06-22T07:20:04.000Z
2022-03-31T21:52:34.000Z
src/api/processors/thumbnail.cpp
sucangit/images
6171702646129b3dadbbeb7bfe75e4ac9379b714
[ "BSD-3-Clause" ]
210
2018-06-18T15:50:12.000Z
2022-03-30T22:56:28.000Z
src/api/processors/thumbnail.cpp
sucangit/images
6171702646129b3dadbbeb7bfe75e4ac9379b714
[ "BSD-3-Clause" ]
121
2018-06-19T19:41:43.000Z
2022-03-20T19:20:29.000Z
#include "thumbnail.h" #include "../exceptions/large.h" #include <algorithm> #include <cmath> #include <string> #include <tuple> namespace weserv { namespace api { namespace processors { using enums::Canvas; using enums::ImageType; // Set to true in order to have a greater advantage of the JPEG // shrink-on-load feature. You can set this to false for more // consistent results and to avoid occasional small image shifting. // NOTE: Can be overridden with `&fsol=0`. const bool FAST_SHRINK_ON_LOAD = true; using io::Source; std::pair<double, double> Thumbnail::resolve_shrink(int width, int height) const { auto rotation = query_->get<int>("angle", 0); auto precrop = query_->get<bool>("precrop", false); if (!precrop && (rotation == 90 || rotation == 270)) { // Swap input width and height when rotating by 90 or 270 degrees std::swap(width, height); } double hshrink = 1.0; double vshrink = 1.0; auto target_width = query_->get<int>("w"); auto target_height = query_->get<int>("h"); auto canvas = query_->get<Canvas>("fit", Canvas::Max); if (target_width > 0 && target_height > 0) { // Fixed width and height hshrink = static_cast<double>(width) / target_width; vshrink = static_cast<double>(height) / target_height; switch (canvas) { case Canvas::Crop: case Canvas::Min: if (hshrink < vshrink) { vshrink = hshrink; } else { hshrink = vshrink; } break; case Canvas::Embed: case Canvas::Max: if (hshrink > vshrink) { vshrink = hshrink; } else { hshrink = vshrink; } break; case Canvas::IgnoreAspect: if (!precrop && (rotation == 90 || rotation == 270)) { std::swap(hshrink, vshrink); } break; } } else if (target_width > 0) { // Fixed width hshrink = static_cast<double>(width) / target_width; if (canvas != Canvas::IgnoreAspect) { // Auto height vshrink = hshrink; } } else if (target_height > 0) { // Fixed height vshrink = static_cast<double>(height) / target_height; if (canvas != Canvas::IgnoreAspect) { // Auto width hshrink = vshrink; } } // Should we not enlarge (oversample) the output image? if (query_->get<bool>("we", false)) { hshrink = std::max(1.0, hshrink); vshrink = std::max(1.0, vshrink); } // We don't want to shrink so much that we send an axis to 0 hshrink = std::min(hshrink, static_cast<double>(width)); vshrink = std::min(vshrink, static_cast<double>(height)); return std::make_pair(hshrink, vshrink); } double Thumbnail::resolve_common_shrink(int width, int height) const { double hshrink; double vshrink; std::tie(hshrink, vshrink) = resolve_shrink(width, height); return std::min(hshrink, vshrink); } int Thumbnail::resolve_jpeg_shrink(int width, int height) const { double shrink = resolve_common_shrink(width, height); int shrink_on_load_factor = query_->get<bool>("fsol", FAST_SHRINK_ON_LOAD) ? 1 : 2; // Shrink-on-load is a simple block shrink and will // add quite a bit of extra sharpness to the image. if (shrink >= 8 * shrink_on_load_factor) { return 8; } if (shrink >= 4 * shrink_on_load_factor) { return 4; } if (shrink >= 2 * shrink_on_load_factor) { return 2; } return 1; } int Thumbnail::resolve_tiff_pyramid(const VImage &image, const Source &source, int width, int height) const { // Note: This is checked against config_.max_pages in stream.cpp. int n_pages = image.get_typeof(VIPS_META_N_PAGES) != 0 ? image.get_int(VIPS_META_N_PAGES) : 1; // Only one page? Can't be if (n_pages < 2) { return -1; } int target_page = -1; for (int i = n_pages - 1; i >= 0; i--) { auto page = #ifdef WESERV_ENABLE_TRUE_STREAMING VImage::new_from_source( source, "", #else VImage::new_from_buffer( source.buffer(), "", #endif VImage::option() ->set("access", VIPS_ACCESS_SEQUENTIAL) ->set("fail", config_.fail_on_error == 1) ->set("page", i)); int level_width = page.width(); int level_height = page.height(); // Try to sanity-check the size of the pages. Do they look // like a pyramid? int expected_level_width = width / (1 << i); int expected_level_height = height / (1 << i); // Won't be exact due to rounding etc. if (std::abs(level_width - expected_level_width) > 5 || std::abs(level_height - expected_level_height) > 5 || level_width < 2 || level_height < 2) { return -1; } if (target_page == -1 && resolve_common_shrink(level_width, level_height) >= 1.0) { target_page = i; // We may have found a pyramid, but we // have to finish the loop to be sure. } } return target_page; } // TODO(kleisauke): Support whole-slide images(?) /*int Thumbnail::resolve_open_slide_level(const VImage &image) const { int level_count = 1; if (image.get_typeof("openslide.level-count") != 0) { level_count = std::max(1, std::min(image.get_int("openslide.level-count"), static_cast<int>(config_.max_pages))); } for (int level = level_count - 1; level >= 0; level--) { auto level_str = "openslide.level[" + std::to_string(level) + "]"; auto level_width_field = level_str + ".width"; auto level_height_field = level_str + ".height"; if (image.get_typeof(level_width_field.c_str()) == 0 || image.get_typeof(level_height_field.c_str()) == 0) { continue; } auto level_width = std::stoi(image.get_string(level_width_field.c_str())); auto level_height = std::stoi(image.get_string(level_height_field.c_str())); if (resolve_common_shrink(level_width, level_height) >= 1.0) { return level; } } return 0; }*/ void Thumbnail::append_page_options(vips::VOption *options) const { auto n = query_->get<int>("n"); auto page = query_->get_if<int>( "page", [](int p) { // Page needs to be in the range of // 0 (numbered from zero) - 100000 return p >= 0 && p <= 100000; }, 0); options->set("n", n); options->set("page", page); } VImage Thumbnail::shrink_on_load(const VImage &image, const Source &source) const { // Try to reload input using shrink-on-load, when: // - the width or height parameters are specified. // - gamma correction doesn't need to be applied. // - trimming isn't required. if (query_->get<bool>("trim", false) || query_->get<float>("gam", 0.0F) != 0.0F || (query_->get<int>("w") == 0 && query_->get<int>("h") == 0)) { return image; } int width = image.width(); int height = image.height(); vips::VOption *load_options = VImage::option() ->set("access", VIPS_ACCESS_SEQUENTIAL) ->set("fail", config_.fail_on_error == 1); auto image_type = query_->get<ImageType>("type", ImageType::Unknown); if (image_type == ImageType::Jpeg) { auto shrink = resolve_jpeg_shrink(width, height); #ifdef WESERV_ENABLE_TRUE_STREAMING return VImage::new_from_source(source, "", #else return VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("shrink", shrink)); } else if (image_type == ImageType::Pdf || image_type == ImageType::Webp) { append_page_options(load_options); auto scale = 1.0 / resolve_common_shrink(width, utils::get_page_height(image)); #ifdef WESERV_ENABLE_TRUE_STREAMING return VImage::new_from_source(source, "", #else return VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("scale", scale)); } else if (image_type == ImageType::Tiff) { auto page = resolve_tiff_pyramid(image, source, width, height); // We've found a pyramid if (page != -1) { #ifdef WESERV_ENABLE_TRUE_STREAMING return VImage::new_from_source(source, "", #else return VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("page", page)); } /*} else if (image_type == ImageType::OpenSlide) { auto level = resolve_open_slide_level(image); #ifdef WESERV_ENABLE_TRUE_STREAMING return VImage::new_from_source(source, "", #else return VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("level", level));*/ } else if (image_type == ImageType::Svg) { auto scale = 1.0 / resolve_common_shrink(width, height); #ifdef WESERV_ENABLE_TRUE_STREAMING return VImage::new_from_source(source, "", #else return VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("scale", scale)); } else if (image_type == ImageType::Heif) { append_page_options(load_options); // Fetch the size of the stored thumbnail #ifdef WESERV_ENABLE_TRUE_STREAMING auto thumb = VImage::new_from_source(source, "", #else auto thumb = VImage::new_from_buffer(source.buffer(), "", #endif load_options->set("thumbnail", true)); // Use the thumbnail if, by using it, we could get a factor > 1.0, // i.e. we would not need to expand the thumbnail. // Don't use >= since factor can be clipped to 1.0 under some // resizing modes. return resolve_common_shrink(thumb.width(), thumb.height()) > 1.0 ? thumb : image; } // Still here? The loader probably doesn't support shrink-on-load. // Delete the options we allocated above delete load_options; // And return the original image return image; } VImage Thumbnail::process(const VImage &image) const { // Any pre-shrinking may already have been done auto thumb = image; // So page_height is after pre-shrink, but before the main shrink stage // Pre-resize extract needs to fetch the page height from the query holder auto page_height = query_->get<int>("page_height", utils::get_page_height(thumb)); // RAD needs special unpacking. if (thumb.coding() == VIPS_CODING_RAD) { // rad is scRGB thumb = thumb.rad2float(); } // If this is a CMYK image, we only want to export at the end bool is_cmyk = thumb.interpretation() == VIPS_INTERPRETATION_CMYK; // To the processing colourspace. This will unpack LABQ, import CMYK // etc. thumb = thumb.colourspace(VIPS_INTERPRETATION_sRGB); int thumb_width = thumb.width(); int thumb_height = thumb.height(); double hshrink; double vshrink; // Shrink to page_height, so we work for multi-page images std::tie(hshrink, vshrink) = resolve_shrink(thumb_width, page_height); auto target_width = static_cast<int>(std::rint(static_cast<double>(thumb_width) / hshrink)); auto target_page_height = static_cast<int>(std::rint(static_cast<double>(page_height) / vshrink)); auto target_image_height = target_page_height; // In toilet-roll mode, we must adjust vshrink so that we exactly hit // page_height or we'll have pixels straddling pixel boundaries. if (thumb_height > page_height) { auto n_pages = query_->get<int>("n"); target_image_height *= n_pages; vshrink = static_cast<double>(thumb_height) / target_image_height; } // Limit output images to a given number of pixels, where // pixels = width * height if (config_.limit_output_pixels > 0 && static_cast<uint64_t>(target_width) * target_image_height > config_.limit_output_pixels) { throw exceptions::TooLargeImageException( "Output image exceeds pixel limit. " "Width x height should be less than " + std::to_string(config_.limit_output_pixels)); } // If there's an alpha, we have to premultiply before shrinking. See // https://github.com/libvips/libvips/issues/291 VipsBandFormat unpremultiplied_format = VIPS_FORMAT_NOTSET; if (thumb.has_alpha() && hshrink != 1.0 && vshrink != 1.0) { // .premultiply() makes a float image. When we .unpremultiply() below, // we need to cast back to the pre-premultiply format. unpremultiplied_format = thumb.format(); thumb = thumb.premultiply(); } thumb = thumb.resize(1.0 / hshrink, VImage::option()->set("vscale", 1.0 / vshrink)); query_->update("page_height", target_page_height); if (unpremultiplied_format != VIPS_FORMAT_NOTSET) { thumb = thumb.unpremultiply().cast(unpremultiplied_format); } // Colour management. // If this is a CMYK image, just export. Otherwise, we're in // device space and we need a combined import/export to transform to // the target space. if (is_cmyk) { thumb = thumb.icc_export(VImage::option() ->set("output_profile", "srgb") ->set("intent", VIPS_INTENT_PERCEPTUAL)); } else if (utils::has_profile(thumb)) { thumb = thumb.icc_transform( "srgb", VImage::option() // Fallback to srgb ->set("input_profile", "srgb") // Use "perceptual" intent to better match imagemagick ->set("intent", VIPS_INTENT_PERCEPTUAL) ->set("embedded", true)); } return thumb; } } // namespace processors } // namespace api } // namespace weserv
33.497717
80
0.582061
sucangit
a98ef7f7aa35078dd39e14254884d93be6f559bd
401
cpp
C++
cpp/src/player_utils.cpp
calincru/UltimateTicTacToe
2811c9021369f97dd3d6fa4f2247cbadb1aece49
[ "Apache-2.0" ]
null
null
null
cpp/src/player_utils.cpp
calincru/UltimateTicTacToe
2811c9021369f97dd3d6fa4f2247cbadb1aece49
[ "Apache-2.0" ]
null
null
null
cpp/src/player_utils.cpp
calincru/UltimateTicTacToe
2811c9021369f97dd3d6fa4f2247cbadb1aece49
[ "Apache-2.0" ]
null
null
null
// Self #include "player_utils.hpp" // Project #include "utils.hpp" namespace tictactoe { player_e player_utils::opponent(player_e player) { TTT_ASSERT(player == player_e::ME || player == player_e::OPPONENT, "opponent precondition"); return player == player_e::OPPONENT ? player_e::ME : player_e::OPPONENT; } } // namespace tictactoe
23.588235
70
0.618454
calincru
817bbc88fc0a18ff51f05c50dd8c600457b3c84e
4,512
cpp
C++
core/src/data/tileSource.cpp
flyskyosg/tangram-es
7d0d7297485fdb388455b15810690c1568bdbedb
[ "MIT" ]
null
null
null
core/src/data/tileSource.cpp
flyskyosg/tangram-es
7d0d7297485fdb388455b15810690c1568bdbedb
[ "MIT" ]
null
null
null
core/src/data/tileSource.cpp
flyskyosg/tangram-es
7d0d7297485fdb388455b15810690c1568bdbedb
[ "MIT" ]
1
2019-08-31T14:43:29.000Z
2019-08-31T14:43:29.000Z
#include "data/tileSource.h" #include "data/formats/geoJson.h" #include "data/formats/mvt.h" #include "data/formats/topoJson.h" #include "data/tileData.h" #include "platform.h" #include "tile/tileID.h" #include "tile/tile.h" #include "tile/tileTask.h" #include "log.h" #include <atomic> #include <functional> namespace Tangram { TileSource::TileSource(const std::string& _name, std::unique_ptr<DataSource> _sources, int32_t _minDisplayZoom, int32_t _maxDisplayZoom, int32_t _maxZoom) : m_name(_name), m_minDisplayZoom(_minDisplayZoom), m_maxDisplayZoom(_maxDisplayZoom), m_maxZoom(_maxZoom), m_sources(std::move(_sources)) { static std::atomic<int32_t> s_serial; m_id = s_serial++; } TileSource::~TileSource() { clearData(); } const char* TileSource::mimeType() const { switch (m_format) { case Format::GeoJson: return "application/geo+json"; case Format::TopoJson: return "application/topo+json"; case Format::Mvt: return "application/vnd.mapbox-vector-tile"; } } std::shared_ptr<TileTask> TileSource::createTask(TileID _tileId, int _subTask) { auto task = std::make_shared<BinaryTileTask>(_tileId, shared_from_this(), _subTask); createSubTasks(task); return task; } void TileSource::createSubTasks(std::shared_ptr<TileTask> _task) { size_t index = 0; for (auto& subSource : m_rasterSources) { TileID subTileID = _task->tileId(); // get tile for lower zoom if we are past max zoom if (subTileID.z > subSource->maxZoom()) { subTileID = subTileID.withMaxSourceZoom(subSource->maxZoom()); } _task->subTasks().push_back(subSource->createTask(subTileID, index++)); } } void TileSource::clearData() { if (m_sources) { m_sources->clear(); } m_generation++; } bool TileSource::equals(const TileSource& other) const { if (m_name != other.m_name) { return false; } // TODO compare DataSources instead //if (m_urlTemplate != other.m_urlTemplate) { return false; } if (m_minDisplayZoom != other.m_minDisplayZoom) { return false; } if (m_maxDisplayZoom != other.m_maxDisplayZoom) { return false; } if (m_maxZoom != other.m_maxZoom) { return false; } if (m_rasterSources.size() != other.m_rasterSources.size()) { return false; } for (size_t i = 0, end = m_rasterSources.size(); i < end; ++i) { if (!m_rasterSources[i]->equals(*other.m_rasterSources[i])) { return false; } } return true; } void TileSource::loadTileData(std::shared_ptr<TileTask> _task, TileTaskCb _cb) { if (m_sources) { if (_task->needsLoading()) { if (m_sources->loadTileData(_task, _cb)) { _task->startedLoading(); } } else if(_task->hasData()) { _cb.func(_task); } } for (auto& subTask : _task->subTasks()) { subTask->source().loadTileData(subTask, _cb); } } std::shared_ptr<TileData> TileSource::parse(const TileTask& _task, const MapProjection& _projection) const { switch (m_format) { case Format::TopoJson: return TopoJson::parseTile(_task, _projection, m_id); case Format::GeoJson: return GeoJson::parseTile(_task, _projection, m_id); case Format::Mvt: return Mvt::parseTile(_task, _projection, m_id); } } void TileSource::cancelLoadingTile(const TileID& _tileID) { if (m_sources) { return m_sources->cancelLoadingTile(_tileID); } for (auto& raster : m_rasterSources) { TileID rasterID = _tileID.withMaxSourceZoom(raster->maxZoom()); raster->cancelLoadingTile(rasterID); } } void TileSource::clearRasters() { for (auto& raster : m_rasterSources) { raster->clearRasters(); } } void TileSource::clearRaster(const TileID& id) { for (auto& raster : m_rasterSources) { TileID rasterID = id.withMaxSourceZoom(raster->maxZoom()); raster->clearRaster(rasterID); } } void TileSource::addRasterSource(std::shared_ptr<TileSource> _rasterSource) { /* * We limit the parent source by any attached raster source's min/max. */ int32_t rasterMinDisplayZoom = _rasterSource->minDisplayZoom(); int32_t rasterMaxDisplayZoom = _rasterSource->maxDisplayZoom(); if (rasterMinDisplayZoom > m_minDisplayZoom) { m_minDisplayZoom = rasterMinDisplayZoom; } if (rasterMaxDisplayZoom < m_maxDisplayZoom) { m_maxDisplayZoom = rasterMaxDisplayZoom; } m_rasterSources.push_back(_rasterSource); } }
29.684211
108
0.672651
flyskyosg
817d9f34d37507b0c168d13ff88f415f94b5604e
1,455
cpp
C++
z2/src/WyrazenieZesp.cpp
MultiMixization/ZadanieLiczbyZepsolone
c6e4d0d66497bd5347a23e17714f1777a9678fbc
[ "MIT" ]
null
null
null
z2/src/WyrazenieZesp.cpp
MultiMixization/ZadanieLiczbyZepsolone
c6e4d0d66497bd5347a23e17714f1777a9678fbc
[ "MIT" ]
null
null
null
z2/src/WyrazenieZesp.cpp
MultiMixization/ZadanieLiczbyZepsolone
c6e4d0d66497bd5347a23e17714f1777a9678fbc
[ "MIT" ]
null
null
null
#include "WyrazenieZesp.hh" using std::cout; using std::cin; /* * Tu nalezy zdefiniowac funkcje, ktorych zapowiedzi znajduja sie * w pliku naglowkowym. */ std::istream & operator >> (std::istream & strm, Operator & Op) { char znak; strm >> znak; switch(znak) { case '+': Op=Op_Dodaj; break; case '-': Op=Op_Odejmij; break; case '*': Op=Op_Mnoz; break; case '/': Op=Op_Dziel; break; } return strm; } std::istream & operator >> (std::istream & strm, WyrazenieZesp & Wz) { strm >> Wz.Arg1 >> Wz.Op >> Wz.Arg2; return strm; } std::ostream & operator << (std::ostream & strm, Operator Op) { switch(Op) { case Op_Dodaj: strm << "+"; break; case Op_Odejmij: strm << "-"; break; case Op_Mnoz: strm << "*"; break; case Op_Dziel: strm << "/"; break; } return strm; } std::ostream & operator << (std::ostream & strm, WyrazenieZesp Wz) { strm << Wz.Arg1 << " " << Wz.Op << " " << Wz.Arg2; return strm; } LZespolona Oblicz(WyrazenieZesp WyrZ) { switch(WyrZ.Op) { case Op_Dodaj: return WyrZ.Arg1+WyrZ.Arg2; break; case Op_Odejmij: return WyrZ.Arg1-WyrZ.Arg2; break; case Op_Mnoz: return WyrZ.Arg1*WyrZ.Arg2; break; case Op_Dziel: return WyrZ.Arg1/WyrZ.Arg2; break; } return WyrZ.Arg1; //Zeby kompilator nie narzekal }
17.321429
68
0.557388
MultiMixization
817e85987e99618d4499db11459e34b90e714d99
1,954
cpp
C++
firmware/src/lib/simple_fs/mock_spi_flash.cpp
rundb/dictofun
cc9d80da88819095ef0fdcdf816d976c2afa4eba
[ "Apache-2.0" ]
6
2021-10-07T18:34:51.000Z
2022-02-03T20:34:26.000Z
firmware/src/lib/simple_fs/mock_spi_flash.cpp
rundb/dictofun
cc9d80da88819095ef0fdcdf816d976c2afa4eba
[ "Apache-2.0" ]
29
2021-10-08T20:37:47.000Z
2022-03-18T20:27:53.000Z
firmware/src/lib/simple_fs/mock_spi_flash.cpp
rundb/dictofun
cc9d80da88819095ef0fdcdf816d976c2afa4eba
[ "Apache-2.0" ]
2
2021-10-06T16:13:56.000Z
2021-10-08T20:42:56.000Z
// SPDX-License-Identifier: Apache-2.0 /* * Copyright (c) 2022, Roman Turkin */ #include "simple_fs.h" #include <cstring> #include <iostream> using namespace std; namespace test { // Simulating a standard 128Mbit memory (16 Mb) constexpr size_t MOCK_MEMORY_SIZE = 16 * 1024 * 1024; constexpr size_t PAGE_SIZE = 256; constexpr size_t SECTOR_SIZE = 4096; static uint8_t _memory_mock[MOCK_MEMORY_SIZE]; void initFsMock() { for(size_t i = 0; i < MOCK_MEMORY_SIZE; ++i) { _memory_mock[i] = 0xFF; } } result::Result spiMockRead(const uint32_t address, uint8_t* data, const size_t size) { if(address >= MOCK_MEMORY_SIZE) return result::Result::ERROR_INVALID_PARAMETER; memcpy(data, &_memory_mock[address], size); return result::Result::OK; } result::Result spiMockWrite(const uint32_t address, const uint8_t* const data, const size_t size) { if(address >= MOCK_MEMORY_SIZE || (address % PAGE_SIZE != 0)) return result::Result::ERROR_INVALID_PARAMETER; memcpy(&_memory_mock[address], data, size); return result::Result::OK; } result::Result spiMockErase(const uint32_t address, const size_t size) { if(address % SECTOR_SIZE != 0 || size % SECTOR_SIZE != 0) return result::Result::ERROR_INVALID_PARAMETER; for(uint32_t pos = address; pos < address + size; ++pos) { _memory_mock[pos] = 0xFF; } return result::Result::OK; } void print_memory(size_t offset, size_t size) { if(offset > sizeof(_memory_mock)) return; size_t printed = 0; cout << offset << "\t"; while(printed < size) { cout << hex << (int)_memory_mock[offset + printed] << " "; printed++; if((offset + printed) % 16 == 0) cout << endl << hex << (offset + printed) << "\t"; } } filesystem::SpiFlashConfiguration test_spi_flash_config = { spiMockRead, spiMockWrite, spiMockErase, PAGE_SIZE, SECTOR_SIZE}; } // namespace test
27.138889
97
0.66479
rundb
818230de7f12ce5819ad5de75759369dfb91b5c0
2,483
cpp
C++
ql/experimental/mcbasket/mcpathbasketengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/experimental/mcbasket/mcpathbasketengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/experimental/mcbasket/mcpathbasketengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Andrea Odetti This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/experimental/mcbasket/mcpathbasketengine.hpp> namespace QuantLib { EuropeanPathMultiPathPricer::EuropeanPathMultiPathPricer( std::shared_ptr<PathPayoff> & payoff, const std::vector<Size> & timePositions, const std::vector<Handle<YieldTermStructure> > & forwardTermStructures, const Array & discounts) : payoff_(payoff), timePositions_(timePositions), forwardTermStructures_(forwardTermStructures), discounts_(discounts) {} Real EuropeanPathMultiPathPricer::operator()(const MultiPath& multiPath) const { Size n = multiPath.pathSize(); QL_REQUIRE(n > 0, "the path cannot be empty"); Size numberOfAssets = multiPath.assetNumber(); QL_REQUIRE(numberOfAssets > 0, "there must be some paths"); const Size numberOfTimes = timePositions_.size(); Matrix path(numberOfAssets, numberOfTimes, Null<Real>()); for (Size i = 0; i < numberOfTimes; ++i) { const Size pos = timePositions_[i]; for (Size j = 0; j < numberOfAssets; ++j) path[j][i] = multiPath[j][pos]; } Array values(numberOfTimes, 0.0); // ignored Array exercises; std::vector<Array> states; payoff_->value(path, forwardTermStructures_, values, exercises, states); // in this engine we ignore early exercise Real discountedPayoff = DotProduct(values, discounts_); return discountedPayoff; } }
37.059701
126
0.633911
haozhangphd
81826b98faa4efe5e6045b8c40c4f324e4fd52da
5,907
cpp
C++
cdn/src/v20180606/model/DescribeScdnTopDataResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdn/src/v20180606/model/DescribeScdnTopDataResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdn/src/v20180606/model/DescribeScdnTopDataResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cdn/v20180606/model/DescribeScdnTopDataResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdn::V20180606::Model; using namespace std; DescribeScdnTopDataResponse::DescribeScdnTopDataResponse() : m_topTypeDataHasBeenSet(false), m_topIpDataHasBeenSet(false), m_modeHasBeenSet(false), m_topUrlDataHasBeenSet(false) { } CoreInternalOutcome DescribeScdnTopDataResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("TopTypeData") && !rsp["TopTypeData"].IsNull()) { if (!rsp["TopTypeData"].IsArray()) return CoreInternalOutcome(Error("response `TopTypeData` is not array type")); const rapidjson::Value &tmpValue = rsp["TopTypeData"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ScdnTypeData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_topTypeData.push_back(item); } m_topTypeDataHasBeenSet = true; } if (rsp.HasMember("TopIpData") && !rsp["TopIpData"].IsNull()) { if (!rsp["TopIpData"].IsArray()) return CoreInternalOutcome(Error("response `TopIpData` is not array type")); const rapidjson::Value &tmpValue = rsp["TopIpData"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ScdnTopData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_topIpData.push_back(item); } m_topIpDataHasBeenSet = true; } if (rsp.HasMember("Mode") && !rsp["Mode"].IsNull()) { if (!rsp["Mode"].IsString()) { return CoreInternalOutcome(Error("response `Mode` IsString=false incorrectly").SetRequestId(requestId)); } m_mode = string(rsp["Mode"].GetString()); m_modeHasBeenSet = true; } if (rsp.HasMember("TopUrlData") && !rsp["TopUrlData"].IsNull()) { if (!rsp["TopUrlData"].IsArray()) return CoreInternalOutcome(Error("response `TopUrlData` is not array type")); const rapidjson::Value &tmpValue = rsp["TopUrlData"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ScdnTopUrlData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_topUrlData.push_back(item); } m_topUrlDataHasBeenSet = true; } return CoreInternalOutcome(true); } vector<ScdnTypeData> DescribeScdnTopDataResponse::GetTopTypeData() const { return m_topTypeData; } bool DescribeScdnTopDataResponse::TopTypeDataHasBeenSet() const { return m_topTypeDataHasBeenSet; } vector<ScdnTopData> DescribeScdnTopDataResponse::GetTopIpData() const { return m_topIpData; } bool DescribeScdnTopDataResponse::TopIpDataHasBeenSet() const { return m_topIpDataHasBeenSet; } string DescribeScdnTopDataResponse::GetMode() const { return m_mode; } bool DescribeScdnTopDataResponse::ModeHasBeenSet() const { return m_modeHasBeenSet; } vector<ScdnTopUrlData> DescribeScdnTopDataResponse::GetTopUrlData() const { return m_topUrlData; } bool DescribeScdnTopDataResponse::TopUrlDataHasBeenSet() const { return m_topUrlDataHasBeenSet; }
32.103261
116
0.651261
sinjoywong
8189ad4d84cffe7cd66a7da5eea8304425b9c383
601
cpp
C++
src/parser/transform/statement/transform_delete.cpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
2
2020-01-07T17:19:02.000Z
2020-01-09T22:04:04.000Z
src/parser/transform/statement/transform_delete.cpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
src/parser/transform/statement/transform_delete.cpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
#include "duckdb/parser/statement/delete_statement.hpp" #include "duckdb/parser/transformer.hpp" using namespace duckdb; using namespace std; unique_ptr<DeleteStatement> Transformer::TransformDelete(postgres::Node *node) { auto stmt = reinterpret_cast<postgres::DeleteStmt *>(node); assert(stmt); auto result = make_unique<DeleteStatement>(); result->condition = TransformExpression(stmt->whereClause); result->table = TransformRangeVar(stmt->relation); if (result->table->type != TableReferenceType::BASE_TABLE) { throw Exception("Can only delete from base tables!"); } return result; }
31.631579
80
0.770383
RelationalAI-oss
818c43491286cc8f73f8a65a56f6a54f4c2c8b2d
13,386
cpp
C++
source/annotator/source/main/mainwindow.cpp
annotatorproject/annotator
637b7469051b7f5ab3c9994de458fd8a1cafdb70
[ "Apache-2.0" ]
null
null
null
source/annotator/source/main/mainwindow.cpp
annotatorproject/annotator
637b7469051b7f5ab3c9994de458fd8a1cafdb70
[ "Apache-2.0" ]
null
null
null
source/annotator/source/main/mainwindow.cpp
annotatorproject/annotator
637b7469051b7f5ab3c9994de458fd8a1cafdb70
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2017 Annotator Team #include "mainwindow.h" #include "ui_mainwindow.h" #include <string> #include <AnnotatorLib/Annotation.h> #include <AnnotatorLib/Commands/CleanSession.h> #include <AnnotatorLib/Commands/CompressSession.h> #include <QApplication> #include <QCheckBox> #include <QDebug> #include <QFileDialog> #include <QMessageBox> #include <QSettings> #include "aboutdialog.h" #include "controller/commandcontroller.h" #include "controller/selectioncontroller.h" #include "gui/alert.h" #include "gui/classesdialog.h" #include "gui/exportannotations.h" #include "gui/saveasdialog.h" #include "gui/statisticsdialog.h" #include "newprojectdialog.h" #include "optionsdialog.h" #include "plugins/pluginloader.h" #include "plugins/pluginrunner.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->PlayerLayout->addWidget(&playerWidget); ui->annotationsLayout->addWidget(&annotationsWidget); ui->objectsLayout->addWidget(&objectsWidget); ui->selectedObjectLayout->addWidget(&selectedObject); ui->attributesLayout->addWidget(&attributesWidget); // TODO ui->pluginsLayout->addWidget(&pluginsWidget); rateLabel = new QLabel; // Frame rate rateLabel->setText("fps"); // Add to Status bar // initial locking drawing area and plugins enableDrawing(false); // make some initialization ui->statusBar->addPermanentWidget(rateLabel); playerWidget.setRateLabel(rateLabel); loadRecentProjects(); connectSignalSlots(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::connectSignalSlots() { // session connect(CommandController::instance(), SIGNAL(signal_refreshSession()), &annotationsWidget, SLOT(on_refreshSession())); connect(CommandController::instance(), SIGNAL(signal_refreshSession()), &objectsWidget, SLOT(on_refreshSession())); // frames connect(SelectionController::instance(), SIGNAL(signal_frameSelection(long)), &playerWidget, SLOT(on_frameSelected(long))); // object selection connect(SelectionController::instance(), SIGNAL(signal_objectSelection(shared_ptr<AnnotatorLib::Object>)), &objectsWidget, SLOT(on_objectSelected(shared_ptr<AnnotatorLib::Object>))); connect(SelectionController::instance(), SIGNAL(signal_objectSelection(shared_ptr<AnnotatorLib::Object>)), &selectedObject, SLOT(on_objectSelected(shared_ptr<AnnotatorLib::Object>))); connect(SelectionController::instance(), SIGNAL(signal_objectSelection(shared_ptr<AnnotatorLib::Object>)), &annotationsWidget, SLOT(on_objectSelected(shared_ptr<AnnotatorLib::Object>))); connect(SelectionController::instance(), SIGNAL(signal_objectSelection(shared_ptr<AnnotatorLib::Object>)), &pluginsWidget, SLOT(on_objectSelected(shared_ptr<AnnotatorLib::Object>))); // upate annotations connect(CommandController::instance(), SIGNAL(signal_newAnnotation(shared_ptr<AnnotatorLib::Annotation>)), &annotationsWidget, SLOT(on_annotationAdded(shared_ptr<AnnotatorLib::Annotation>))); connect( CommandController::instance(), SIGNAL(signal_removedAnnotation(shared_ptr<AnnotatorLib::Annotation>)), &annotationsWidget, SLOT(on_annotationRemoved(shared_ptr<AnnotatorLib::Annotation>))); // update objects connect(CommandController::instance(), SIGNAL(signal_newObject(shared_ptr<AnnotatorLib::Object>)), &annotationsWidget, SLOT(on_objectAdded(shared_ptr<AnnotatorLib::Object>))); connect(CommandController::instance(), SIGNAL(signal_removedObject(shared_ptr<AnnotatorLib::Object>)), &annotationsWidget, SLOT(on_objectRemoved(shared_ptr<AnnotatorLib::Object>))); connect(CommandController::instance(), SIGNAL(signal_newObject(shared_ptr<AnnotatorLib::Object>)), &objectsWidget, SLOT(on_objectAdded(shared_ptr<AnnotatorLib::Object>))); connect(CommandController::instance(), SIGNAL(signal_removedObject(shared_ptr<AnnotatorLib::Object>)), &objectsWidget, SLOT(on_objectRemoved(shared_ptr<AnnotatorLib::Object>))); // update attributes connect(SelectionController::instance(), SIGNAL(signal_frameSelection(long)), &attributesWidget, SLOT(setFrame(long))); connect(&playerWidget, SIGNAL(signal_frameChanged(long)), &attributesWidget, SLOT(setFrame(long))); // autoAnnotate connect(&pluginsWidget, SIGNAL(signal_autoAnnotate(bool)), &playerWidget, SLOT(on_autoAnnotate(bool))); } void MainWindow::setRateValue(QString value) { rateLabel->setText(value); } void MainWindow::openProject(std::shared_ptr<AnnotatorLib::Project> project) { if (project) { this->project = project; this->session = project->getSession(); CommandController::instance()->setSession(session); playerWidget.setProject(project); annotationsWidget.setSession(this->session); objectsWidget.setSession(this->session); selectedObject.setProject(project); attributesWidget.setSession(this->session); this->setRateValue("FPS: " + QString::number(playerWidget.getRateValue())); setWindowTitle(project); CommandController::instance()->doEmitRefreshSession(); for (Annotator::Plugin *p : Annotator::PluginLoader::getInstance().getPlugins()) { p->setProject(project); } // save path to last opened project in settings addRecentProject(QString::fromStdString(project->getPath())); // lock/unlock project lock(!project->isActive()); } } void MainWindow::loadRecentProjects() { QSettings settings(QApplication::organizationName(), QApplication::applicationName()); foreach (QVariant v, settings.value("RecentProjects").toList()) { QFileInfo fileInfo(v.toString()); QAction *recentProjectAction = new QAction(fileInfo.baseName(), ui->menuRecentProjects); recentProjectAction->setToolTip(v.toString()); // load project when action is triggered connect(recentProjectAction, &QAction::triggered, this, [recentProjectAction, this]() { QString recentProject = recentProjectAction->toolTip(); this->openProject( AnnotatorLib::Project::loadPath(recentProject.toStdString())); }); ui->menuRecentProjects->addAction(recentProjectAction); } } void MainWindow::addRecentProject(QString projectfile) { QSettings settings(QApplication::organizationName(), QApplication::applicationName()); QVariantList recentProjects = settings.value("RecentProjects").toList(); if (recentProjects.contains(projectfile)) recentProjects.removeOne(projectfile); recentProjects.prepend(projectfile); settings.setValue("RecentProjects", recentProjects); settings.setValue("LastProjectPath", projectfile); } void MainWindow::on_actionClose_Project_triggered() { closeProject(); } void MainWindow::closeProject() { if (!this->project) { return; } // lock drawing area and plugins enableDrawing(false); annotationsWidget.setSession(nullptr); annotationsWidget.on_refreshSession(); objectsWidget.setSession(nullptr); objectsWidget.on_refreshSession(); selectedObject.setProject(nullptr); attributesWidget.setSession(nullptr); // ask if project should be saved QCheckBox *cb_lock = new QCheckBox("Yes, lock this project. Labeling is completed now."); cb_lock->setChecked(!project->isActive()); QMessageBox msgbox; msgbox.setParent(0); msgbox.setStyleSheet( "color: black;" "background-color: white;" "selection-color: black;" "selection-background-color: black;"); msgbox.setText(tr("Save project before close?\n")); msgbox.setIcon(QMessageBox::Icon::Question); msgbox.addButton(QMessageBox::No); msgbox.addButton(QMessageBox::Yes); msgbox.setDefaultButton(QMessageBox::Yes); QPalette p; p.setColor(QPalette::WindowText, QColor("Black")); p.setColor(QPalette::Window, QColor("White")); msgbox.setPalette(p); msgbox.setCheckBox(cb_lock); if (msgbox.exec() == QMessageBox::Yes) { this->project->setActive(cb_lock->checkState() != Qt::Checked); project->save(); } this->setWindowTitle(nullptr); this->project.reset(); playerWidget.closeProject(); } void MainWindow::closeEvent(QCloseEvent *event) { this->closeProject(); event->accept(); QWidget::closeEvent(event); } void MainWindow::on_actionQuit_triggered() { if (!playerWidget.videoplayer->isStop()) { playerWidget.videoplayer->pauseIt(); } this->close(); } void MainWindow::setWindowTitle( std::shared_ptr<AnnotatorLib::Project> project) { if (project == nullptr) { QMainWindow::setWindowTitle(QApplication::applicationName() + " - No project opened."); } else { QMainWindow::setWindowTitle(QApplication::applicationName() + " - " + QString::fromStdString(project->getName())); } } void MainWindow::on_actionOpen_Project_triggered() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Project"), ".", tr("Project Files (*.xml)")); if (QFile::exists(fileName)) { QApplication::setOverrideCursor(Qt::WaitCursor); Annotator::PluginLoader::getInstance(); try { std::shared_ptr<AnnotatorLib::Project> project = AnnotatorLib::Project::loadPath(fileName.toStdString()); openProject(project); QApplication::restoreOverrideCursor(); } catch (std::exception &e) { QApplication::restoreOverrideCursor(); QMessageBox::warning(this, "Failure while loading Project", QString(e.what())); } } CommandController::instance()->doEmitRefreshSession(); } void MainWindow::on_actionNew_Project_triggered() { NewProjectDialog dialog; dialog.exec(); if (dialog.getProject()) { this->project = dialog.getProject(); AnnotatorLib::Project::savePath(this->project, this->project->getPath()); openProject(this->project); } } void MainWindow::on_actionSave_Project_triggered() { if (this->project != nullptr) { project->save(); } } void MainWindow::on_actionUndo_triggered() { if (this->project != nullptr) { CommandController::instance()->undo(); } } void MainWindow::on_actionRedo_triggered() { if (this->project != nullptr) { CommandController::instance()->redo(); } } void MainWindow::on_actionClear_Session_triggered() { QMessageBox::StandardButton resBtn = QMessageBox::question( this, "", tr("This will delete everything! Are you sure?\n"), QMessageBox::Cancel | QMessageBox::Yes, QMessageBox::Yes); if (resBtn == QMessageBox::Yes) { shared_ptr<AnnotatorLib::Commands::CleanSession> cmd = std::make_shared<AnnotatorLib::Commands::CleanSession>(this->session); CommandController::instance()->execute(cmd); } } void MainWindow::on_actionCompress_Session_triggered() { // TODO: freeze window and show progress bar int nmb_annotations_before = session->getAnnotations().size(); shared_ptr<AnnotatorLib::Commands::CompressSession> cmd = std::make_shared<AnnotatorLib::Commands::CompressSession>(this->session); CommandController::instance()->execute(cmd); int nmb_annotations_after = session->getAnnotations().size(); Alert msgBox; msgBox.setText(QString::fromStdString( std::string("Compression algorithm has removed ") + std::to_string(nmb_annotations_before - nmb_annotations_after) + std::string(" annotations.\n"))); msgBox.setIcon(QMessageBox::Information); msgBox.setStandardButtons(0); msgBox.setAutoClose(true); msgBox.setTimeout(3); // Closes after three seconds msgBox.exec(); } void MainWindow::on_actionAbout_triggered() { AboutDialog aboutDialog; aboutDialog.exec(); } void MainWindow::on_actionClasses_triggered() { if (session != nullptr) { ClassesDialog dialog(session, this); dialog.exec(); } } void MainWindow::enableDrawing(bool enable) { this->pluginsWidget.setEnabled(enable); this->playerWidget.enableDrawing(enable); } void MainWindow::on_actionLock_project_toggled(bool b) { lock(b); } void MainWindow::lock(bool b) { this->project->setActive(!b); enableDrawing(!b); if (b) { Alert msgBox; msgBox.setToolTip("Warning"); msgBox.setText(QString::fromStdString( std::string("This project is locked. Unlock via the menu."))); msgBox.setIcon(QMessageBox::Warning); msgBox.setStandardButtons(0); msgBox.setAutoClose(true); msgBox.setTimeout(3); // Closes after three seconds msgBox.exec(); } } void MainWindow::on_actionProject_Statistics_triggered() { if (project) { StatisticsDialog dialog(project, this); dialog.exec(); } } void MainWindow::on_actionRun_Plugins_Dialog_triggered() { PluginRunner pluginRunner(project, this); pluginRunner.exec(); } void MainWindow::on_actionExport_Annotations_triggered() { ExportAnnotations dialog(project, this); dialog.exec(); } void MainWindow::on_action_Options_triggered() { OptionsDialog dialog; dialog.exec(); } void MainWindow::on_actionSave_Project_As_triggered() { SaveAsDialog dialog(project, this); dialog.exec(); }
33.215881
80
0.708726
annotatorproject
818dd04aa637d30278cf11ecd1982abbdadbc877
15,269
cpp
C++
source/flashplayer/brflashmanager.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/flashplayer/brflashmanager.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/flashplayer/brflashmanager.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Flash player manager Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brflashmanager.h" #include "brfloatingpoint.h" /*! ************************************ \typedef Burger::Flash::FSCommandProc \brief Functions and classes to support playing Adobe Flash files Adobe flash requires subsystems to support ActionScript, textures, fonts and vectors to be able to play Flash files. \sa Flash::Manager ***************************************/ /*! ************************************ \namespace Burger::Flash \brief Functions and classes to support playing Adobe Flash files Adobe flash requires subsystems to support ActionScript, textures, fonts and vectors to be able to play Flash files. \sa Flash::Manager ***************************************/ /*! ************************************ \class Burger::Flash::Manager \brief Manager to support the playing of Flash files Adobe flash requires subsystems to support ActionScript, textures, fonts and vectors to be able to play Flash files. This manager is the main dispatcher to load, manager and play Flash files. The application must supply a renderer (Usually OpenGL or DirectX) for the low level draw functions and this manager and player will do the rest. ***************************************/ /*! ************************************ \brief Initialize a Flash file manager Init to power up defaults \param pApp Pointer to the master application to the player can use low level systems ***************************************/ Burger::Flash::Manager::Manager(GameApp *pApp) : m_pGameApp(pApp), m_pFSCommmand(NULL), m_pCurrentObject(), m_fTextureLODBias(-1.2f), m_fCurvePixelError(1.0f), m_bUseRealtimeFrameRateFlag(FALSE), m_bVerboseActionFlag(FALSE), m_bVerboseParsingFlag(FALSE), m_bVerboseBitmapInfoFlag(FALSE), m_bAllowMultithreadingFlag(TRUE), m_Random(), m_BaseDirectory("9:"), m_CodeLibraryHash(), m_GlobalEnvironmentVariables(), m_ConstructorName("__constructor__"), m_CriticalSection() { } /*! ************************************ \brief Dispose of a Flash file manager Release everything that had been allocated and managed by the Adobe compatible Flash player. ***************************************/ /*! ************************************ \fn GameApp *Burger::Flash::Manager::GetGameApp(void) const \brief Get the main application \return Pointer to the application to render the scene ***************************************/ /*! ************************************ \fn FSCommandProc Burger::Flash::Manager::GetFSCallback(void) const \brief Get the Flash FSCommand handler \return Pointer to the FSCommand handler \sa SetFSCallback(FSCommandProc) ***************************************/ /*! ************************************ \fn GameApp *Burger::Flash::Manager::SetFSCallback(FSCommandProc pFSCommand) \brief Set the Flash FSCommand handler \param pFSCommand Pointer to the FSCommand handler \sa GetFSCallback(void) const ***************************************/ /*! ************************************ \fn RootObject *Burger::Flash::Manager::GetRootObject(void) const \brief Get the pointer to the movie file that has focus \return Pointer to the main flash movie object \sa SetRootObject(RootObject *) ***************************************/ /*! ************************************ \fn GameApp *Burger::Flash::Manager::SetRootObject(RootObject *pObject) \brief Set the pointer to the movie file that has focus \param pObject Pointer to the movie object to contain focus \sa GetRootObject(void) const ***************************************/ /*! ************************************ \fn Random * Burger::Flash::Manager::GetRandomGenerator(void) \brief Accessor to the random number generator \return A pointer to the random number generator used by the Flash system ***************************************/ /*! ************************************ \fn Filename * Burger::Flash::Manager::GetDataDirectory(void) \brief Get the data directory Retrieve the directory that the flash player is using to load data files that the flash file is requesting. \return A pointer to the filename record \sa SetDataDirectory(const char *) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetDataDirectory(const char *pDirectory) \brief Set the data directory Set the directory that the flash player will use to load data files that the flash file is requesting. The directory must be in Burgerlib format \param pDirectory A pointer to the "C" string with the directory name \sa GetDataDirectory(void) ***************************************/ /*! ************************************ \fn float Burger::Flash::Manager::GetLODBias(void) const \brief Get the texture Level of Detail bias \return The current Mip Map Z bias value. \sa SetLODBias(float) ***************************************/ /*! ************************************ \brief Set the texture Level of Detail bias For Flash files that use 3D graphics, this value is passed to the low level 3D system to set the Z bias for mip mapping. The default is -1.2f \param fTextureLODBias The new level of detail bias \sa GetLODBias(void) const ***************************************/ void BURGER_API Burger::Flash::Manager::SetLODBias(float fTextureLODBias) { m_fTextureLODBias = fTextureLODBias; } /*! ************************************ \fn float Burger::Flash::Manager::GetCurvePixelError(void) const \brief Get the curve detail level 1.0f is the default, higher numbers generate courser curves which speeds up rendering, and lower number generates finer curves which can slow down rendering. \return The current curve pixel resolution value. \sa SetCurvePixelError(float) ***************************************/ /*! ************************************ \brief Set the texture Level of Detail bias For Flash files that use vector graphics, this constant changes the resolution and refinement of the generation of curves. Larger numbers generate fewer vertices and smaller numbers generate more vertices. The default is 1.0f \param fCurvePixelError The new curve detail level. \sa GetCurvePixelError(void) const ***************************************/ void BURGER_API Burger::Flash::Manager::SetCurvePixelError(float fCurvePixelError) { m_fCurvePixelError = Clamp(fCurvePixelError,1e-6f,1e6f); } /*! ************************************ \fn uint_t Burger::Flash::Manager::GetRealtimeFrameRateFlag(void) \brief Get the real time frame rate flag. If non-zero, the player will call the update logic once or more times per frame to ensure that the logic is called as many times per second as the requested frame rate. On slow machines, frames may skip but the logic will work at the requested speed. \return Zero if \ref FALSE or non-zero for \ref TRUE \sa SetRealtimeFrameRateFlag(uint_t) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetRealtimeFrameRateFlag(uint_t bUseRealtimeFrameRateFlag) \brief Set the real time frame rate flag. If non-zero, the player will call the update logic once or more times per frame to ensure that the logic is called as many times per second as the requested frame rate. On slow machines, frames may skip but the logic will work at the requested speed. \param bUseRealtimeFrameRateFlag The new flag \sa GetRealtimeFrameRateFlag(void) const ***************************************/ /*! ************************************ \fn uint_t Burger::Flash::Manager::GetVerboseActionFlag(void) \brief Get the verbose action script debug flag If non-zero, the action script interpreter will output logging text to the console for debugging. \return Zero if \ref FALSE or non-zero for \ref TRUE \sa SetVerboseActionFlag(uint_t) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetVerboseActionFlag(uint_t bVerboseActionFlag) \brief Set the verbose action script debug flag If non-zero, the action script interpreter will output logging text to the console for debugging. This should not be set for shipping code, it's a performance hit. \param bVerboseActionFlag The new flag \sa GetVerboseActionFlag(void) const ***************************************/ /*! ************************************ \fn uint_t Burger::Flash::Manager::GetVerboseParsingFlag(void) \brief Get the verbose data parsing debug flag If non-zero, internal data parsing will output logging text to the console for debugging. \return Zero if \ref FALSE or non-zero for \ref TRUE \sa SetVerboseParsingFlag(uint_t) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetVerboseParsingFlag(uint_t m_bVerboseParsingFlag) \brief Set the verbose action script debug flag If non-zero, internal data parsing will output logging text to the console for debugging. This should not be set for shipping code, it's a performance hit. \param m_bVerboseParsingFlag The new flag \sa GetVerboseParsingFlag(void) const ***************************************/ /*! ************************************ \fn uint_t Burger::Flash::Manager::GetVerboseBitmapInfoFlag(void) \brief Get the bitmap generation debug flag If non-zero, bitmap generation will output logging text to the console for debugging. \return Zero if \ref FALSE or non-zero for \ref TRUE \sa SetVerboseBitmapInfoFlag(uint_t) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetVerboseBitmapInfoFlag(uint_t bVerboseBitmapInfoFlag) \brief Set the bitmap generation debug flag If non-zero, bitmap generation parsing will output logging text to the console for debugging. This should not be set for shipping code, it's a performance hit. \param bVerboseBitmapInfoFlag The new flag \sa GetVerboseBitmapInfoFlag(void) const ***************************************/ /*! ************************************ \fn uint_t Burger::Flash::Manager::GetAllowMultithreadingFlag(void) \brief Get the multithreading flag If non-zero, the player will use multiple threads for background processing \return Zero if \ref FALSE or non-zero for \ref TRUE \sa SetAllowMultithreadingFlag(uint_t) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::SetAllowMultithreadingFlag(uint_t bAllowMultithreadingFlag) \brief Set the multithreading flag If non-zero, the player will use multiple CPU threads to spread out the processing of the Flash movie. \param bAllowMultithreadingFlag The new flag \sa GetAllowMultithreadingFlag(void) const ***************************************/ /*! ************************************ \brief Release all of the loaded code libraries If any code libraries were loaded during the execution of the Flash movie, this function will release all of them \sa LoadCodeLibrary(const String *) ***************************************/ void Burger::Flash::Manager::ReleaseCodeLibraries(void) { // Get the iterators for the hash HashMapString<CodeLibrary*>::iterator it = m_CodeLibraryHash.begin(); HashMapString<CodeLibrary*>::iterator end = m_CodeLibraryHash.end(); if (it!=end) { // Any valid entries in the hash will be disposed of do { Delete(it->second); ++it; } while (it!=end); } // Dispose of the hash and its contents m_CodeLibraryHash.Clear(); } /*! ************************************ \brief Load a code library If a code library is in the cache, return the reference otherwise, load the library from the file system and if successful, add it to the cache. \param pName Pointer to a String with the filename of the code library \return \ref NULL if the library couldn't be loaded or a valid CodeLibrary to pull functions from. \sa ReleaseCodeLibraries(void) ***************************************/ Burger::CodeLibrary *Burger::Flash::Manager::LoadCodeLibrary(const String *pName) { CodeLibrary *pResult = NULL; // Using the key, see if it's in the hash if (!m_CodeLibraryHash.GetData(pName[0],&pResult)) { // Not found, create a library object pResult = New<CodeLibrary>(); if (pResult) { if (pResult->Init(pName->GetPtr())) { Delete(pResult); pResult = NULL; } else { m_CodeLibraryHash.add(pName[0],pResult); } } } return pResult; } /*! ************************************ \fn const String *Burger::Flash::Manager::GetGlobalEnvironmentVariables(void) const \brief Get the global environment variables Retrieves the pointer to the internal copy of the global environment variables. \return Pointer to a String with list of environment variables \sa SetGlobalEnvironmentVariables(const char *) ***************************************/ /*! ************************************ \brief Set the global environment variables Action script can access "global" variables that the interpreter generates to pass information from the host system to the movie. This function sets those variables so information can be passed to the movie before it's started up. The string is in the format of a variable name, followed by an '=' (Equals) character, and then the variable itself. Multiple variables are separated by commas. Example: VARIABLENAME=DATA,NEXTVARIABLE=DATA \note This function makes an internal copy of the string. If changes are desired, call this function again with the updated data. \param pInput Pointer to a "C" string with list of environment variables \sa GetGlobalEnvironmentVariables(void) const ***************************************/ void Burger::Flash::Manager::SetGlobalEnvironmentVariables(const char *pInput) { m_GlobalEnvironmentVariables = pInput; } /*! ************************************ \fn const String *Burger::Flash::Manager::GetConstructorName(void) const \brief Get the string constant "__constructor__" This constant is used by ActionScript for invoking data constructors \return Pointer to a String "__constructor__" ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::Lock(void) \brief Lock the global CriticalSection The Flash player may spawn multiple threads, this CriticalSection is used to keep the threads in sync by locking. \sa Unlock(void) ***************************************/ /*! ************************************ \fn void Burger::Flash::Manager::Unlock(void) \brief Lock the global CriticalSection The Flash player may spawn multiple threads, this CriticalSection is used to keep the threads in sync by unlocking. \sa Lock(void) ***************************************/
28.918561
99
0.62676
Olde-Skuul
818ec90634660c0f090307c219f591f551b378cf
381
cpp
C++
xlloption/fms_sequence_constant.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
xlloption/fms_sequence_constant.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
xlloption/fms_sequence_constant.t.cpp
GR6250-2019/hw6
13a78ed4474c5e37b82a3ded10eef95b706e382b
[ "MIT" ]
null
null
null
// fms_sequence_constant.t.cpp - Test constant sequences. #include <cassert> #include "fms_sequence_constant.h" using namespace fms::sequence; int test_sequence_constant() { constant c(42); assert(c); assert(*c == 42); assert(++c && *c == 42); assert(++c && *c == 42); return 0; } int test_sequence_constant_ = test_sequence_constant();
21.166667
58
0.632546
GR6250-2019
818f3e012c9ae59bb19734c573c19f48e1f5eaf9
4,067
cpp
C++
libs/besiq/method/peer_method.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
1
2015-10-21T14:22:12.000Z
2015-10-21T14:22:12.000Z
libs/besiq/method/peer_method.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2019-05-26T20:52:31.000Z
2019-05-28T16:19:49.000Z
libs/besiq/method/peer_method.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2016-11-06T14:58:37.000Z
2019-05-26T14:03:13.000Z
#include <dcdflib/libdcdf.hpp> #include <besiq/method/peer_method.hpp> #include <besiq/stats/snp_count.hpp> peer_method::peer_method(method_data_ptr data) : method_type::method_type( data ) { m_weight = arma::ones<arma::vec>( data->phenotype.size( ) ); } std::vector<std::string> peer_method::init() { std::vector<std::string> header; header.push_back( "Z_dd_ld" ); header.push_back( "P_dd_con" ); header.push_back( "Z_rd_ld" ); header.push_back( "P_rd_con" ); header.push_back( "Z_dr_ld" ); header.push_back( "P_dr_con" ); header.push_back( "Z_rr_ld" ); header.push_back( "P_rr_con" ); return header; } /** * rr | rd * dr | dd * * 00 | 00/01 | 01 * 10/00 | 00/11 | 01/11 * 10 | 10/11 | 11 * * @param counts The counts for each genotype. * @param snp1_onestart The minimum number of minor alleles that should be considered a 1, * at locus 1. * @param snp2_onestart The minimum number of minor alleles that should be considered a 1. * at locus 2. */ arma::mat peer_method::encode_counts(const arma::mat &counts, size_t snp1_onestart, size_t snp2_onestart) { int dd = ( snp1_onestart == 1 ) && ( snp2_onestart == 1 ); int rd = ( snp1_onestart == 1 ) && ( snp2_onestart == 2 ); int dr = ( snp1_onestart == 2 ) && ( snp2_onestart == 1 ); int rr = ( snp1_onestart == 2 ) && ( snp2_onestart == 2 ); arma::mat encoded_counts( 4, 2 ); for(int i = 0; i <= 1; i++) { encoded_counts( 0, i ) = counts( 0, i ) + (rd + rr) * counts( 1, i ) + (dr + rr) * counts( 3, i ) + rr * counts( 4, i ); encoded_counts( 1, i ) = (dr + dd) * counts( 1, i ) + counts( 2, i ) + dr * counts( 4, i ) + (dr + rr) * counts( 5, i ); encoded_counts( 2, i ) = (rd + dd) * counts( 3, i ) + rd * counts( 4, i ) + counts( 6, i ) + (rd + rr) * counts( 7, i ); encoded_counts( 3, i ) = dd * counts( 4, i ) + (rd + dd) * counts( 5, i ) + (dr + dd) * counts( 7, i ) + counts( 8, i ); } return encoded_counts; } void peer_method::compute_ld_p(const arma::mat &counts, float *ld_case_z, float *ld_contrast_z) { double N_controls = sum( counts.col( 0 ) ); double N_cases = sum( counts.col( 1 ) ); double p_a_case = ( counts( 1, 1 ) + counts( 3, 1 ) ) / N_cases; double p_a_control = ( counts( 1, 0 ) + counts( 3, 0 ) ) / N_controls; double p_b_case = ( counts( 2, 1 ) + counts( 3, 1 ) ) / N_cases; double p_b_control = ( counts( 2, 0 ) + counts( 3, 0 ) ) / N_controls; double p_ab_case = counts( 3, 1 ) / N_cases; double p_ab_control = counts( 3, 0 ) / N_controls; double delta_case = ( p_ab_case - p_a_case * p_b_case ); double delta_control = ( p_ab_control - p_a_control * p_b_control ); double sigma2_case = ( p_a_case * (1 - p_a_case) * p_b_case * (1 - p_b_case ) ) / N_cases; double sigma2_control = ( p_a_control * (1 - p_a_control) * p_b_control * (1 - p_b_control ) ) / N_controls; double sigma_diff = sqrt( sigma2_case + sigma2_control ); *ld_case_z = delta_case / sqrt( sigma2_case ); *ld_contrast_z = ( delta_case - delta_control ) / sigma_diff; } double peer_method::run(const snp_row &row1, const snp_row &row2, float *output) { arma::mat counts = joint_count( row1, row2, get_data( )->phenotype, m_weight ); if( arma::min( arma::min( counts ) ) < METHOD_SMALLEST_CELL_SIZE_BINOMIAL ) { return -9; } set_num_ok_samples( (size_t) arma::accu( counts ) ); size_t output_index = 0; for(int i = 1; i <= 2; i++) { for(int j = 1; j <= 2; j++) { arma::mat encoded_counts = encode_counts( counts, i, j ); float ld_case_z; float ld_contrast_z; compute_ld_p( encoded_counts, &ld_case_z, &ld_contrast_z ); output[ output_index++ ] = ld_case_z; output[ output_index++ ] = 1 - norm_cdf( ld_contrast_z, 0.0, 1.0 ); } } return min_na( min_na( output[ 1 ], output[ 3 ] ), min_na( output[ 5 ], output[ 7 ] ) ); }
35.365217
128
0.588886
hoehleatsu
81913ee91dd7b1b46d1e7227740ec4e5c2bf7d91
2,606
cpp
C++
Employee-database-test-v1/Employee-database-test-v1.cpp
TheJoyfulProgrammer/My-CPP-Demos
1c19cb2bdf041e788c141a7816f37c264e106411
[ "MIT" ]
null
null
null
Employee-database-test-v1/Employee-database-test-v1.cpp
TheJoyfulProgrammer/My-CPP-Demos
1c19cb2bdf041e788c141a7816f37c264e106411
[ "MIT" ]
null
null
null
Employee-database-test-v1/Employee-database-test-v1.cpp
TheJoyfulProgrammer/My-CPP-Demos
1c19cb2bdf041e788c141a7816f37c264e106411
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <fstream> int main () { std::fstream DatabaseFile; std::string EmployeeID, EmployeeName, EmployeeAddress, EmployeePhone, EmployeeDepartment; std::string EmployeePosition, EmployeeHiredDate, EmployeeRatePerDay, EmployeeRatePerHour, EmployeeOvertimeRate; const int ColumnPaddingSize = 17; DatabaseFile.open ("EmployeeDatabase.txt", std::fstream::in); if (!DatabaseFile.is_open()) { std::cout << "Could not open the employee database\n"; system("pause"); return 0; } getline(DatabaseFile, EmployeeID, '|'); getline(DatabaseFile, EmployeeName, '|'); getline(DatabaseFile, EmployeeAddress, '|'); getline(DatabaseFile, EmployeePhone, '|'); getline(DatabaseFile, EmployeeDepartment, '|'); getline(DatabaseFile, EmployeePosition, '|'); getline(DatabaseFile, EmployeeHiredDate, '|'); getline(DatabaseFile, EmployeeRatePerDay, '|'); getline(DatabaseFile, EmployeeRatePerHour, '|'); getline(DatabaseFile, EmployeeOvertimeRate, '|'); std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Employee ID: "; std::cout << EmployeeID << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Name: "; std::cout << EmployeeName << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Address: "; std::cout << EmployeeAddress << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Contact Number: "; std::cout << EmployeePhone << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Department: "; std::cout << EmployeeDepartment << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Position: "; std::cout << EmployeePosition << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Date Started: "; std::cout << EmployeeHiredDate << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Rate Per Day: "; std::cout << EmployeeRatePerDay << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Rate Per Hour: "; std::cout << EmployeeRatePerHour << "\n"; std::cout << std::setw(ColumnPaddingSize) << std::setfill (' ') << std::left << "Overtime Rate: "; std::cout << EmployeeOvertimeRate << "\n"; DatabaseFile.close(); }
40.092308
116
0.605909
TheJoyfulProgrammer
81928e3f6e8c1667a72587f1209edac785ec4709
5,902
cpp
C++
OpenTESArena/src/Interface/Panel.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
OpenTESArena/src/Interface/Panel.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
OpenTESArena/src/Interface/Panel.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
#include <vector> #include "SDL.h" #include "CinematicPanel.h" #include "CursorAlignment.h" #include "ImageSequencePanel.h" #include "ImagePanel.h" #include "MainMenuPanel.h" #include "Panel.h" #include "RichTextString.h" #include "TextAlignment.h" #include "TextBox.h" #include "../Game/Game.h" #include "../Game/Options.h" #include "../Math/Rect.h" #include "../Math/Vector2.h" #include "../Media/Color.h" #include "../Media/FontManager.h" #include "../Media/MusicName.h" #include "../Media/PaletteFile.h" #include "../Media/PaletteName.h" #include "../Media/TextureFile.h" #include "../Media/TextureName.h" #include "../Media/TextureSequenceName.h" #include "../Rendering/Renderer.h" #include "../Rendering/Surface.h" #include "components/vfs/manager.hpp" Panel::CursorData::CursorData(const Texture *texture, CursorAlignment alignment) { this->texture = texture; this->alignment = alignment; } const Texture *Panel::CursorData::getTexture() const { return this->texture; } CursorAlignment Panel::CursorData::getAlignment() const { return this->alignment; } Panel::Panel(Game &game) : game(game) { } Texture Panel::createTooltip(const std::string &text, FontName fontName, FontManager &fontManager, Renderer &renderer) { const Color textColor(255, 255, 255, 255); const Color backColor(32, 32, 32, 192); const int x = 0; const int y = 0; const RichTextString richText( text, fontName, textColor, TextAlignment::Left, fontManager); // Create text. const TextBox textBox(x, y, richText, renderer); const Surface &textSurface = textBox.getSurface(); // Create background. Make it a little bigger than the text box. const int padding = 4; Surface background = Surface::createWithFormat( textSurface.getWidth() + padding, textSurface.getHeight() + padding, Renderer::DEFAULT_BPP, Renderer::DEFAULT_PIXELFORMAT); background.fill(backColor.r, backColor.g, backColor.b, backColor.a); // Offset the text from the top left corner by a bit so it isn't against the side // of the tooltip (for aesthetic purposes). SDL_Rect rect; rect.x = padding / 2; rect.y = padding / 2; rect.w = textSurface.getWidth(); rect.h = textSurface.getHeight(); // Draw the text onto the background. SDL_BlitSurface(textSurface.get(), nullptr, background.get(), &rect); // Create a hardware texture for the tooltip. Texture tooltip = renderer.createTextureFromSurface(background); return tooltip; } std::unique_ptr<Panel> Panel::defaultPanel(Game &game) { // If not showing the intro, then jump to the main menu. if (!game.getOptions().getMisc_ShowIntro()) { return std::make_unique<MainMenuPanel>(game); } // All of these lambdas are linked together like a stack by each panel's last // argument. auto changeToMainMenu = [](Game &game) { game.setPanel<MainMenuPanel>(game); }; auto changeToIntroStory = [changeToMainMenu](Game &game) { std::vector<std::string> paletteNames { "SCROLL03.IMG", "SCROLL03.IMG", "SCROLL03.IMG" }; std::vector<std::string> textureNames { "SCROLL01.IMG", "SCROLL02.IMG", "SCROLL03.IMG" }; // In the original game, the last frame ("...hope flies on death's wings...") // seems to be a bit shorter. std::vector<double> imageDurations { 13.0, 13.0, 10.0 }; game.setPanel<ImageSequencePanel>(game, paletteNames, textureNames, imageDurations, changeToMainMenu); }; auto changeToScrolling = [changeToIntroStory](Game &game) { game.setPanel<CinematicPanel>( game, PaletteFile::fromName(PaletteName::Default), TextureFile::fromName(TextureSequenceName::OpeningScroll), 0.042, changeToIntroStory); }; auto changeToQuote = [changeToScrolling](Game &game) { const double secondsToDisplay = 5.0; game.setPanel<ImagePanel>( game, PaletteFile::fromName(PaletteName::BuiltIn), TextureFile::fromName(TextureName::IntroQuote), secondsToDisplay, changeToScrolling); }; auto makeIntroTitlePanel = [changeToQuote, &game]() { const double secondsToDisplay = 5.0; return std::make_unique<ImagePanel>( game, PaletteFile::fromName(PaletteName::BuiltIn), TextureFile::fromName(TextureName::IntroTitle), secondsToDisplay, changeToQuote); }; // Decide how the game starts up. If only the floppy disk data is available, // then go to the splash screen. Otherwise, load the intro book video. const auto &exeData = game.getMiscAssets().getExeData(); const bool isFloppyVersion = exeData.isFloppyVersion(); if (!isFloppyVersion) { auto changeToTitle = [makeIntroTitlePanel](Game &game) { game.setPanel(makeIntroTitlePanel()); }; auto makeIntroBookPanel = [changeToTitle, &game]() { return std::make_unique<CinematicPanel>( game, PaletteFile::fromName(PaletteName::Default), TextureFile::fromName(TextureSequenceName::IntroBook), 1.0 / 7.0, changeToTitle); }; return makeIntroBookPanel(); } else { return makeIntroTitlePanel(); } } Panel::CursorData Panel::getCurrentCursor() const { // Null by default. return CursorData(nullptr, CursorAlignment::TopLeft); } void Panel::handleEvent(const SDL_Event &e) { // Do nothing by default. static_cast<void>(e); } void Panel::onPauseChanged(bool paused) { // Do nothing by default. static_cast<void>(paused); } void Panel::resize(int windowWidth, int windowHeight) { // Do nothing by default. static_cast<void>(windowWidth); static_cast<void>(windowHeight); } Game &Panel::getGame() const { return this->game; } void Panel::tick(double dt) { // Do nothing by default. static_cast<void>(dt); } void Panel::renderSecondary(Renderer &renderer) { // Do nothing by default. static_cast<void>(renderer); }
25.222222
84
0.689258
Digital-Monk
8193a7552545c3c7fef8863bf87bb19cd2ff5007
154
cpp
C++
public/similarity_plugin/input/10/12/10 12 5112100047--Fungsi Hello World!.cpp
laurensiusadi/elearning-pweb
c72ae1fc414895919ef71ae370686353d9086bce
[ "MIT" ]
null
null
null
public/similarity_plugin/input/10/12/10 12 5112100047--Fungsi Hello World!.cpp
laurensiusadi/elearning-pweb
c72ae1fc414895919ef71ae370686353d9086bce
[ "MIT" ]
null
null
null
public/similarity_plugin/input/10/12/10 12 5112100047--Fungsi Hello World!.cpp
laurensiusadi/elearning-pweb
c72ae1fc414895919ef71ae370686353d9086bce
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; void Print() { cout << "Hello World!" << endl; } int main() { int aaaa = 2; print(); return 0; }
12.833333
35
0.558442
laurensiusadi
8198d1fef53f71d33f40f519f595842d8db97b5b
3,018
cpp
C++
QmlVlcConfig.cpp
mdkcore0/QmlVlc
67c764d72dd6c45f47322b0da4e10fa94c60aabe
[ "BSD-2-Clause" ]
null
null
null
QmlVlcConfig.cpp
mdkcore0/QmlVlc
67c764d72dd6c45f47322b0da4e10fa94c60aabe
[ "BSD-2-Clause" ]
null
null
null
QmlVlcConfig.cpp
mdkcore0/QmlVlc
67c764d72dd6c45f47322b0da4e10fa94c60aabe
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2014, Sergey Radionov <rsatom_gmail.com> * 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. *******************************************************************************/ #include "QmlVlcConfig.h" #include <QVector> int QmlVlcConfig::_networkCacheTime = -1; bool QmlVlcConfig::_adjustFilter = false; bool QmlVlcConfig::_marqueeFilter = false; bool QmlVlcConfig::_logoFilter = false; bool QmlVlcConfig::_debug = false; bool QmlVlcConfig::_noVideoTitleShow = true; bool QmlVlcConfig::_hardwareAcceleration = false; bool QmlVlcConfig::_trustedEnvironment = false; libvlc_instance_t* QmlVlcConfig::createLibvlcInstance() { QVector<const char*> opts; QByteArray networkCachingBuf; if( _networkCacheTime >= 0 ) { opts.push_back( "--network-caching" ); networkCachingBuf = QString::number( _networkCacheTime ).toLatin1(); opts.push_back( networkCachingBuf.constData() ); } if( _adjustFilter ) opts.push_back( "--video-filter=adjust" ); QString subFilters; if( _marqueeFilter ) subFilters = QStringLiteral( "marq" ); if( _logoFilter ) { if( !subFilters.isEmpty() ) subFilters += ':'; subFilters += QStringLiteral( "logo" ); } QByteArray subFiltersBuf; if( !subFilters.isEmpty() ) { subFilters = QStringLiteral( "--sub-filter=" ) + subFilters; subFiltersBuf = subFilters.toLatin1(); opts.push_back( subFiltersBuf.constData() ); } if( _debug ) opts.push_back( "-vvv" ); if( _noVideoTitleShow ) opts.push_back( "--no-video-title-show" ); return libvlc_new( opts.size(), opts.data() ); }
38.692308
80
0.680583
mdkcore0
819bf7d4469ce00e40d22618123389fa3b931b08
6,382
cpp
C++
test/console_tests.cpp
bponsler/ros2_console
2ad033046a1d72c509f20d6478fa86ecf21fc6be
[ "Apache-2.0" ]
null
null
null
test/console_tests.cpp
bponsler/ros2_console
2ad033046a1d72c509f20d6478fa86ecf21fc6be
[ "Apache-2.0" ]
null
null
null
test/console_tests.cpp
bponsler/ros2_console
2ad033046a1d72c509f20d6478fa86ecf21fc6be
[ "Apache-2.0" ]
2
2017-07-31T05:25:47.000Z
2017-12-07T22:14:49.000Z
// project headers #include <ros2_console/console.hpp> // gtest includes #include <gtest/gtest.h> TEST(TimeTestSuite, testRegularNoArgs) { ROS_DEBUG("Empty format"); ROS_INFO("Empty format"); ROS_WARN("Empty format"); ROS_ERROR("Empty format"); ROS_FATAL("Empty format"); } TEST(TimeTestSuite, testRegular) { ROS_DEBUG("Hey: %s %d", "there", 100); ROS_INFO("Hey: %s %d", "there", 100); ROS_WARN("Hey: %s %d", "there", 100); ROS_ERROR("Hey: %s %d", "there", 100); ROS_FATAL("Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularNamed) { ROS_DEBUG_NAMED("test_name", "Hey: %s %d", "there", 100); ROS_INFO_NAMED("my_name", "Hey: %s %d", "there", 100); ROS_WARN_NAMED("their_name", "Hey: %s %d", "there", 100); ROS_ERROR_NAMED("your_name", "Hey: %s %d", "there", 100); ROS_FATAL_NAMED("ThisIsMyName", "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularCond) { ROS_DEBUG_COND(true, "Hey: %s %d", "there", 100); ROS_INFO_COND(false, "Hey: %s %d", "there", 100); ROS_WARN_COND(1, "Hey: %s %d", "there", 100); ROS_ERROR_COND(0, "Hey: %s %d", "there", 100); ROS_FATAL_COND(123, "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularCondNamed) { ROS_DEBUG_COND_NAMED(true, "a_name", "Hey: %s %d", "there", 100); ROS_INFO_COND_NAMED(false, "b_name", "Hey: %s %d", "there", 100); ROS_WARN_COND_NAMED(1, "name_c", "Hey: %s %d", "there", 100); ROS_ERROR_COND_NAMED(0, "name_d", "Hey: %s %d", "there", 100); ROS_FATAL_COND_NAMED(123, "name_e", "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularThrottle) { ROS_DEBUG_THROTTLE(3, "Hey: %s %d", "there", 100); ROS_INFO_THROTTLE(2, "Hey: %s %d", "there", 100); ROS_WARN_THROTTLE(5, "Hey: %s %d", "there", 100); ROS_ERROR_THROTTLE(10, "Hey: %s %d", "there", 100); ROS_FATAL_THROTTLE(5, "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularDelayedThrottle) { ROS_DEBUG_DELAYED_THROTTLE(3, "Hey: %s %d", "there", 100); ROS_INFO_DELAYED_THROTTLE(2, "Hey: %s %d", "there", 100); ROS_WARN_DELAYED_THROTTLE(5, "Hey: %s %d", "there", 100); ROS_ERROR_DELAYED_THROTTLE(10, "Hey: %s %d", "there", 100); ROS_FATAL_DELAYED_THROTTLE(5, "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularThrottleNamed) { ROS_DEBUG_THROTTLE_NAMED(3, "name", "Hey: %s %d", "there", 100); ROS_INFO_THROTTLE_NAMED(2, "name", "Hey: %s %d", "there", 100); ROS_WARN_THROTTLE_NAMED(5, "name", "Hey: %s %d", "there", 100); ROS_ERROR_THROTTLE_NAMED(10, "name", "Hey: %s %d", "there", 100); ROS_FATAL_THROTTLE_NAMED(5, "name", "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testRegularDelayedThrottleNamed) { ROS_DEBUG_DELAYED_THROTTLE_NAMED(3, "name", "Hey: %s %d", "there", 100); ROS_INFO_DELAYED_THROTTLE_NAMED(2, "name", "Hey: %s %d", "there", 100); ROS_WARN_DELAYED_THROTTLE_NAMED(5, "name", "Hey: %s %d", "there", 100); ROS_ERROR_DELAYED_THROTTLE_NAMED(10, "name", "Hey: %s %d", "there", 100); ROS_FATAL_DELAYED_THROTTLE_NAMED(5, "name", "Hey: %s %d", "there", 100); } TEST(TimeTestSuite, testStream) { ROS_DEBUG_STREAM("Hey: " << "there" << " " << 100); ROS_INFO_STREAM("Hey: " << "there" << " " << 100); ROS_WARN_STREAM("Hey: " << "there" << " " << 100); ROS_ERROR_STREAM("Hey: " << "there" << " " << 100); ROS_FATAL_STREAM("Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamNamed) { ROS_DEBUG_STREAM_NAMED("name1", "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_NAMED("name2", "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_NAMED("name3", "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_NAMED("name4", "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_NAMED("name5", "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamCond) { ROS_DEBUG_STREAM_COND(0, "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_COND(1, "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_COND(true, "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_COND(false, "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_COND(123, "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamCondNamed) { ROS_DEBUG_STREAM_COND_NAMED(0, "name5", "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_COND_NAMED(1, "name4", "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_COND_NAMED(true, "name3", "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_COND_NAMED(false, "name2", "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_COND_NAMED(123, "name1", "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamThrottle) { ROS_DEBUG_STREAM_THROTTLE(9, "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_THROTTLE(0, "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_THROTTLE(4, "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_THROTTLE(3, "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_THROTTLE(123, "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamDelayedThrottle) { ROS_DEBUG_STREAM_DELAYED_THROTTLE(9, "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_DELAYED_THROTTLE(0, "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_DELAYED_THROTTLE(4, "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_DELAYED_THROTTLE(3, "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_DELAYED_THROTTLE(123, "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamThrottleNamed) { ROS_DEBUG_STREAM_THROTTLE_NAMED(9, "name", "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_THROTTLE_NAMED(0, "name", "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_THROTTLE_NAMED(4, "name", "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_THROTTLE_NAMED(3, "name", "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_THROTTLE_NAMED(123, "name", "Hey: " << "there" << " " << 100); } TEST(TimeTestSuite, testStreamDelayedThrottleNamed) { ROS_DEBUG_STREAM_DELAYED_THROTTLE_NAMED(9, "name", "Hey: " << "there" << " " << 100); ROS_INFO_STREAM_DELAYED_THROTTLE_NAMED(0, "name", "Hey: " << "there" << " " << 100); ROS_WARN_STREAM_DELAYED_THROTTLE_NAMED(4, "name", "Hey: " << "there" << " " << 100); ROS_ERROR_STREAM_DELAYED_THROTTLE_NAMED(3, "name", "Hey: " << "there" << " " << 100); ROS_FATAL_STREAM_DELAYED_THROTTLE_NAMED(123, "name", "Hey: " << "there" << " " << 100); } // Run all tests int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
38.215569
89
0.623316
bponsler
819d02aa678c629cbf59da927a1341b0fb71b6d3
2,570
cpp
C++
Code/Editor/EditorFramework/Manipulators/Implementation/SphereManipulatorAdapter.cpp
jakrams/ezEngine
2308f9d708f829b1716f54d3f79bbd262bb86132
[ "MIT" ]
null
null
null
Code/Editor/EditorFramework/Manipulators/Implementation/SphereManipulatorAdapter.cpp
jakrams/ezEngine
2308f9d708f829b1716f54d3f79bbd262bb86132
[ "MIT" ]
null
null
null
Code/Editor/EditorFramework/Manipulators/Implementation/SphereManipulatorAdapter.cpp
jakrams/ezEngine
2308f9d708f829b1716f54d3f79bbd262bb86132
[ "MIT" ]
null
null
null
#include <EditorFramework/EditorFrameworkPCH.h> #include <EditorFramework/DocumentWindow/EngineDocumentWindow.moc.h> #include <EditorFramework/Manipulators/SphereManipulatorAdapter.h> #include <ToolsFoundation/Object/ObjectAccessorBase.h> ezSphereManipulatorAdapter::ezSphereManipulatorAdapter() {} ezSphereManipulatorAdapter::~ezSphereManipulatorAdapter() {} void ezSphereManipulatorAdapter::Finalize() { auto* pDoc = m_pObject->GetDocumentObjectManager()->GetDocument(); auto* pWindow = ezQtDocumentWindow::FindWindowByDocument(pDoc); ezQtEngineDocumentWindow* pEngineWindow = qobject_cast<ezQtEngineDocumentWindow*>(pWindow); EZ_ASSERT_DEV(pEngineWindow != nullptr, "Manipulators are only supported in engine document windows"); m_Gizmo.SetTransformation(GetObjectTransform()); m_Gizmo.SetVisible(m_bManipulatorIsVisible); m_Gizmo.SetOwner(pEngineWindow, nullptr); m_Gizmo.m_GizmoEvents.AddEventHandler(ezMakeDelegate(&ezSphereManipulatorAdapter::GizmoEventHandler, this)); } void ezSphereManipulatorAdapter::Update() { m_Gizmo.SetVisible(m_bManipulatorIsVisible); ezObjectAccessorBase* pObjectAccessor = GetObjectAccessor(); const ezSphereManipulatorAttribute* pAttr = static_cast<const ezSphereManipulatorAttribute*>(m_pManipulatorAttr); if (!pAttr->GetInnerRadiusProperty().IsEmpty()) { float fValue = pObjectAccessor->Get<float>(m_pObject, GetProperty(pAttr->GetInnerRadiusProperty())); m_Gizmo.SetInnerSphere(true, fValue); } if (!pAttr->GetOuterRadiusProperty().IsEmpty()) { float fValue = pObjectAccessor->Get<float>(m_pObject, GetProperty(pAttr->GetOuterRadiusProperty())); m_Gizmo.SetOuterSphere(fValue); } m_Gizmo.SetTransformation(GetObjectTransform()); } void ezSphereManipulatorAdapter::GizmoEventHandler(const ezGizmoEvent& e) { switch (e.m_Type) { case ezGizmoEvent::Type::BeginInteractions: BeginTemporaryInteraction(); break; case ezGizmoEvent::Type::CancelInteractions: CancelTemporayInteraction(); break; case ezGizmoEvent::Type::EndInteractions: EndTemporaryInteraction(); break; case ezGizmoEvent::Type::Interaction: { const ezSphereManipulatorAttribute* pAttr = static_cast<const ezSphereManipulatorAttribute*>(m_pManipulatorAttr); ChangeProperties(pAttr->GetInnerRadiusProperty(), m_Gizmo.GetInnerRadius(), pAttr->GetOuterRadiusProperty(), m_Gizmo.GetOuterRadius()); } break; } } void ezSphereManipulatorAdapter::UpdateGizmoTransform() { m_Gizmo.SetTransformation(GetObjectTransform()); }
32.531646
141
0.781712
jakrams
819faf953b8b078fed9e3da98544ec8204ce7850
9,608
cpp
C++
third party/openRTMFP-Cumulus/CumulusLib/sources/Flow.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
5
2015-04-30T09:08:30.000Z
2018-08-13T05:00:39.000Z
third party/openRTMFP-Cumulus/CumulusLib/sources/Flow.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
third party/openRTMFP-Cumulus/CumulusLib/sources/Flow.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
/* Copyright 2010 OpenRTMFP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License received along this program for more details (or else see http://www.gnu.org/licenses/). This file is a part of Cumulus. */ #include "Flow.h" #include "Logs.h" #include "Util.h" #include "string.h" using namespace std; using namespace Poco; namespace Cumulus { class Packet { public: Packet(PacketReader& fragment) : fragments(1),_pMessage(NULL),_buffer((string::size_type)fragment.available()) { if(_buffer.size()>0) memcpy(&_buffer[0],fragment.current(),_buffer.size()); } ~Packet() { if(_pMessage) delete _pMessage; } void add(PacketReader& fragment) { string::size_type old = _buffer.size(); _buffer.resize(old + (string::size_type)fragment.available()); if(_buffer.size()>old) memcpy(&_buffer[old],fragment.current(),(size_t)fragment.available()); ++(UInt16&)fragments; } PacketReader* release() { if(_pMessage) { ERROR("Packet already released!"); return _pMessage; } _pMessage = new PacketReader(_buffer.size()==0 ? NULL : &_buffer[0],_buffer.size()); (UInt16&)_pMessage->fragments = fragments; return _pMessage; } const UInt32 fragments; private: vector<UInt8> _buffer; PacketReader* _pMessage; }; class Fragment : public Buffer<UInt8> { public: Fragment(PacketReader& data,UInt8 flags) : flags(flags),Buffer<UInt8>(data.available()) { data.readRaw(begin(),size()); } Poco::UInt8 flags; }; Flow::Flow(UInt32 id,const string& signature,const string& name,Peer& peer,Invoker& invoker,BandWriter& band) : id(id),stage(0),peer(peer),invoker(invoker),_completed(false),_pPacket(NULL),_band(band),writer(*new FlowWriter(signature,band)) { if(writer.flowId==0) ((UInt32&)writer.flowId)=id; // create code prefix for a possible response writer._obj.assign(name); } Flow::~Flow() { complete(); writer.close(); } void Flow::complete() { if(_completed) return; if(!writer.signature.empty()) // writer.signature.empty() == FlowNull instance, not display the message in FullNull case DEBUG("Flow %u consumed",id); // delete fragments map<UInt32,Fragment*>::const_iterator it; for(it=_fragments.begin();it!=_fragments.end();++it) delete it->second; _fragments.clear(); // delete receive buffer if(_pPacket) { delete _pPacket; _pPacket=NULL; } _completed=true; } void Flow::fail(const string& error) { ERROR("Flow %u failed : %s",id,error.c_str()); if(!_completed) { BinaryWriter& writer = _band.writeMessage(0x5e,Util::Get7BitValueSize(id)+1); writer.write7BitValue(id); writer.write8(0); // unknown } } Message::Type Flow::unpack(PacketReader& reader) { if(reader.available()==0) return Message::EMPTY; Message::Type type = (Message::Type)reader.read8(); switch(type) { // amf content case 0x11: reader.next(1); case Message::AMF_WITH_HANDLER: reader.next(4); return Message::AMF_WITH_HANDLER; case Message::AMF: reader.next(5); case Message::AUDIO: case Message::VIDEO: break; // raw data case 0x04: reader.next(4); case 0x01: break; default: ERROR("Unpacking type '%02x' unknown",type); break; } return type; } void Flow::commit() { // Lost informations! UInt32 size = 0; list<UInt32> lost; UInt32 current=stage; UInt32 count=0; map<UInt32,Fragment*>::const_iterator it=_fragments.begin(); while(it!=_fragments.end()) { current = it->first-current-2; size += Util::Get7BitValueSize(current); lost.push_back(current); current = it->first; while(++it!=_fragments.end() && it->first==(++current)) ++count; --current; size += Util::Get7BitValueSize(count); lost.push_back(count); count=0; } UInt32 bufferSize = _pPacket ? ((_pPacket->fragments>0x3F00) ? 0 : (0x3F00-_pPacket->fragments)) : 0x7F; if(writer.signature.empty()) bufferSize=0; PacketWriter& ack = _band.writeMessage(0x51,Util::Get7BitValueSize(id)+Util::Get7BitValueSize(bufferSize)+Util::Get7BitValueSize(stage)+size); // UInt32 pos = ack.position(); ack.write7BitValue(id); ack.write7BitValue(bufferSize); ack.write7BitValue(stage); list<UInt32>::const_iterator it2; for(it2=lost.begin();it2!=lost.end();++it2) ack.write7BitValue(*it2); // TRACE("Commit : %s",Util::FormatHex(ack.begin()+pos,ack.position()-pos).c_str()); commitHandler(); writer.flush(); } void Flow::fragmentHandler(UInt32 stage,UInt32 deltaNAck,PacketReader& fragment,UInt8 flags) { if(_completed) return; // TRACE("Flow %u stage %u",id,stage); UInt32 nextStage = this->stage+1; if(stage < nextStage) { DEBUG("Stage %u on flow %u has already been received",stage,id); return; } if(deltaNAck>stage) { WARN("DeltaNAck %u superior to stage %u on flow %u",deltaNAck,stage,id); deltaNAck=stage; } if(this->stage < (stage-deltaNAck)) { map<UInt32,Fragment*>::iterator it=_fragments.begin(); while(it!=_fragments.end()) { if( it->first > stage) break; // leave all stages <= stage PacketReader reader(it->second->begin(),it->second->size()); fragmentSortedHandler(it->first,reader,it->second->flags); if(_completed) // to prevent a crash bug!! (double fragments deletion) return; delete it->second; _fragments.erase(it++); } nextStage = stage; } if(stage>nextStage) { // not following stage, bufferizes the stage map<UInt32,Fragment*>::iterator it = _fragments.lower_bound(stage); if(it==_fragments.end() || it->first!=stage) { if(it!=_fragments.begin()) --it; _fragments.insert(it,pair<UInt32,Fragment*>(stage,new Fragment(fragment,flags))); if(_fragments.size()>100) DEBUG("_fragments.size()=%lu",_fragments.size()); } else DEBUG("Stage %u on flow %u has already been received",stage,id); } else { fragmentSortedHandler(nextStage++,fragment,flags); map<UInt32,Fragment*>::iterator it=_fragments.begin(); while(it!=_fragments.end()) { if( it->first > nextStage) break; PacketReader reader(it->second->begin(),it->second->size()); fragmentSortedHandler(nextStage++,reader,it->second->flags); if(_completed) break; delete it->second; _fragments.erase(it++); } } } void Flow::fragmentSortedHandler(UInt32 stage,PacketReader& fragment,UInt8 flags) { if(stage<=this->stage) { ERROR("Stage %u not sorted on flow %u",stage,id); return; } if(stage>(this->stage+1)) { // not following stage! UInt32 lostCount = stage-this->stage-1; (UInt32&)this->stage = stage; if(_pPacket) { delete _pPacket; _pPacket = NULL; } if(flags&MESSAGE_WITH_BEFOREPART) { lostFragmentsHandler(lostCount+1); return; } lostFragmentsHandler(lostCount); } else (UInt32&)this->stage = stage; // If MESSAGE_ABANDONMENT, content is not the right normal content! if(flags&MESSAGE_ABANDONMENT) { if(_pPacket) { delete _pPacket; _pPacket = NULL; } return; } PacketReader* pMessage(&fragment); if(flags&MESSAGE_WITH_BEFOREPART){ if(!_pPacket) { WARN("A received message tells to have a 'beforepart' and nevertheless partbuffer is empty, certainly some packets were lost"); lostFragmentsHandler(1); delete _pPacket; _pPacket = NULL; return; } _pPacket->add(fragment); if(flags&MESSAGE_WITH_AFTERPART) return; pMessage = _pPacket->release(); } else if(flags&MESSAGE_WITH_AFTERPART) { if(_pPacket) { ERROR("A received message tells to have not 'beforepart' and nevertheless partbuffer exists"); lostFragmentsHandler(_pPacket->fragments); delete _pPacket; } _pPacket = new Packet(fragment); return; } Message::Type type = unpack(*pMessage); if(type!=Message::EMPTY) { writer._callbackHandle = 0; string name; AMFReader amf(*pMessage); if(type==Message::AMF_WITH_HANDLER || type==Message::AMF) { amf.read(name); if(type==Message::AMF_WITH_HANDLER) { writer._callbackHandle = amf.readNumber(); if(amf.followingType()==AMF::Null) amf.readNull(); } } try { switch(type) { case Message::AMF_WITH_HANDLER: case Message::AMF: messageHandler(name,amf); break; case Message::AUDIO: audioHandler(*pMessage); break; case Message::VIDEO: videoHandler(*pMessage); break; default: rawHandler(type,*pMessage); } } catch(Exception& ex) { _error = "flow error, " + ex.displayText(); } catch(exception& ex) { _error = string("flow error, ") + ex.what(); } catch(...) { _error = "Unknown flow error"; } } writer._callbackHandle = 0; if(_pPacket) { delete _pPacket; _pPacket=NULL; } if(flags&MESSAGE_END) complete(); } void Flow::messageHandler(const std::string& name,AMFReader& message) { ERROR("Message '%s' unknown for flow %u",name.c_str(),id); } void Flow::rawHandler(UInt8 type,PacketReader& data) { ERROR("Raw message %s unknown for flow %u",Util::FormatHex(data.current(),data.available()).c_str(),id); } void Flow::audioHandler(PacketReader& packet) { ERROR("Audio packet untreated for flow %u",id); } void Flow::videoHandler(PacketReader& packet) { ERROR("Video packet untreated for flow %u",id); } void Flow::lostFragmentsHandler(UInt32 count) { INFO("%u fragments lost on flow %u",count,id); } } // namespace Cumulus
25.68984
242
0.688905
Patrick-Bay
81ab333630250bf0b6cc8d485148a0564974f1c8
19,863
cpp
C++
dof-mgr/test/dofmngr_test/tGlobalIndexerUtilities.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
1
2022-03-22T03:49:50.000Z
2022-03-22T03:49:50.000Z
dof-mgr/test/dofmngr_test/tGlobalIndexerUtilities.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
dof-mgr/test/dofmngr_test/tGlobalIndexerUtilities.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
// @HEADER // *********************************************************************** // // Panzer: A partial differential equation assembly // engine for strongly coupled complex multiphysics systems // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and // Eric C. Cyr (eccyr@sandia.gov) // *********************************************************************** // @HEADER #include <Teuchos_ConfigDefs.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_TimeMonitor.hpp> #include <Teuchos_ParameterList.hpp> #include <string> #include <iostream> #include <vector> #include <set> #include "Panzer_GlobalIndexer_Utilities.hpp" #include "Panzer_IntrepidFieldPattern.hpp" #include "Panzer_GeometricAggFieldPattern.hpp" #include "UnitTest_GlobalIndexer.hpp" #ifdef HAVE_MPI #include "Epetra_MpiComm.h" #include "mpi.h" #else #include "Epetra_SerialComm.h" #endif #include "Intrepid2_HGRAD_QUAD_C1_FEM.hpp" using Teuchos::rcp; using Teuchos::rcp_dynamic_cast; using Teuchos::RCP; using Teuchos::rcpFromRef; namespace panzer { TEUCHOS_UNIT_TEST(tGlobalIndexer_Utilities,GhostedFieldVector) { // build global (or serial communicator) #ifdef HAVE_MPI RCP<Epetra_Comm> eComm = rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else RCP<Epetra_Comm> eComm = rcp(new Epetra_SerialComm()); #endif int myRank = eComm->MyPID(); int numProcs = eComm->NumProc(); TEUCHOS_ASSERT(numProcs==2); RCP<panzer::GlobalIndexer> globalIndexer = rcp(new panzer::unit_test::GlobalIndexer(myRank,numProcs)); std::vector<int> ghostedFields; std::vector<panzer::GlobalOrdinal> ghostedIndices; globalIndexer->getOwnedAndGhostedIndices(ghostedIndices); panzer::buildGhostedFieldVector(*globalIndexer,ghostedFields); TEST_EQUALITY(ghostedFields.size(),ghostedIndices.size()); TEST_COMPARE(*std::min_element(ghostedFields.begin(),ghostedFields.end()),>,-1); std::stringstream ss; ss << "Field Numbers = "; for(std::size_t i=0;i<ghostedFields.size();i++) ss << ghostedIndices[i] << ":" << ghostedFields[i] << " "; out << std::endl; out << ss.str() << std::endl; if(myRank==0) { TEST_EQUALITY(ghostedFields[0], 0); TEST_EQUALITY(ghostedFields[1], 1); TEST_EQUALITY(ghostedFields[2], 0); TEST_EQUALITY(ghostedFields[3], 1); TEST_EQUALITY(ghostedFields[4], 0); TEST_EQUALITY(ghostedFields[5], 1); TEST_EQUALITY(ghostedFields[6], 0); TEST_EQUALITY(ghostedFields[7], 1); TEST_EQUALITY(ghostedFields[8], 0); TEST_EQUALITY(ghostedFields[9], 1); TEST_EQUALITY(ghostedFields[10],0); TEST_EQUALITY(ghostedFields[11],0); TEST_EQUALITY(ghostedFields[12],0); TEST_EQUALITY(ghostedFields[13],1); } else if(myRank==1) { TEST_EQUALITY(ghostedFields[0], 0); TEST_EQUALITY(ghostedFields[1], 1); TEST_EQUALITY(ghostedFields[2], 0); TEST_EQUALITY(ghostedFields[3], 1); TEST_EQUALITY(ghostedFields[4], 0); TEST_EQUALITY(ghostedFields[5], 1); TEST_EQUALITY(ghostedFields[6], 0); TEST_EQUALITY(ghostedFields[7], 1); TEST_EQUALITY(ghostedFields[8], 0); TEST_EQUALITY(ghostedFields[9], 0); TEST_EQUALITY(ghostedFields[10],0); TEST_EQUALITY(ghostedFields[11],0); } else TEUCHOS_ASSERT(false); } void fillFieldContainer(int fieldNum,const std::string & blockId, const panzer::GlobalIndexer & ugi, Kokkos::DynRankView<int,PHX::Device> & data) { data = Kokkos::DynRankView<int,PHX::Device>("data",1,4); auto host_data = Kokkos::create_mirror_view(data); const std::vector<panzer::LocalOrdinal> & elements = ugi.getElementBlock(blockId); const std::vector<int> & fieldOffsets = ugi.getGIDFieldOffsets(blockId,fieldNum); std::vector<panzer::GlobalOrdinal> gids; for(std::size_t e=0;e<elements.size();e++) { ugi.getElementGIDs(elements[e],gids); for(std::size_t f=0;f<fieldOffsets.size();f++) host_data(e,f) = gids[fieldOffsets[f]]; } Kokkos::deep_copy(data,host_data); } void fillFieldContainer(int fieldNum,const std::string & blockId, const panzer::GlobalIndexer & ugi, Kokkos::DynRankView<int,PHX::Device> & data,std::size_t cols) { data = Kokkos::DynRankView<int,PHX::Device>("data",1,4,cols); auto host_data = Kokkos::create_mirror_view(data); const std::vector<panzer::LocalOrdinal> & elements = ugi.getElementBlock(blockId); const std::vector<int> & fieldOffsets = ugi.getGIDFieldOffsets(blockId,fieldNum); std::vector<panzer::GlobalOrdinal> gids; for(std::size_t e=0;e<elements.size();e++) { ugi.getElementGIDs(elements[e],gids); for(std::size_t f=0;f<fieldOffsets.size();f++) for(std::size_t c=0;c<cols;c++) host_data(e,f,c) = gids[fieldOffsets[f]]+c; } Kokkos::deep_copy(data,host_data); } TEUCHOS_UNIT_TEST(tGlobalIndexer_Utilities,updateGhostedDataVector) { typedef Kokkos::DynRankView<int,PHX::Device> IntFieldContainer; // build global (or serial communicator) #ifdef HAVE_MPI RCP<Epetra_Comm> eComm = rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else RCP<Epetra_Comm> eComm = rcp(new Epetra_SerialComm()); #endif int myRank = eComm->MyPID(); int numProcs = eComm->NumProc(); TEUCHOS_ASSERT(numProcs==2); RCP<panzer::GlobalIndexer> globalIndexer = rcp(new panzer::unit_test::GlobalIndexer(myRank,numProcs)); int uFieldNum = globalIndexer->getFieldNum("U"); int tFieldNum = globalIndexer->getFieldNum("T"); Teuchos::RCP<Tpetra::Vector<int,int,panzer::GlobalOrdinal> > reducedFieldVector = panzer::buildGhostedFieldReducedVector(*globalIndexer); Tpetra::Vector<int,int,panzer::GlobalOrdinal> reducedUDataVector(getFieldMap(uFieldNum,*reducedFieldVector)); Tpetra::Vector<int,int,panzer::GlobalOrdinal> reducedTDataVector(getFieldMap(tFieldNum,*reducedFieldVector)); TEST_EQUALITY(reducedUDataVector.getLocalLength(),8); TEST_EQUALITY(reducedTDataVector.getLocalLength(),4); IntFieldContainer dataU_b0, dataU_b1; fillFieldContainer(uFieldNum,"block_0",*globalIndexer,dataU_b0); fillFieldContainer(uFieldNum,"block_1",*globalIndexer,dataU_b1); IntFieldContainer dataT_b0; fillFieldContainer(tFieldNum,"block_0",*globalIndexer,dataT_b0); updateGhostedDataReducedVector("U","block_0",*globalIndexer,dataU_b0,reducedUDataVector); updateGhostedDataReducedVector("U","block_1",*globalIndexer,dataU_b1,reducedUDataVector); updateGhostedDataReducedVector("T","block_0",*globalIndexer,dataT_b0,reducedTDataVector); std::vector<int> ghostedFields_u(reducedUDataVector.getLocalLength()); std::vector<int> ghostedFields_t(reducedTDataVector.getLocalLength()); reducedUDataVector.get1dCopy(Teuchos::arrayViewFromVector(ghostedFields_u)); reducedTDataVector.get1dCopy(Teuchos::arrayViewFromVector(ghostedFields_t)); if(myRank==0) { TEST_EQUALITY(ghostedFields_u[0], 0); TEST_EQUALITY(ghostedFields_u[1], 2); TEST_EQUALITY(ghostedFields_u[2], 4); TEST_EQUALITY(ghostedFields_u[3], 6); TEST_EQUALITY(ghostedFields_u[4], 8); TEST_EQUALITY(ghostedFields_u[5],12); TEST_EQUALITY(ghostedFields_u[6],13); TEST_EQUALITY(ghostedFields_u[7],10); TEST_EQUALITY(ghostedFields_t[0], 1); TEST_EQUALITY(ghostedFields_t[1], 3); TEST_EQUALITY(ghostedFields_t[2], 5); TEST_EQUALITY(ghostedFields_t[3], 7); } else if(myRank==1) { TEST_EQUALITY(ghostedFields_u[0], 2); TEST_EQUALITY(ghostedFields_u[1], 8); TEST_EQUALITY(ghostedFields_u[2],10); TEST_EQUALITY(ghostedFields_u[3], 4); TEST_EQUALITY(ghostedFields_u[4],12); TEST_EQUALITY(ghostedFields_u[5],14); TEST_EQUALITY(ghostedFields_u[6],15); TEST_EQUALITY(ghostedFields_u[7],13); TEST_EQUALITY(ghostedFields_t[0], 3); TEST_EQUALITY(ghostedFields_t[1], 9); TEST_EQUALITY(ghostedFields_t[2],11); TEST_EQUALITY(ghostedFields_t[3], 5); } else TEUCHOS_ASSERT(false); } TEUCHOS_UNIT_TEST(tGlobalIndexer_Utilities,ArrayToFieldVector_ghost) { typedef Kokkos::DynRankView<int,PHX::Device> IntFieldContainer; // build global (or serial communicator) #ifdef HAVE_MPI RCP<Epetra_Comm> eComm = rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else RCP<Epetra_Comm> eComm = rcp(new Epetra_SerialComm()); #endif int myRank = eComm->MyPID(); int numProcs = eComm->NumProc(); TEUCHOS_ASSERT(numProcs==2); RCP<panzer::GlobalIndexer> globalIndexer = rcp(new panzer::unit_test::GlobalIndexer(myRank,numProcs)); panzer::ArrayToFieldVector atfv(globalIndexer); std::map<std::string,IntFieldContainer> dataU, dataT; fillFieldContainer(globalIndexer->getFieldNum("U"),"block_0",*globalIndexer,dataU["block_0"]); fillFieldContainer(globalIndexer->getFieldNum("U"),"block_1",*globalIndexer,dataU["block_1"]); fillFieldContainer(globalIndexer->getFieldNum("T"),"block_0",*globalIndexer,dataT["block_0"]); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedUDataVector = atfv.getGhostedDataVector<int>("U",dataU); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedTDataVector = atfv.getGhostedDataVector<int>("T",dataT); std::vector<int> ghostedFields_u(reducedUDataVector->getLocalLength()); std::vector<int> ghostedFields_t(reducedTDataVector->getLocalLength()); reducedUDataVector->getVector(0)->get1dCopy(Teuchos::arrayViewFromVector(ghostedFields_u)); reducedTDataVector->getVector(0)->get1dCopy(Teuchos::arrayViewFromVector(ghostedFields_t)); if(myRank==0) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),8); TEST_EQUALITY(reducedTDataVector->getLocalLength(),6); TEST_EQUALITY(ghostedFields_u[0], 0); TEST_EQUALITY(ghostedFields_u[1], 2); TEST_EQUALITY(ghostedFields_u[2], 4); TEST_EQUALITY(ghostedFields_u[3], 6); TEST_EQUALITY(ghostedFields_u[4], 8); TEST_EQUALITY(ghostedFields_u[5],12); TEST_EQUALITY(ghostedFields_u[6],13); TEST_EQUALITY(ghostedFields_u[7],10); TEST_EQUALITY(ghostedFields_t[0], 1); TEST_EQUALITY(ghostedFields_t[1], 3); TEST_EQUALITY(ghostedFields_t[2], 5); TEST_EQUALITY(ghostedFields_t[3], 7); TEST_EQUALITY(ghostedFields_t[4], 9); TEST_EQUALITY(ghostedFields_t[5],11); } else if(myRank==1) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),8); TEST_EQUALITY(reducedTDataVector->getLocalLength(),4); TEST_EQUALITY(ghostedFields_u[0], 2); TEST_EQUALITY(ghostedFields_u[1], 8); TEST_EQUALITY(ghostedFields_u[2],10); TEST_EQUALITY(ghostedFields_u[3], 4); TEST_EQUALITY(ghostedFields_u[4],12); TEST_EQUALITY(ghostedFields_u[5],14); TEST_EQUALITY(ghostedFields_u[6],15); TEST_EQUALITY(ghostedFields_u[7],13); TEST_EQUALITY(ghostedFields_t[0], 3); TEST_EQUALITY(ghostedFields_t[1], 9); TEST_EQUALITY(ghostedFields_t[2],11); TEST_EQUALITY(ghostedFields_t[3], 5); } else TEUCHOS_ASSERT(false); } TEUCHOS_UNIT_TEST(tGlobalIndexer_Utilities,ArrayToFieldVector) { typedef Kokkos::DynRankView<int,PHX::Device> IntFieldContainer; // build global (or serial communicator) #ifdef HAVE_MPI RCP<Epetra_Comm> eComm = rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else RCP<Epetra_Comm> eComm = rcp(new Epetra_SerialComm()); #endif int myRank = eComm->MyPID(); int numProcs = eComm->NumProc(); TEUCHOS_ASSERT(numProcs==2); RCP<panzer::GlobalIndexer> globalIndexer = rcp(new panzer::unit_test::GlobalIndexer(myRank,numProcs)); panzer::ArrayToFieldVector atfv(globalIndexer); std::map<std::string,IntFieldContainer> dataU, dataT; fillFieldContainer(globalIndexer->getFieldNum("U"),"block_0",*globalIndexer,dataU["block_0"]); fillFieldContainer(globalIndexer->getFieldNum("U"),"block_1",*globalIndexer,dataU["block_1"]); fillFieldContainer(globalIndexer->getFieldNum("T"),"block_0",*globalIndexer,dataT["block_0"]); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedUDataVector = atfv.getDataVector<int>("U",dataU); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedTDataVector = atfv.getDataVector<int>("T",dataT); std::vector<int> fields_u(reducedUDataVector->getLocalLength()); std::vector<int> fields_t(reducedTDataVector->getLocalLength()); reducedUDataVector->getVector(0)->get1dCopy(Teuchos::arrayViewFromVector(fields_u)); reducedTDataVector->getVector(0)->get1dCopy(Teuchos::arrayViewFromVector(fields_t)); if(myRank==0) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),6); TEST_EQUALITY(reducedTDataVector->getLocalLength(),5); TEST_EQUALITY(fields_u[0], 6); TEST_EQUALITY(fields_u[1], 0); TEST_EQUALITY(fields_u[2], 2); TEST_EQUALITY(fields_u[3], 8); TEST_EQUALITY(fields_u[4],10); TEST_EQUALITY(fields_u[5],13); TEST_EQUALITY(fields_t[0], 7); TEST_EQUALITY(fields_t[1], 1); TEST_EQUALITY(fields_t[2], 3); TEST_EQUALITY(fields_t[3], 9); TEST_EQUALITY(fields_t[4],11); } else if(myRank==1) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),4); TEST_EQUALITY(reducedTDataVector->getLocalLength(),1); TEST_EQUALITY(fields_u[0], 4); TEST_EQUALITY(fields_u[1],12); TEST_EQUALITY(fields_u[2],15); TEST_EQUALITY(fields_u[3],14); TEST_EQUALITY(fields_t[0], 5); } else TEUCHOS_ASSERT(false); } TEUCHOS_UNIT_TEST(tGlobalIndexer_Utilities,ArrayToFieldVector_multicol) { typedef Kokkos::DynRankView<int,PHX::Device> IntFieldContainer; // build global (or serial communicator) #ifdef HAVE_MPI RCP<Epetra_Comm> eComm = rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else RCP<Epetra_Comm> eComm = rcp(new Epetra_SerialComm()); #endif int myRank = eComm->MyPID(); int numProcs = eComm->NumProc(); TEUCHOS_ASSERT(numProcs==2); RCP<panzer::GlobalIndexer> globalIndexer = rcp(new panzer::unit_test::GlobalIndexer(myRank,numProcs)); panzer::ArrayToFieldVector atfv(globalIndexer); Teuchos::RCP<const Tpetra::Map<int,panzer::GlobalOrdinal> > uMap = atfv.getFieldMap("U"); // these will be tested below! Teuchos::RCP<const Tpetra::Map<int,panzer::GlobalOrdinal> > tMap = atfv.getFieldMap("T"); std::map<std::string,IntFieldContainer> dataU, dataT; std::size_t numCols = 5; fillFieldContainer(globalIndexer->getFieldNum("U"),"block_0",*globalIndexer,dataU["block_0"],numCols); fillFieldContainer(globalIndexer->getFieldNum("U"),"block_1",*globalIndexer,dataU["block_1"],numCols); fillFieldContainer(globalIndexer->getFieldNum("T"),"block_0",*globalIndexer,dataT["block_0"],numCols); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedUDataVector = atfv.getDataVector<int>("U",dataU); Teuchos::RCP<Tpetra::MultiVector<int,int,panzer::GlobalOrdinal> > reducedTDataVector = atfv.getDataVector<int>("T",dataT); TEST_EQUALITY(reducedUDataVector->getNumVectors(),numCols); TEST_EQUALITY(reducedTDataVector->getNumVectors(),numCols); for(std::size_t c=0;c<numCols;c++) { std::vector<int> fields_u(reducedUDataVector->getLocalLength()); std::vector<int> fields_t(reducedTDataVector->getLocalLength()); reducedUDataVector->getVector(c)->get1dCopy(Teuchos::arrayViewFromVector(fields_u)); reducedTDataVector->getVector(c)->get1dCopy(Teuchos::arrayViewFromVector(fields_t)); if(myRank==0) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),6); TEST_EQUALITY(reducedTDataVector->getLocalLength(),5); TEST_EQUALITY(fields_u[0], 6+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[1], 0+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[2], 2+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[3], 8+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[4],10+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[5],13+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[0], 7+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[1], 1+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[2], 3+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[3], 9+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[4],11+Teuchos::as<int>(c)); } else if(myRank==1) { TEST_EQUALITY(reducedUDataVector->getLocalLength(),4); TEST_EQUALITY(reducedTDataVector->getLocalLength(),1); TEST_EQUALITY(fields_u[0], 4+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[1],12+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[2],15+Teuchos::as<int>(c)); TEST_EQUALITY(fields_u[3],14+Teuchos::as<int>(c)); TEST_EQUALITY(fields_t[0], 5+Teuchos::as<int>(c)); } else TEUCHOS_ASSERT(false); } if(myRank==0) { TEST_EQUALITY(uMap->getLocalNumElements(),6); TEST_EQUALITY(uMap->getGlobalElement(0),6); TEST_EQUALITY(uMap->getGlobalElement(1),0); TEST_EQUALITY(uMap->getGlobalElement(2),2); TEST_EQUALITY(uMap->getGlobalElement(3),8); TEST_EQUALITY(uMap->getGlobalElement(4),10); TEST_EQUALITY(uMap->getGlobalElement(5),13); TEST_EQUALITY(tMap->getLocalNumElements(),5); TEST_EQUALITY(tMap->getGlobalElement(0),7); TEST_EQUALITY(tMap->getGlobalElement(1),1); TEST_EQUALITY(tMap->getGlobalElement(2),3); TEST_EQUALITY(tMap->getGlobalElement(3),9); TEST_EQUALITY(tMap->getGlobalElement(4),11); } else if(myRank==1) { TEST_EQUALITY(uMap->getLocalNumElements(),4); TEST_EQUALITY(uMap->getGlobalElement(0),4); TEST_EQUALITY(uMap->getGlobalElement(1),12); TEST_EQUALITY(uMap->getGlobalElement(2),15); TEST_EQUALITY(uMap->getGlobalElement(3),14); TEST_EQUALITY(tMap->getLocalNumElements(),1); TEST_EQUALITY(tMap->getGlobalElement(0),5); } else TEUCHOS_ASSERT(false); } }
38.12476
132
0.704274
hillyuan
81b1dc92ab2ff3381fa3c701f930769f05c6561c
2,949
cpp
C++
Engine/Networking/NetworkHandler.cpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Networking/NetworkHandler.cpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Networking/NetworkHandler.cpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
#include "NetworkHandler.hpp" NetworkHandler::NetworkHandler(){ inPort = outPort = 50012; lastMessageAddress = new char[20]; } /** * Bind the socket to the given port. Opens Socket to listen * to connections on given port. * @param port Port to bind to. */ void NetworkHandler::bind(unsigned short port){ inPort = port; socket.unbind(); socket.bind(inPort); socket.setBlocking(false); } /** * Set outgoing connection info. * @param addr Address to send to. * @param port Port to send to. */ void NetworkHandler::setOutConnection(const char* addr, unsigned short port){ address = addr; outPort = port; } const char* NetworkHandler::getOutAddress(){ #ifdef _PC_ return address.toString().c_str(); #endif } unsigned short NetworkHandler::getOutPort(){ return outPort; } /** * Add message to send. * @param code Message code. * @param data Message data. * @return Iterator pointing to position of added message. */ MessageIterator& NetworkHandler::addMessage(unsigned short code, void* data){ return outQueue.createMessage(code, data); } /** * Send any messages in the queue if they are ready to be sent. */ bool NetworkHandler::sendMessages(){ #ifdef _PC_ if(outQueue.sendQueue(socket, address, outPort) == sf::Socket::Done){ return true; }else{ return false; } #endif } /** * Force send any messages in the queue. */ bool NetworkHandler::forceSendMessages(){ #ifdef _PC_ if(outQueue.forceSendQueue(socket, address, outPort) == sf::Socket::Done){ return true; }else{ return false; } #endif } /** * Get messages from server. * @return MessageQueue with any messages received or 0 if none received. */ MessageQueue* NetworkHandler::getMessages(){ #ifdef _PC_ sf::Packet receivedPacket; sf::IpAddress address; if(socket.receive(receivedPacket, address, lastMessagePort) == sf::Socket::Done){ std::strcpy(lastMessageAddress, address.toString().c_str()); inQueue.parsePacket(receivedPacket); return &inQueue; } return 0; #endif } /** * A blocking call to get messages from server. Waits for specified time. * @param timeout Blocking call timeout time. * @todo Remove sf::Clock usage. */ MessageQueue* NetworkHandler::getMessagesBlocking(unsigned int timeout){ #ifdef _PC_ sf::Clock timer; timer.restart(); MessageQueue* returnQueue = getMessages(); //Attempt reading messages until timeout reached or a message received. while (timer.getElapsedTime().asMilliseconds() < timeout && returnQueue == 0) { sf::sleep(sf::milliseconds(1)); returnQueue = getMessages(); } return returnQueue; #endif } /** * Close connection with server. */ void NetworkHandler::close() { socket.unbind(); } /** * Attempts to close connection. */ NetworkHandler::~NetworkHandler() { close(); delete lastMessageAddress; lastMessageAddress = 0; }
22.860465
85
0.683622
artur-kink
81b9dabcc958fef94124ea2894226716a1682354
1,843
cpp
C++
src/libFonts/GeeGrow_SSD1306_libLettersCyrillic.cpp
geegrow/GeeGrow_SSD1306_128_32
068cad4d844e85ae2d256f770fac3c567126d03b
[ "BSD-3-Clause" ]
null
null
null
src/libFonts/GeeGrow_SSD1306_libLettersCyrillic.cpp
geegrow/GeeGrow_SSD1306_128_32
068cad4d844e85ae2d256f770fac3c567126d03b
[ "BSD-3-Clause" ]
null
null
null
src/libFonts/GeeGrow_SSD1306_libLettersCyrillic.cpp
geegrow/GeeGrow_SSD1306_128_32
068cad4d844e85ae2d256f770fac3c567126d03b
[ "BSD-3-Clause" ]
null
null
null
/*! * @file GeeGrow_SSD1306_libLettersCyrillic.cpp * * This is an addon library for the GeeGrow SSD1306 128x32 display, which implements support of cyrillic letters * https://geegrow.ru * * @section author Author * Written by Anton Pomazanov * * @section license License * BSD license, all text here must be included in any redistribution. * */ #include "GeeGrow_SSD1306_libLettersCyrillic.h" /**************************************************************************/ /*! @brief Send a bitmap of certain cyrillic letter @param _char Symbol to be sent @param _encoding Encoding to use for selecting bitmap @return Pointer to bitmap array */ /**************************************************************************/ uint8_t* GeeGrow_SSD1306_libLettersCyrillic::getBitMap(char _char, uint8_t _encoding){ uint16_t idx = 0; if (_encoding == ENCODING_UTF8) if ((uint8_t)_char >= 144 && (uint8_t)_char <= 175) // А - Я idx = ((uint8_t)_char - 144) * FONT_WIDTH; else if ((uint8_t)_char >= 176 && (uint8_t)_char <= 191) // а - п idx = ((uint8_t)_char - 176 + 32) * FONT_WIDTH; else if ((uint8_t)_char >= 128 && (uint8_t)_char <= 143) // р - я idx = ((uint8_t)_char - 128 + 32 + 16) * FONT_WIDTH; else { Serial.print(F("getBitMap(): char not supported: ")); Serial.println((uint8_t)_char, DEC); return; } if (_encoding == ENCODING_CP1251) if ((uint8_t)_char >= 192 && (uint8_t)_char <= 255) idx = ((uint8_t)_char - 192) * FONT_WIDTH; else { Serial.print(F("getBitMap(): char not supported: ")); Serial.println((uint8_t)_char, DEC); return; } return (fontLibLettersCyrillic + idx); }
35.442308
86
0.55236
geegrow
81ba2157ab715a23b1fcffe35d74136289825e67
2,166
cpp
C++
libs/mesh/meshPhysicalNodesTri2D.cpp
paranumal/benchparanumal
8e2e247ad828282782b2e3dc443167954e90648c
[ "MIT" ]
3
2019-06-14T09:28:51.000Z
2021-12-12T22:49:26.000Z
libs/mesh/meshPhysicalNodesTri2D.cpp
paranumal/benchparanumal
8e2e247ad828282782b2e3dc443167954e90648c
[ "MIT" ]
null
null
null
libs/mesh/meshPhysicalNodesTri2D.cpp
paranumal/benchparanumal
8e2e247ad828282782b2e3dc443167954e90648c
[ "MIT" ]
1
2020-03-25T17:10:25.000Z
2020-03-25T17:10:25.000Z
/* The MIT License (MIT) Copyright (c) 2017-2022 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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 "mesh.hpp" namespace libp { void mesh_t::PhysicalNodesTri2D(){ x.malloc((Nelements+totalHaloPairs)*Np); y.malloc((Nelements+totalHaloPairs)*Np); #pragma omp parallel for for(dlong e=0;e<Nelements;++e){ /* for each element */ dlong id = e*Nverts+0; dfloat xe1 = EX[id+0]; /* x-coordinates of vertices */ dfloat xe2 = EX[id+1]; dfloat xe3 = EX[id+2]; dfloat ye1 = EY[id+0]; /* y-coordinates of vertices */ dfloat ye2 = EY[id+1]; dfloat ye3 = EY[id+2]; for(int n=0;n<Np;++n){ /* for each node */ /* (r,s) coordinates of interpolation nodes*/ dfloat rn = r[n]; dfloat sn = s[n]; /* physical coordinate of interpolation node */ x[e*Np + n] = -0.5*(rn+sn)*xe1 + 0.5*(1+rn)*xe2 + 0.5*(1+sn)*xe3; y[e*Np + n] = -0.5*(rn+sn)*ye1 + 0.5*(1+rn)*ye2 + 0.5*(1+sn)*ye3; } } halo.Exchange(x, Np); halo.Exchange(y, Np); o_x = platform.malloc<dfloat>(Nelements*Np, x); o_y = platform.malloc<dfloat>(Nelements*Np, y); } } //namespace libp
31.391304
78
0.695291
paranumal
81baab1ac6e87fa0ea9ad31634efe841d32df4d8
3,520
cc
C++
test/fuzzers/audio_processing_configs_fuzzer.cc
tangxuan1023/Webrtc-src
506ffb744d2bd50a1f5c2893e414b453ca0f1e99
[ "DOC", "BSD-3-Clause" ]
1
2018-01-30T01:15:38.000Z
2018-01-30T01:15:38.000Z
test/fuzzers/audio_processing_configs_fuzzer.cc
tangxuan1023/Webrtc-src
506ffb744d2bd50a1f5c2893e414b453ca0f1e99
[ "DOC", "BSD-3-Clause" ]
1
2018-02-10T01:29:22.000Z
2018-02-10T01:29:22.000Z
test/fuzzers/audio_processing_configs_fuzzer.cc
tangxuan1023/Webrtc-src
506ffb744d2bd50a1f5c2893e414b453ca0f1e99
[ "DOC", "BSD-3-Clause" ]
1
2018-11-27T09:06:37.000Z
2018-11-27T09:06:37.000Z
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/include/audio_processing.h" #include "test/fuzzers/audio_processing_fuzzer_helper.h" #include "test/fuzzers/fuzz_data_helper.h" namespace webrtc { namespace { std::unique_ptr<AudioProcessing> CreateApm(test::FuzzDataHelper* fuzz_data) { // Parse boolean values for optionally enabling different // configurable public components of APM. bool exp_agc = fuzz_data->ReadOrDefaultValue(true); bool exp_ns = fuzz_data->ReadOrDefaultValue(true); bool bf = fuzz_data->ReadOrDefaultValue(true); bool ef = fuzz_data->ReadOrDefaultValue(true); bool raf = fuzz_data->ReadOrDefaultValue(true); bool da = fuzz_data->ReadOrDefaultValue(true); bool ie = fuzz_data->ReadOrDefaultValue(true); bool red = fuzz_data->ReadOrDefaultValue(true); bool lc = fuzz_data->ReadOrDefaultValue(true); bool hpf = fuzz_data->ReadOrDefaultValue(true); bool aec3 = fuzz_data->ReadOrDefaultValue(true); bool use_aec = fuzz_data->ReadOrDefaultValue(true); bool use_aecm = fuzz_data->ReadOrDefaultValue(true); bool use_agc = fuzz_data->ReadOrDefaultValue(true); bool use_ns = fuzz_data->ReadOrDefaultValue(true); bool use_le = fuzz_data->ReadOrDefaultValue(true); bool use_vad = fuzz_data->ReadOrDefaultValue(true); bool use_agc_limiter = fuzz_data->ReadOrDefaultValue(true); // Filter out incompatible settings that lead to CHECK failures. if (use_aecm && use_aec) { return nullptr; } // Components can be enabled through webrtc::Config and // webrtc::AudioProcessingConfig. Config config; std::unique_ptr<EchoControlFactory> echo_control_factory; if (aec3) { echo_control_factory.reset(new EchoCanceller3Factory()); } config.Set<ExperimentalAgc>(new ExperimentalAgc(exp_agc)); config.Set<ExperimentalNs>(new ExperimentalNs(exp_ns)); if (bf) { config.Set<Beamforming>(new Beamforming()); } config.Set<ExtendedFilter>(new ExtendedFilter(ef)); config.Set<RefinedAdaptiveFilter>(new RefinedAdaptiveFilter(raf)); config.Set<DelayAgnostic>(new DelayAgnostic(da)); config.Set<Intelligibility>(new Intelligibility(ie)); std::unique_ptr<AudioProcessing> apm( AudioProcessingBuilder() .SetEchoControlFactory(std::move(echo_control_factory)) .Create(config)); webrtc::AudioProcessing::Config apm_config; apm_config.residual_echo_detector.enabled = red; apm_config.level_controller.enabled = lc; apm_config.high_pass_filter.enabled = hpf; apm->ApplyConfig(apm_config); apm->echo_cancellation()->Enable(use_aec); apm->echo_control_mobile()->Enable(use_aecm); apm->gain_control()->Enable(use_agc); apm->noise_suppression()->Enable(use_ns); apm->level_estimator()->Enable(use_le); apm->voice_detection()->Enable(use_vad); apm->gain_control()->enable_limiter(use_agc_limiter); return apm; } } // namespace void FuzzOneInput(const uint8_t* data, size_t size) { test::FuzzDataHelper fuzz_data(rtc::ArrayView<const uint8_t>(data, size)); auto apm = CreateApm(&fuzz_data); if (apm) { FuzzAudioProcessing(&fuzz_data, std::move(apm)); } } } // namespace webrtc
36.28866
77
0.750568
tangxuan1023
81be8a37b9807e8be2da3560630c133e01d1d289
452
cpp
C++
codes/HDU/hdu5477.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu5477.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu5477.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 1e5 + 5; int N, A, B, L; int main () { int cas; scanf("%d", &cas); for (int kcas = 1; kcas <= cas; kcas++) { int ans = 0, len = 0; scanf("%d%d%d%d", &N, &A, &B, &L); int l, r; while (N--) { scanf("%d%d", &l, &r); len += r - l; ans += max(len * A - (r - len) * B - ans, 0); } printf("Case #%d: %d\n", kcas, ans); } return 0; }
16.740741
48
0.49115
JeraKrs
81c05331c419e85bbe4689eb301c92164ca455c4
2,409
hpp
C++
src/entropy/BinaryEntropyEncoder.hpp
flanglet/kanzi-cpp
680085d03fdf77d924af61c8333a1257b01b6de5
[ "Apache-2.0" ]
52
2018-05-16T07:31:17.000Z
2022-03-27T17:36:48.000Z
src/entropy/BinaryEntropyEncoder.hpp
flanglet/kanzi-cpp
680085d03fdf77d924af61c8333a1257b01b6de5
[ "Apache-2.0" ]
4
2019-07-20T12:49:05.000Z
2021-12-12T20:34:59.000Z
src/entropy/BinaryEntropyEncoder.hpp
flanglet/kanzi-cpp
680085d03fdf77d924af61c8333a1257b01b6de5
[ "Apache-2.0" ]
1
2019-07-02T13:27:32.000Z
2019-07-02T13:27:32.000Z
/* Copyright 2011-2021 Frederic Langlet Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. you may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef _BinaryEntropyEncoder_ #define _BinaryEntropyEncoder_ #include "../EntropyEncoder.hpp" #include "../Memory.hpp" #include "../Predictor.hpp" #include "../SliceArray.hpp" namespace kanzi { // This class is a generic implementation of a bool entropy encoder class BinaryEntropyEncoder : public EntropyEncoder { private: static const uint64 TOP = 0x00FFFFFFFFFFFFFF; static const uint64 MASK_0_24 = 0x0000000000FFFFFF; static const uint64 MASK_0_32 = 0x00000000FFFFFFFF; static const int MAX_BLOCK_SIZE = 1 << 30; static const int MAX_CHUNK_SIZE = 1 << 26; Predictor* _predictor; uint64 _low; uint64 _high; OutputBitStream& _bitstream; bool _disposed; bool _deallocate; SliceArray<byte> _sba; void _dispose(); protected: virtual void flush(); public: BinaryEntropyEncoder(OutputBitStream& bitstream, Predictor* predictor, bool deallocate=true) THROW; virtual ~BinaryEntropyEncoder(); int encode(const byte block[], uint blkptr, uint count) THROW; OutputBitStream& getBitStream() const { return _bitstream; } virtual void dispose() { _dispose(); } void encodeByte(byte val); void encodeBit(int bit, int pred = 2048); }; inline void BinaryEntropyEncoder::encodeBit(int bit, int pred) { // Update fields with new interval bounds and predictor if (bit == 0) { _low = _low + ((((_high - _low) >> 4) * uint64(pred)) >> 8) + 1; _predictor->update(0); } else { _high = _low + ((((_high - _low) >> 4) * uint64(pred)) >> 8); _predictor->update(1); } // Write unchanged first 32 bits to bitstream if (((_low ^ _high) >> 24) == 0) flush(); } } #endif
29.024096
106
0.660025
flanglet
81c1b5b34e4fa1b70cc06abe76e19c6ec03698f0
678
cpp
C++
src_smartcontract_db/schema_table/record/table_record_local/LocalOidFactory.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_smartcontract_db/schema_table/record/table_record_local/LocalOidFactory.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_smartcontract_db/schema_table/record/table_record_local/LocalOidFactory.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * LocalOidFactory.cpp * * Created on: 2020/09/25 * Author: iizuka */ #include "schema_table/record/table_record_local/LocalOidFactory.h" #include "schema_table/record/table_record_local/LocalCdbOid.h" #include "schema_table/record/table_record_value/VmInstanceValueConverter.h" #include "base_thread/SysMutex.h" #include "base_thread/StackUnlocker.h" namespace codablecash { LocalOidFactory::LocalOidFactory() { this->serial = 1; } LocalOidFactory::~LocalOidFactory() { } LocalCdbOid* LocalOidFactory::createLocalOid() noexcept { SysMutex mutex; StackUnlocker unlocker(&mutex); return new LocalCdbOid(this->serial++); } } /* namespace codablecash */
19.941176
76
0.761062
alinous-core
81c403b2822493ba708a5831aa9ef4335bdf483d
7,424
hpp
C++
libs/boost_1_72_0/boost/proto/detail/traits.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/proto/detail/traits.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/proto/detail/traits.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES) #include <boost/proto/detail/preprocessed/traits.hpp> #elif !defined(BOOST_PP_IS_ITERATING) #define BOOST_PROTO_CHILD(Z, N, DATA) \ /** INTERNAL ONLY */ \ typedef BOOST_PP_CAT(DATA, N) BOOST_PP_CAT(proto_child, N); \ /**/ #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve : 2, line : 0, output : "preprocessed/traits.hpp") #endif /////////////////////////////////////////////////////////////////////////////// /// \file traits.hpp /// Definitions of proto::function, proto::nary_expr and /// proto::result_of::child_c // // Copyright 2008 Eric Niebler. 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) #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve : 1) #endif #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, BOOST_PROTO_MAX_ARITY, <boost / proto / detail / traits.hpp>)) #include BOOST_PP_ITERATE() #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES) #pragma wave option(output : null) #endif #undef BOOST_PROTO_CHILD #else // BOOST_PP_IS_ITERATING #define N BOOST_PP_ITERATION() #if N > 0 /// \brief A metafunction for generating function-call expression types, /// a grammar element for matching function-call expressions, and a /// PrimitiveTransform that dispatches to the <tt>pass_through\<\></tt> /// transform. template <BOOST_PP_ENUM_PARAMS(N, typename A)> struct function #if N != BOOST_PROTO_MAX_ARITY <BOOST_PP_ENUM_PARAMS(N, A) BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_PP_SUB(BOOST_PROTO_MAX_ARITY, N), void BOOST_PP_INTERCEPT)> #endif : proto::transform< function<BOOST_PP_ENUM_PARAMS(N, A) BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_PP_SUB(BOOST_PROTO_MAX_ARITY, N), void BOOST_PP_INTERCEPT)>, int> { typedef proto::expr<proto::tag::function, BOOST_PP_CAT(list, N) < BOOST_PP_ENUM_PARAMS(N, A)>, N > type; typedef proto::basic_expr<proto::tag::function, BOOST_PP_CAT(list, N) < BOOST_PP_ENUM_PARAMS(N, A)>, N > proto_grammar; template <typename Expr, typename State, typename Data> struct impl : detail::pass_through_impl<function, deduce_domain, Expr, State, Data> { }; /// INTERNAL ONLY typedef proto::tag::function proto_tag; BOOST_PP_REPEAT(N, BOOST_PROTO_CHILD, A) BOOST_PP_REPEAT_FROM_TO( N, BOOST_PROTO_MAX_ARITY, BOOST_PROTO_CHILD, detail::if_vararg<BOOST_PP_CAT(A, BOOST_PP_DEC(N))> BOOST_PP_INTERCEPT) }; /// \brief A metafunction for generating n-ary expression types with a /// specified tag type, /// a grammar element for matching n-ary expressions, and a /// PrimitiveTransform that dispatches to the <tt>pass_through\<\></tt> /// transform. /// /// Use <tt>nary_expr\<_, vararg\<_\> \></tt> as a grammar element to match any /// n-ary expression; that is, any non-terminal. template <typename Tag BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)> struct nary_expr #if N != BOOST_PROTO_MAX_ARITY <Tag BOOST_PP_ENUM_TRAILING_PARAMS(N, A) BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_PP_SUB(BOOST_PROTO_MAX_ARITY, N), void BOOST_PP_INTERCEPT)> #endif : proto::transform<nary_expr<Tag BOOST_PP_ENUM_TRAILING_PARAMS(N, A) BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_PP_SUB(BOOST_PROTO_MAX_ARITY, N), void BOOST_PP_INTERCEPT)>, int> { typedef proto::expr<Tag, BOOST_PP_CAT(list, N) < BOOST_PP_ENUM_PARAMS(N, A)>, N > type; typedef proto::basic_expr<Tag, BOOST_PP_CAT(list, N) < BOOST_PP_ENUM_PARAMS(N, A)>, N > proto_grammar; template <typename Expr, typename State, typename Data> struct impl : detail::pass_through_impl<nary_expr, deduce_domain, Expr, State, Data> { }; /// INTERNAL ONLY typedef Tag proto_tag; BOOST_PP_REPEAT(N, BOOST_PROTO_CHILD, A) BOOST_PP_REPEAT_FROM_TO( N, BOOST_PROTO_MAX_ARITY, BOOST_PROTO_CHILD, detail::if_vararg<BOOST_PP_CAT(A, BOOST_PP_DEC(N))> BOOST_PP_INTERCEPT) }; namespace detail { template <template <BOOST_PP_ENUM_PARAMS(N, typename BOOST_PP_INTERCEPT)> class T, BOOST_PP_ENUM_PARAMS(N, typename A)> struct is_callable_< T<BOOST_PP_ENUM_PARAMS(N, A)> BOOST_PROTO_TEMPLATE_ARITY_PARAM(N)> : is_same<BOOST_PP_CAT(A, BOOST_PP_DEC(N)), callable> {}; } // namespace detail #endif namespace result_of { /// \brief A metafunction that returns the type of the Nth child /// of a Proto expression. /// /// A metafunction that returns the type of the Nth child /// of a Proto expression. \c N must be less than /// \c Expr::proto_arity::value. template <typename Expr> struct child_c<Expr, N> { /// Verify that we are not operating on a terminal BOOST_STATIC_ASSERT(0 != Expr::proto_arity_c); /// The raw type of the Nth child as it is stored within /// \c Expr. This may be a value or a reference typedef typename Expr::BOOST_PP_CAT(proto_child, N) value_type; /// The "value" type of the child, suitable for return by value, /// computed as follows: /// \li <tt>T const &</tt> becomes <tt>T</tt> /// \li <tt>T &</tt> becomes <tt>T</tt> /// \li <tt>T</tt> becomes <tt>T</tt> typedef typename detail::expr_traits<typename Expr::BOOST_PP_CAT( proto_child, N)>::value_type type; }; template <typename Expr> struct child_c<Expr &, N> { /// Verify that we are not operating on a terminal BOOST_STATIC_ASSERT(0 != Expr::proto_arity_c); /// The raw type of the Nth child as it is stored within /// \c Expr. This may be a value or a reference typedef typename Expr::BOOST_PP_CAT(proto_child, N) value_type; /// The "reference" type of the child, suitable for return by /// reference, computed as follows: /// \li <tt>T const &</tt> becomes <tt>T const &</tt> /// \li <tt>T &</tt> becomes <tt>T &</tt> /// \li <tt>T</tt> becomes <tt>T &</tt> typedef typename detail::expr_traits<typename Expr::BOOST_PP_CAT( proto_child, N)>::reference type; /// INTERNAL ONLY /// BOOST_FORCEINLINE static type call(Expr &e) { return e.proto_base().BOOST_PP_CAT(child, N); } }; template <typename Expr> struct child_c<Expr const &, N> { /// Verify that we are not operating on a terminal BOOST_STATIC_ASSERT(0 != Expr::proto_arity_c); /// The raw type of the Nth child as it is stored within /// \c Expr. This may be a value or a reference typedef typename Expr::BOOST_PP_CAT(proto_child, N) value_type; /// The "const reference" type of the child, suitable for return by /// const reference, computed as follows: /// \li <tt>T const &</tt> becomes <tt>T const &</tt> /// \li <tt>T &</tt> becomes <tt>T &</tt> /// \li <tt>T</tt> becomes <tt>T const &</tt> typedef typename detail::expr_traits<typename Expr::BOOST_PP_CAT( proto_child, N)>::const_reference type; /// INTERNAL ONLY /// BOOST_FORCEINLINE static type call(Expr const &e) { return e.proto_base().BOOST_PP_CAT(child, N); } }; } // namespace result_of #undef N #endif
36.935323
80
0.670663
henrywarhurst
81c4611002014185af5342ee8b4909b2d43dc54c
851
hpp
C++
include/concept/numeric.hpp
janisozaur/safe_numerics
c494e9d6bddc47292b1bb1552469196b01fcdc55
[ "BSL-1.0" ]
null
null
null
include/concept/numeric.hpp
janisozaur/safe_numerics
c494e9d6bddc47292b1bb1552469196b01fcdc55
[ "BSL-1.0" ]
null
null
null
include/concept/numeric.hpp
janisozaur/safe_numerics
c494e9d6bddc47292b1bb1552469196b01fcdc55
[ "BSL-1.0" ]
null
null
null
#ifndef BOOST_NUMERIC_CONCEPT_NUMERIC_HPP #define BOOST_NUMERIC_CONCEPT_NUMERIC_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // Copyright (c) 2012 Robert Ramey // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <limits> namespace boost { namespace numeric { template<class T> struct Numeric { // if your program traps here, you need to create a // std::numeric_limits class for your type T. see // see C++ standard 18.3.2.2 static_assert( std::numeric_limits<T>::is_specialized, "std::numeric_limits<T> has not been specialized for this type" ); }; } // numeric } // boost #endif // BOOST_NUMERIC_CONCEPT_NUMERIC_HPP
24.314286
71
0.716804
janisozaur
81c5fcf526e6ff58d6576cc3b71c80bb83acfd24
2,957
cpp
C++
src/Yson/Common/ReaderIterators.cpp
jebreimo/Yson
499374426a49a5e70658623fdce69bfaa203cc1c
[ "BSD-2-Clause" ]
1
2022-03-07T08:45:50.000Z
2022-03-07T08:45:50.000Z
src/Yson/Common/ReaderIterators.cpp
jebreimo/Yson
499374426a49a5e70658623fdce69bfaa203cc1c
[ "BSD-2-Clause" ]
null
null
null
src/Yson/Common/ReaderIterators.cpp
jebreimo/Yson
499374426a49a5e70658623fdce69bfaa203cc1c
[ "BSD-2-Clause" ]
null
null
null
//**************************************************************************** // Copyright © 2021 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2021-06-03. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include "Yson/ReaderIterators.hpp" namespace Yson { namespace detail { bool initialize(Reader& reader) { auto state = reader.state(); if (state == ReaderState::INITIAL_STATE || (state == ReaderState::AT_START && reader.scope().empty())) { if (!reader.nextValue()) return false; } reader.enter(); return true; } } ObjectKeyIterator::ObjectKeyIterator() : m_Reader(nullptr), m_AtEnd(true) {} ObjectKeyIterator::ObjectKeyIterator(Reader & reader) : m_Reader(&reader), m_AtEnd(!detail::initialize(*m_Reader)) { if (!m_AtEnd) operator++(); } const std::string& ObjectKeyIterator::operator*() const { return m_Key; } const std::string* ObjectKeyIterator::operator->() const { return &m_Key; } ObjectKeyIterator& ObjectKeyIterator::operator++() { if (!m_AtEnd) { if (m_Reader->nextKey()) { m_Reader->read(m_Key); m_Reader->nextValue(); } else { m_Reader->leave(); m_AtEnd = true; } } return *this; } bool operator==(const ObjectKeyIterator& a, const ObjectKeyIterator& b) { return &a == &b || (a.m_AtEnd && b.m_AtEnd); } bool operator!=(const ObjectKeyIterator& a, const ObjectKeyIterator& b) { return !(a == b); } ObjectKeyIteratorAdapter::ObjectKeyIteratorAdapter(Reader& reader) : m_Reader(&reader) {} ObjectKeyIterator ObjectKeyIteratorAdapter::begin() { if (!m_Reader) YSON_THROW("begin() can only be called once."); auto* reader = m_Reader; m_Reader = nullptr; return ObjectKeyIterator(*reader); } ObjectKeyIterator ObjectKeyIteratorAdapter::end() const { return ObjectKeyIterator(); } ArrayIterator::ArrayIterator(Reader& reader) : m_Reader (& reader), m_State(0) {} bool ArrayIterator::next() { if (m_State == 0) m_State = detail::initialize(*m_Reader) ? 1 : 2; if (m_State == 1) { if (m_Reader->nextValue()) return true; m_State = 2; m_Reader->leave(); } return false; } }
23.846774
78
0.487656
jebreimo
81cb63447779129f7bc92e2b8673ff59767110ca
37,720
hxx
C++
include/nifty/graph/opt/multicut/cgc.hxx
DerThorsten/n3p
c4bd4cd90f20e68f0dbd62587aba28e4752a0ac1
[ "MIT" ]
38
2016-06-29T07:42:50.000Z
2021-12-09T09:25:25.000Z
include/nifty/graph/opt/multicut/cgc.hxx
tbullmann/nifty
00119fd4753817b931272d6d3120b6ebd334882a
[ "MIT" ]
62
2016-07-27T16:07:53.000Z
2022-03-30T17:24:36.000Z
include/nifty/graph/opt/multicut/cgc.hxx
tbullmann/nifty
00119fd4753817b931272d6d3120b6ebd334882a
[ "MIT" ]
20
2016-01-25T21:21:52.000Z
2021-12-09T09:25:16.000Z
#pragma once #include <queue> #include "boost/format.hpp" #include "nifty/tools/changable_priority_queue.hxx" #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/components.hxx" #include "nifty/graph/opt/multicut/multicut_base.hxx" #include "nifty/graph/opt/common/solver_factory.hxx" #include "nifty/graph/opt/multicut/multicut_objective.hxx" #include "nifty/graph/undirected_list_graph.hxx" #include "nifty/ufd/ufd.hxx" #include "nifty/graph/edge_contraction_graph.hxx" #include "nifty/graph/opt/mincut/mincut_visitor_base.hxx" #include "nifty/graph/opt/mincut/mincut_base.hxx" #include "nifty/graph/opt/mincut/mincut_objective.hxx" #include "nifty/graph/undirected_list_graph.hxx" namespace nifty{ namespace graph{ namespace opt{ namespace multicut{ /// \cond HIDDEN_SYMBOLS namespace detail_cgc{ template<class OBJECTIVE> class SubmodelOptimizer{ public: typedef OBJECTIVE ObjectiveType; typedef typename ObjectiveType::WeightType WeightType; typedef MulticutBase<ObjectiveType> MulticutBaseType; typedef typename ObjectiveType::GraphType GraphType; typedef typename ObjectiveType::WeightsMap WeightsMapType; typedef typename GraphType:: template NodeMap<uint64_t> GlobalNodeToLocal; typedef std::vector<uint64_t> LocalNodeToGlobal; typedef typename GraphType:: template EdgeMap<uint8_t> IsDirtyEdge; typedef nifty::graph::UndirectedGraph<> SubGraph; typedef mincut::MincutObjective<SubGraph, double> MincutSubObjective; typedef mincut::MincutBase<MincutSubObjective> MincutSubBase; typedef nifty::graph::opt::common::SolverFactoryBase<MincutSubBase> MincutSubMcFactoryBase; typedef mincut::MincutVerboseVisitor<MincutSubObjective> SubMcVerboseVisitor; typedef typename MincutSubBase::NodeLabelsType MincutSubNodeLabels; struct Optimzie1ReturnType{ Optimzie1ReturnType(const bool imp, const double val) : improvment(imp), minCutValue(val){ } bool improvment; double minCutValue; }; struct Optimzie2ReturnType{ Optimzie2ReturnType(const bool imp, const double val) : improvment(imp), improvedBy(val){ } bool improvment; double improvedBy; }; SubmodelOptimizer( const ObjectiveType & objective, IsDirtyEdge & isDirtyEdge, std::shared_ptr<MincutSubMcFactoryBase> & mincutFactory ) : objective_(objective), graph_(objective.graph()), weights_(objective.weights()), globalNodeToLocal_(objective.graph()), localNodeToGlobal_(objective.graph().numberOfNodes()), nLocalNodes_(0), nLocalEdges_(0), ufd_(), isDirtyEdge_(isDirtyEdge), mincutFactory_(mincutFactory), insideEdges_(), borderEdges_() { isDirtyEdge_.reserve(graph_.numberOfNodes()); borderEdges_.reserve(graph_.numberOfNodes()/4); if(!bool(mincutFactory)){ throw std::runtime_error("Cgc mincutFactory shall not be empty"); } } template<class NODE_LABELS, class ANCHOR_QUEUE> Optimzie1ReturnType optimize1( NODE_LABELS & nodeLabels, const uint64_t anchorNode, ANCHOR_QUEUE & anchorQueue ){ // get mapping from local to global and vice versa // also counts nLocalEdges const auto maxNodeLabel = this->varMapping(nodeLabels, anchorNode); //std::cout<<"nLocalNodes "<<nLocalNodes_<<"\n"; //for(auto localNode=0; localNode<nLocalNodes_; ++localNode){ // std::cout<<"uLocal "<<localNode<<" "<<localNodeToGlobal_[localNode]<<"\n"; //} ufd_.assign(nLocalNodes_); if(nLocalNodes_ >= 2){ const auto anchorLabel = nodeLabels[anchorNode]; // setup the submodel SubGraph subGraph(nLocalNodes_); MincutSubObjective subObjective(subGraph); auto & subWeights = subObjective.weights(); //NIFTY_CHECK_OP(0,==,subWeights.size(),""); this->forEachInternalEdge(nodeLabels, anchorLabel,[&](const uint64_t uLocal, const uint64_t vLocal, const uint64_t edge){ const auto w = weights_[edge]; //NIFTY_CHECK_OP(subGraph.findEdge(uLocal, vLocal),==,-1,""); const auto edgeId = subGraph.insertEdge(uLocal, vLocal); // NIFTY_CHECK_OP(edgeId,==,subWeights.size(),""); subWeights.insertedEdges(edgeId); subWeights[edgeId] = w; }); // solve it MincutSubNodeLabels subgraphRes(subGraph); auto solverPtr = mincutFactory_->create(subObjective); //SubMcVerboseVisitor visitor; solverPtr->optimize(subgraphRes,nullptr); const auto minCutValue = subObjective.evalNodeLabels(subgraphRes); delete solverPtr; Optimzie1ReturnType res(false,minCutValue); if(minCutValue < 0.0){ //std::cout<<"minCutValue "<<minCutValue<<"\n"; this->forEachInternalEdge(nodeLabels, anchorLabel,[&](const uint64_t uLocal, const uint64_t vLocal, const uint64_t edge){ if(subgraphRes[uLocal] == subgraphRes[vLocal]){ ufd_.merge(uLocal, vLocal); } }); NIFTY_CHECK_OP(ufd_.numberOfSets(),>=,2,""); res.improvment = true; res.minCutValue = minCutValue; std::unordered_map<uint64_t,uint64_t> mapping; ufd_.representativeLabeling(mapping); std::vector<uint64_t> anchors(mapping.size()); std::vector<uint64_t> anchorsSize(mapping.size(),0); for(auto localNode=0; localNode<nLocalNodes_; ++localNode){ const auto node = localNodeToGlobal_[localNode]; const auto denseLocalLabel = mapping[ufd_.find(localNode)]; anchorsSize[denseLocalLabel] +=1; anchors[denseLocalLabel] = node; nodeLabels[node] = denseLocalLabel + maxNodeLabel + 1; //std::cout<<" res localNode "<<localNode<<" "<<nodeLabels[node]<<"\n"; } //std::cout<<"---\n"; for(auto i=0; i<anchors.size(); ++i){ if(anchorsSize[i] > 1){ res.improvment = true; //std::cout<<"push "<<anchors[i]<<"\n"; anchorQueue.push(anchors[i]); } } //std::cout<<"ret.minCutValue "<<res.minCutValue<<"\n"; //std::cout<<"ret.improvment "<<res.improvment<<"\n"; } return res; } else{ return Optimzie1ReturnType(false,0.0); } } template<class NODE_LABELS> Optimzie2ReturnType optimize2( NODE_LABELS & nodeLabels, const uint64_t anchorNode0, const uint64_t anchorNode1 ){ // get mapping from local to global and vice versa // also counts nLocalEdges const auto maxNodeLabel = this->varMapping(nodeLabels, anchorNode0, anchorNode1); // setup the submodel SubGraph subGraph(nLocalNodes_); MincutSubObjective subObjective(subGraph); auto & subWeights = subObjective.weights(); ufd_.assign(nLocalNodes_); const auto anchorLabel0 = nodeLabels[anchorNode0]; const auto anchorLabel1 = nodeLabels[anchorNode1]; auto currentCutValue = 0.0; this->forEachInternalEdge(nodeLabels, anchorLabel0, anchorLabel1,[&](const uint64_t uLocal, const uint64_t vLocal, const uint64_t edge){ const auto w = weights_[edge]; const auto edgeId = subGraph.insertEdge(uLocal, vLocal); subWeights.insertedEdges(edgeId); subWeights[edgeId] = w; if(nodeLabels[localNodeToGlobal_[uLocal]] != nodeLabels[localNodeToGlobal_[vLocal]]){ currentCutValue += w; } }); // optimize MincutSubNodeLabels subgraphRes(subGraph); auto solverPtr = mincutFactory_->create(subObjective); solverPtr->optimize(subgraphRes,nullptr); const auto minCutValue = subObjective.evalNodeLabels(subgraphRes); delete solverPtr; Optimzie2ReturnType ret(false, 0.0); // is there an improvement if(minCutValue + 1e-7 < currentCutValue){ this->forEachInternalEdge(nodeLabels, anchorLabel0, anchorLabel1,[&](const uint64_t uLocal, const uint64_t vLocal, const uint64_t edge){ if(subgraphRes[uLocal] == subgraphRes[vLocal]){ ufd_.merge(uLocal, vLocal); } }); std::unordered_map<uint64_t,uint64_t> mapping; ufd_.representativeLabeling(mapping); for(auto localNode=0; localNode<nLocalNodes_; ++localNode){ const auto node = localNodeToGlobal_[localNode]; const auto denseLocalLabel = mapping[ufd_.find(localNode)]; nodeLabels[node] = denseLocalLabel + maxNodeLabel + 1; } ret.improvment = true; ret.improvedBy = currentCutValue - minCutValue; // update isDirty if(ufd_.numberOfSets() <= 2){ // set inside to clean // border to dirty for(const auto edge : insideEdges_){ // already done // isDirtyEdge_[edge] = false; } for(const auto edge : borderEdges_){ isDirtyEdge_[edge] = true; } } else{ for(const auto edge : insideEdges_){ isDirtyEdge_[edge] = true; } for(const auto edge : borderEdges_){ isDirtyEdge_[edge] = true; } } } return ret; } private: template<class NODE_LABELS> uint64_t varMapping( const NODE_LABELS & nodeLabels, const uint64_t anchorNode0 ){ return varMapping(nodeLabels, anchorNode0, anchorNode0); } template<class NODE_LABELS> uint64_t varMapping( const NODE_LABELS & nodeLabels, const uint64_t anchorNode0, const uint64_t anchorNode1 ){ insideEdges_.clear(); borderEdges_.clear(); nLocalNodes_ = 0; nLocalEdges_ = 0; uint64_t maxNodeLabel = 0; const auto anchorLabel0 = nodeLabels[anchorNode0]; const auto anchorLabel1 = nodeLabels[anchorNode1]; for(const auto node : graph_.nodes()){ const auto nodeLabel = nodeLabels[node]; maxNodeLabel = std::max(maxNodeLabel, nodeLabel); if(nodeLabel == anchorLabel0 || nodeLabel == anchorLabel1){ globalNodeToLocal_[node] = nLocalNodes_; localNodeToGlobal_[nLocalNodes_] = node; nLocalNodes_ += 1; for(const auto adj : graph_.adjacency(node)){ const auto otherNode = adj.node(); const auto edge = adj.edge(); if(node < otherNode){ const auto otherNodeLabel = nodeLabels[otherNode]; if(otherNodeLabel == anchorLabel0 || otherNodeLabel == anchorLabel1){ nLocalEdges_ += 1; insideEdges_.push_back(edge); // mark inside edge as clear isDirtyEdge_[edge] = false; } // border node else{ borderEdges_.push_back(edge); } } } } } return maxNodeLabel; } template<class NODE_LABELS, class F> void forEachInternalEdge(const NODE_LABELS & nodeLabels, const uint64_t anchorLabel, F && f){ for(auto localNode=0; localNode<nLocalNodes_; ++localNode){ const auto u = localNodeToGlobal_[localNode]; const auto uLocal = globalNodeToLocal_[u]; NIFTY_CHECK_OP(localNode,==,uLocal,""); for(const auto adj : graph_.adjacency(u)){ const auto v = adj.node(); const auto edge = adj.edge(); if(u < v && nodeLabels[v] == anchorLabel){ const auto vLocal = globalNodeToLocal_[v]; f(uLocal, vLocal, edge); } } } } template<class NODE_LABELS, class F> void forEachInternalEdge( const NODE_LABELS & nodeLabels, const uint64_t anchorLabel0, const uint64_t anchorLabel1, F && f ){ for(auto localNode=0; localNode<nLocalNodes_; ++localNode){ const auto u = localNodeToGlobal_[localNode]; const auto uLocal = globalNodeToLocal_[u]; NIFTY_CHECK_OP(localNode,==,uLocal,""); for(const auto adj : graph_.adjacency(u)){ const auto v = adj.node(); const auto edge = adj.edge(); if(u < v){ const auto vLabel = nodeLabels[v]; if(vLabel == anchorLabel0 || vLabel == anchorLabel1){ const auto vLocal = globalNodeToLocal_[v]; f(uLocal, vLocal, edge); } } } } } const ObjectiveType & objective_; const GraphType & graph_; const WeightsMapType & weights_; GlobalNodeToLocal globalNodeToLocal_; LocalNodeToGlobal localNodeToGlobal_; uint64_t nLocalNodes_; uint64_t nLocalEdges_; nifty::ufd::Ufd<uint64_t> ufd_; IsDirtyEdge & isDirtyEdge_; std::shared_ptr<MincutSubMcFactoryBase> & mincutFactory_; std::vector<uint64_t> insideEdges_; std::vector<uint64_t> borderEdges_; }; template<class OBJECTIVE> class Cgc ; template<class OBJECTIVE, class SETTINGS> class PartitionCallback{ public: typedef SETTINGS SettingsType; typedef PartitionCallback<OBJECTIVE, SETTINGS> SelfType; typedef OBJECTIVE ObjectiveType; typedef typename ObjectiveType::GraphType GraphType; typedef typename GraphType:: template NodeMap<uint64_t> CcNodeSize; typedef typename GraphType:: template EdgeMap<float> McWeights; typedef nifty::tools::ChangeablePriorityQueue< double ,std::less<double> > QueueType; PartitionCallback( const ObjectiveType & objective, const SettingsType & settings ) : objective_(objective), graph_(objective.graph()), pq_(objective.graph().edgeIdUpperBound()+1 ), ccNodeSize_(objective.graph()), mcWeights_(objective_.graph()), settings_(settings), currentNodeNum_(objective.graph().numberOfNodes()), edgeContractionGraph_(objective.graph(), *this) { // //std::cout<<"nodeNumStopCond "<<settings_.nodeNumStopCond<<"\n"; //std::cout<<"sizeRegularizer "<<settings_.sizeRegularizer<<"\n"; this->reset(); } void reset(){ // reset queue in case something is left while(!pq_.empty()) pq_.pop(); for(const auto node: graph_.nodes()){ ccNodeSize_[node] = 1; } const auto & weights = objective_.weights(); for(const auto edge: graph_.edges()){ mcWeights_[edge] = weights[edge]; pq_.push(edge, this->computeWeight(edge)); } this->edgeContractionGraph_.reset(); } void contractEdge(const uint64_t edgeToContract){ NIFTY_ASSERT(pq_.contains(edgeToContract)); pq_.deleteItem(edgeToContract); } void mergeNodes(const uint64_t aliveNode, const uint64_t deadNode){ ccNodeSize_[aliveNode] += ccNodeSize_[deadNode]; --currentNodeNum_; } void mergeEdges(const uint64_t aliveEdge, const uint64_t deadEdge){ NIFTY_ASSERT(pq_.contains(aliveEdge)); NIFTY_ASSERT(pq_.contains(deadEdge)); mcWeights_[aliveEdge] += mcWeights_[deadEdge]; ///const auto wEdgeInAlive = pq_.priority(aliveEdge); //const auto wEdgeInDead = pq_.priority(deadEdge); pq_.deleteItem(deadEdge); //pq_.changePriority(aliveEdge, wEdgeInAlive + wEdgeInDead); } double computeWeight(const uint64_t edge)const{ const auto su = double(ccNodeSize_[edgeContractionGraph_.u(edge)]); const auto sv = double(ccNodeSize_[edgeContractionGraph_.v(edge)]); const auto sr = settings_.sizeRegularizer; const auto sFac =2.0 / ( 1.0/std::pow(su, sr) + 1.0/std::pow(sv, sr) ); const auto p1 = 1.0/(std::exp(mcWeights_[edge])+1.0); //std::cout<<"w "<<mcWeights_[edge]<<" p "<<p1<<" sFac "<<sFac<<"\n"; return p1 * sFac; } void contractEdgeDone(const uint64_t edgeToContract){ // HERE WE UPDATE const auto u = edgeContractionGraph_.nodeOfDeadEdge(edgeToContract); for(auto adj : edgeContractionGraph_.adjacency(u)){ const auto edge = adj.edge(); pq_.push(edge, computeWeight(edge)); } } bool done(){ const auto nnsc = settings_.nodeNumStopCond; uint64_t ns; if(nnsc >= 1.0){ ns = static_cast<uint64_t>(nnsc); } else{ ns = static_cast<uint64_t>(double(graph_.numberOfNodes())*nnsc +0.5); } if(currentNodeNum_ <= ns){ return true; } if(currentNodeNum_<=1){ return true; } if(pq_.empty()){ return true; } return false; } uint64_t edgeToContract(){ // return pq_.top(); } void changeSettings(const SettingsType & settings){ settings_ = settings; } const QueueType & queue()const{ // return pq_; } EdgeContractionGraph<GraphType, SelfType> & edgeContractionGraph(){ return edgeContractionGraph_; } const EdgeContractionGraph<GraphType, SelfType> & edgeContractionGraph()const{ return edgeContractionGraph_; } private: const ObjectiveType & objective_; const GraphType & graph_; QueueType pq_; CcNodeSize ccNodeSize_; McWeights mcWeights_; SettingsType settings_; uint64_t currentNodeNum_; EdgeContractionGraph<GraphType, SelfType> edgeContractionGraph_; }; } /// \endcond template<class OBJECTIVE> class Cgc : public MulticutBase<OBJECTIVE> { public: typedef OBJECTIVE ObjectiveType; typedef typename ObjectiveType::WeightType WeightType; typedef MulticutBase<ObjectiveType> BaseType; typedef typename BaseType::VisitorBaseType VisitorBaseType; typedef typename BaseType::VisitorProxyType VisitorProxyType; typedef typename BaseType::NodeLabelsType NodeLabelsType; typedef typename ObjectiveType::GraphType GraphType; typedef typename ObjectiveType::WeightsMap WeightsMap; typedef typename GraphType:: template EdgeMap<uint8_t> IsDirtyEdge; typedef UndirectedGraph<> SubGraph; typedef mincut::MincutObjective<SubGraph, double> MincutSubObjective; typedef mincut::MincutBase<MincutSubObjective> MincutSubBase; typedef nifty::graph::opt::common::SolverFactoryBase<MincutSubBase> MincutSubMcFactoryBase; typedef typename MincutSubBase::NodeLabelsType MincutSubNodeLabels; typedef MulticutObjective<SubGraph, double> MulticutSubObjective; typedef MulticutBase<MulticutSubObjective> MulticutSubBase; typedef nifty::graph::opt::common::SolverFactoryBase<MulticutSubBase> MulticutSubMcFactoryBase; typedef typename MulticutSubBase::NodeLabelsType MulticutSubNodeLabels; typedef nifty::graph::opt::common::SolverFactoryBase<BaseType> FactoryBase; private: typedef ComponentsUfd<GraphType> Components; public: struct SettingsType { double nodeNumStopCond{0.1}; double sizeRegularizer{1.0}; bool doCutPhase{true}; bool doBetterCutPhase{false}; bool doGlueAndCutPhase{true}; std::shared_ptr<MincutSubMcFactoryBase> mincutFactory; std::shared_ptr<MulticutSubMcFactoryBase> multicutFactory; }; private: typedef detail_cgc::PartitionCallback<OBJECTIVE, SettingsType> CallbackType; //typedef typename CallbackType::SettingsType CallbackSettingsType; public: virtual ~Cgc(){ } Cgc(const ObjectiveType & objective, const SettingsType & settings = SettingsType()); virtual void optimize(NodeLabelsType & nodeLabels, VisitorBaseType * visitor); virtual const ObjectiveType & objective() const; virtual const NodeLabelsType & currentBestNodeLabels( ){ return *currentBest_; } virtual std::string name()const{ return std::string("Cgc"); } virtual void weightsChanged(){ } virtual double currentBestEnergy() { return currentBestEnergy_; } private: void cutPhase(VisitorProxyType & visitorProxy); void betterCutPhase(VisitorProxyType & visitorProxy); void glueAndCutPhase(VisitorProxyType & visitorProxy); const ObjectiveType & objective_; const GraphType & graph_; const WeightsMap & weights_; Components components_; SettingsType settings_; IsDirtyEdge isDirtyEdge_; detail_cgc::SubmodelOptimizer<ObjectiveType> submodel_; NodeLabelsType * currentBest_; double currentBestEnergy_; }; template<class OBJECTIVE> Cgc<OBJECTIVE>:: Cgc( const ObjectiveType & objective, const SettingsType & settings ) : objective_(objective), graph_(objective.graph()), weights_(objective_.weights()), components_(graph_), settings_(settings), isDirtyEdge_(graph_,true), submodel_(objective, isDirtyEdge_, settings_.mincutFactory), currentBest_(nullptr), currentBestEnergy_(std::numeric_limits<double>::infinity()) { } template<class OBJECTIVE> void Cgc<OBJECTIVE>:: cutPhase( VisitorProxyType & visitorProxy ){ // the node labeling as reference auto & nodeLabels = *currentBest_; // number of components const auto nComponents = components_.buildFromLabels(nodeLabels); components_.denseRelabeling(nodeLabels); // get anchor for each component std::vector<uint64_t> componentsAnchors(nComponents); // anchors graph_.forEachNode([&](const uint64_t node){ componentsAnchors[nodeLabels[node]] = node; }); std::queue<uint64_t> anchorQueue; for(const auto & anchor : componentsAnchors){ anchorQueue.push(anchor); } // while nothing is on the queue visitorProxy.clearLogNames(); visitorProxy.addLogNames({std::string("QueueSize"),std::string("E"),std::string("EE")}); while(!anchorQueue.empty()){ //std::cout<<"a) "<<anchorQueue.size()<<"\n"; const auto anchorNode = anchorQueue.front(); anchorQueue.pop(); const auto anchorLabel = nodeLabels[anchorNode]; //std::cout<<"b) "<<anchorQueue.size()<<"\n"; //visitorProxy.printLog(nifty::logging::LogLevel::INFO, "Optimzie1"); // optimize the submodel const auto ret = submodel_.optimize1(nodeLabels, anchorNode, anchorQueue); if(ret.improvment){ //std::cout<<"old current best "<<currentBestEnergy_<<"\n"; currentBestEnergy_ += ret.minCutValue; //std::cout<<"new current best "<<currentBestEnergy_<<"\n"; } //std::cout<<"c) "<<anchorQueue.size()<<"\n"; visitorProxy.setLogValue(0, anchorQueue.size()); visitorProxy.setLogValue(1, currentBestEnergy_); visitorProxy.setLogValue(2, objective_.evalNodeLabels(*currentBest_)); if(!visitorProxy.visit(this)){ break; } } visitorProxy.visit(this); visitorProxy.clearLogNames(); } template<class OBJECTIVE> void Cgc<OBJECTIVE>:: betterCutPhase( VisitorProxyType & visitorProxy ){ visitorProxy.clearLogNames(); visitorProxy.addLogNames({std::string("#Node"),std::string("priority")}); if(! bool(settings_.multicutFactory)){ throw std::runtime_error("if betterCutPhase is used multicutFactory shall not be empty"); } // the node labeling as reference auto & nodeLabels = *currentBest_; // run the cluster algorithm CallbackType callback(objective_, settings_); auto & edgeContractionGraph = callback.edgeContractionGraph(); while(!callback.done() ){ edgeContractionGraph.contractEdge(callback.edgeToContract()); visitorProxy.setLogValue(0, edgeContractionGraph.numberOfNodes()); visitorProxy.setLogValue(1, callback.queue().topPriority()); if(!visitorProxy.visit(this)) break; } // build a dense remapping const auto & nodeUfd = callback.edgeContractionGraph().nodeUfd(); std::unordered_map<uint64_t,uint64_t> representativeLabeling; nodeUfd.representativeLabeling(representativeLabeling); auto ccIndex = [&](const uint64_t node){ return representativeLabeling[nodeUfd.find(node)]; }; // submodels const auto nSubModels = nodeUfd.numberOfSets(); std::vector<SubGraph *> subGraphs(nSubModels, nullptr); std::vector<MulticutSubObjective *> subObjectives(nSubModels, nullptr); std::vector<MulticutSubNodeLabels *> subLabels(nSubModels, nullptr); std::vector<uint64_t> subModelSize(nSubModels, 0); visitorProxy.printLog(nifty::logging::LogLevel::INFO, std::string("nSubModels") + std::to_string(nSubModels)); //std::cout<<"a\n"; std::vector< std::unordered_map<uint64_t, uint64_t> > nodeToSubNodeVec(nSubModels); for(const auto node : graph_.nodes()){ const auto subgraphId = ccIndex(node); auto & nodeToSubNode = nodeToSubNodeVec[subgraphId]; const auto subVarId = nodeToSubNode.size(); nodeToSubNode[node] = subVarId; } //std::cout<<"b\n"; // submodel size for(const auto node : graph_.nodes()){ ++subModelSize[ccIndex(node)]; } //std::cout<<"c\n"; // allocs model and graphs for(auto i=0; i<nSubModels; ++i){ subGraphs[i] = new SubGraph(subModelSize[i]); subObjectives[i] = new MulticutSubObjective(*subGraphs[i]); subLabels[i] = new MulticutSubNodeLabels(*subGraphs[i]); } //std::cout<<"d\n"; // edges for(const auto edge : graph_.edges()){ const auto u = graph_.u(edge); const auto v = graph_.v(edge); const auto ccU = ccIndex(u); const auto ccV = ccIndex(v); if(ccU == ccV){ const auto & nodeToSubNode = nodeToSubNodeVec[ccU]; const auto dU = nodeToSubNode.find(u)->second; const auto dV = nodeToSubNode.find(v)->second; //std::cout<<weights_.size()<<" ws\n"; const auto w = weights_[edge]; const auto edgeId = subGraphs[ccU]->insertEdge(dU, dV); subObjectives[ccU]->weights().insertedEdges(edgeId); subObjectives[ccU]->weights()[edgeId] = w; isDirtyEdge_[edge] = false; } else{ isDirtyEdge_[edge] = true; } } nifty::ufd::Ufd<uint64_t> ufd(graph_.nodeIdUpperBound()+1); visitorProxy.clearLogNames(); visitorProxy.addLogNames({std::string("#subSize")}); // allocs optimizers and optimize for(auto i=0; i<nSubModels; ++i){ visitorProxy.setLogValue(0, subGraphs[i]->numberOfNodes()); visitorProxy.visit(this); auto solver = settings_.multicutFactory->create(*subObjectives[i]); solver->optimize(*subLabels[i],nullptr); delete solver; } //std::cout<<"merge\n"; // merge for(const auto edge : graph_.edges()){ const auto u = graph_.u(edge); const auto v = graph_.v(edge); const auto ccU = ccIndex(u); const auto ccV = ccIndex(v); if(ccU == ccV){ const auto & nodeToSubNode = nodeToSubNodeVec[ccU]; const auto dU = nodeToSubNode.find(u)->second; const auto dV = nodeToSubNode.find(v)->second; if((*subLabels[ccU])[dU] == (*subLabels[ccU])[dU]){ ufd.merge(u, v); } } } std::cout<<"eval\n"; for(const auto node : graph_.nodes()){ nodeLabels[node] = ufd.find(node); } currentBestEnergy_ = objective_.evalNodeLabels(nodeLabels); // de-allocs for(auto i=0; i<nSubModels; ++i){ //delete subSolvers[i]; delete subLabels[i]; delete subObjectives[i]; delete subGraphs[i]; } } template<class OBJECTIVE> void Cgc<OBJECTIVE>:: glueAndCutPhase( VisitorProxyType & visitorProxy ){ currentBestEnergy_ = objective_.evalNodeLabels(*currentBest_); visitorProxy.clearLogNames(); visitorProxy.addLogNames({std::string("Sweep"),std::string("be")}); // one anchor for all ``cc-edges`` typedef std::pair<uint64_t, uint64_t> LabelPair; struct LabelPairHash{ public: std::size_t operator()(const std::pair<uint64_t, uint64_t> & x) const { std::size_t h = std::hash<uint64_t>()(x.first) ^ std::hash<uint64_t>()(x.second); return h; } }; typedef std::unordered_map<LabelPair, uint64_t, LabelPairHash> LabelPairToAnchor; LabelPairToAnchor labelPairToAnchorEdge; // the node labeling as reference auto & nodeLabels = *currentBest_; // initially everything is marked as dirty auto continueSeach = true; auto sweep = 0; while(continueSeach){ continueSeach = false; labelPairToAnchorEdge.clear(); for(const auto edge : graph_.edges()){ const auto u = graph_.u(edge); const auto v = graph_.v(edge); const auto lu = nodeLabels[std::min(u,v)]; const auto lv = nodeLabels[std::max(u,v)]; if(lu != lv){ const auto labelPair = LabelPair(lu, lv); labelPairToAnchorEdge.insert(std::make_pair(labelPair, edge)); } } for(const auto kv : labelPairToAnchorEdge){ const auto edge = kv.second; if(isDirtyEdge_[edge]){ const auto u = graph_.u(edge); const auto v = graph_.v(edge); const auto lu = nodeLabels[u]; const auto lv = nodeLabels[v]; // if the labels are still different if(lu != lv){ const auto ret = submodel_.optimize2(nodeLabels, u, v); if(ret.improvment){ continueSeach = true; currentBestEnergy_ -= ret.improvedBy; visitorProxy.setLogValue(0, sweep); visitorProxy.setLogValue(1, currentBestEnergy_); if(!visitorProxy.visit(this)){ continueSeach = false; break; } } } } } ++sweep; } } template<class OBJECTIVE> void Cgc<OBJECTIVE>:: optimize( NodeLabelsType & nodeLabels, VisitorBaseType * visitor ){ VisitorProxyType visitorProxy(visitor); //visitorProxy.addLogNames({"violatedConstraints"}); currentBest_ = &nodeLabels; currentBestEnergy_ = objective_.evalNodeLabels(nodeLabels); visitorProxy.begin(this); // the main workhorses // cut phase if(settings_.doCutPhase){ visitorProxy.printLog(nifty::logging::LogLevel::INFO, "Start Cut Phase:"); if(settings_.doBetterCutPhase) this->betterCutPhase(visitorProxy); else this->cutPhase(visitorProxy); } // glue phase if(settings_.doGlueAndCutPhase){ visitorProxy.printLog(nifty::logging::LogLevel::INFO, "Start Glue & Cut Phase:"); this->glueAndCutPhase(visitorProxy); } visitorProxy.end(this); } template<class OBJECTIVE> const typename Cgc<OBJECTIVE>::ObjectiveType & Cgc<OBJECTIVE>:: objective()const{ return objective_; } } // namespace nifty::graph::opt::multicut } // namespace nifty::graph::opt } // namespace nifty::graph } // namespace nifty
37.682318
156
0.531124
DerThorsten
81ccef7c6e9b7ed20ba190aed89b84d2aaf2ed9c
2,153
cpp
C++
src/MC_DDH_Create.cpp
ekhidbor/FUMe
de50357efcb6dbfd0114802bc72ad316daca0ce3
[ "CC0-1.0" ]
null
null
null
src/MC_DDH_Create.cpp
ekhidbor/FUMe
de50357efcb6dbfd0114802bc72ad316daca0ce3
[ "CC0-1.0" ]
null
null
null
src/MC_DDH_Create.cpp
ekhidbor/FUMe
de50357efcb6dbfd0114802bc72ad316daca0ce3
[ "CC0-1.0" ]
null
null
null
/** * This file is a part of the FUMe project. * * To the extent possible under law, the person who associated CC0 with * FUMe has waived all copyright and related or neighboring rights * to FUMe. * * You should have received a copy of the CC0 legalcode along with this * work. If not, see http://creativecommons.org/publicdomain/zero/1.0/. */ // std // local public #include "mcstatus.h" #include "mc3media.h" // local private #include "fume/library_context.h" #include "fume/file_object.h" using fume::g_context; using fume::file_object; MC_STATUS MC_DDH_Create( const char* FilePath, const char* FileSetID, int TemplateFileID, int* DirMsgIDPtr ) { MC_STATUS ret = MC_CANNOT_COMPLY; try { if( g_context != nullptr && DirMsgIDPtr != nullptr ) { file_object* template_dict = dynamic_cast<file_object*>( g_context->get_object( TemplateFileID ) ); // Create DICOMDIR object if the caller didn't specify a template ID // or they did and it's a valid file object if( TemplateFileID == 0 || template_dict != nullptr ) { const int dicomdir_id = g_context->create_dicomdir_object( FilePath, FileSetID, template_dict ); if( dicomdir_id > 0 ) { *DirMsgIDPtr = dicomdir_id; ret = MC_NORMAL_COMPLETION; } else { ret = static_cast<MC_STATUS>( -dicomdir_id ); } } else { ret = MC_INVALID_MESSAGE_ID; } } else if( g_context == nullptr ) { ret = MC_LIBRARY_NOT_INITIALIZED; } else { ret = MC_NULL_POINTER_PARM; } } catch( ... ) { ret = MC_SYSTEM_ERROR; } return ret; }
27.602564
86
0.498374
ekhidbor
81cfe417f98681829e92f49534953fdfdcf228f2
40,620
cpp
C++
Samples/CaseStudies/NBody/NBodyGravityAmp.cpp
AdeMiller/CppAmp
2f2c222ec796968dcdc43ea1d84c825169693331
[ "MS-PL" ]
null
null
null
Samples/CaseStudies/NBody/NBodyGravityAmp.cpp
AdeMiller/CppAmp
2f2c222ec796968dcdc43ea1d84c825169693331
[ "MS-PL" ]
null
null
null
Samples/CaseStudies/NBody/NBodyGravityAmp.cpp
AdeMiller/CppAmp
2f2c222ec796968dcdc43ea1d84c825169693331
[ "MS-PL" ]
null
null
null
//=============================================================================== // // Microsoft Press // C++ AMP: Accelerated Massive Parallelism with Microsoft Visual C++ // //=============================================================================== // Copyright (c) 2012-2013 Ade Miller & Kate Gregory. All rights reserved. // This code released under the terms of the // Microsoft Public License (Ms-PL), http://ampbook.codeplex.com/license. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. //=============================================================================== #include <memory> #include <string> #include <deque> #include <numeric> #include <future> #include <d3dx11.h> #include <commdlg.h> #include <atlbase.h> #include "DXUT.h" #include "DXUTgui.h" #include "SDKmisc.h" #include "DXUTcamera.h" #include "DXUTsettingsdlg.h" #include "NBodyAmp.h" #include "NBodyAmpSimple.h" #include "NBodyAmpTiled.h" #include "NBodyAmpMultiTiled.h" #include "resource.h" enum ComputeType { kSingleSimple = 0, kSingleTile64, kSingleTile128, kSingleTile256, kSingleTile512, kMultiTile = 5, kMultiTile64 = 5, kMultiTile128, kMultiTile256, kMultiTile512 }; //-------------------------------------------------------------------------------------- // Global constants. //-------------------------------------------------------------------------------------- const float g_softeningSquared = 0.0000015625f; const float g_dampingFactor = 0.9995f; const float g_particleMass = ((6.67300e-11f*10000.0f)*10000.0f*10000.0f); const float g_deltaTime = 0.1f; const int g_maxParticles = (57*1024); // Maximum number of particles in the n-body simulation. const int g_particleNumStepSize = 512; // Number of particles added for each slider tick, cannot be less than the max tile size. const float g_Spread = 400.0f; // Separation between the two clusters. //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- CDXUTDialogResourceManager g_dialogResourceManager; // manager for shared resources of dialogs CModelViewerCamera g_camera; // A model viewing camera CD3DSettingsDlg g_d3dSettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // dialog for standard controls CDXUTDialog g_sampleUI; // dialog for sample specific controls std::unique_ptr<CDXUTTextHelper> g_pTxtHelper; std::deque<float> g_FpsStatistics; CComPtr<ID3D11VertexShader> g_pRenderParticlesVS; CComPtr<ID3D11GeometryShader> g_pRenderParticlesGS; CComPtr<ID3D11PixelShader> g_pRenderParticlesPS; CComPtr<ID3D11SamplerState> g_pSampleStateLinear; CComPtr<ID3D11BlendState> g_pBlendingStateParticle; CComPtr<ID3D11DepthStencilState> g_pDepthStencilState; CComPtr<ID3D11Buffer> g_pParticlePosOld; CComPtr<ID3D11Buffer> g_pParticlePosNew; CComPtr<ID3D11ShaderResourceView> g_pParticlePosRvOld; CComPtr<ID3D11ShaderResourceView> g_pParticlePosRvNew; CComPtr<ID3D11UnorderedAccessView> g_pParticlePosUavOld; CComPtr<ID3D11UnorderedAccessView> g_pParticlePosUavNew; CComPtr<ID3D11Buffer> g_pParticleBuffer; CComPtr<ID3D11InputLayout> g_pParticleVertexLayout; CComPtr<ID3D11Buffer> g_pConstantBuffer; CComPtr<ID3D11ShaderResourceView> g_pShaderResView; //-------------------------------------------------------------------------------------- // Nbody functionality //-------------------------------------------------------------------------------------- #if !(defined(DEBUG) || defined(_DEBUG)) int g_numParticles = (20 * 1024); // The current number of particles in the n-body simulation #else int g_numParticles = g_particleNumStepSize; #endif ComputeType g_eComputeType = kSingleSimple; // Default integrator compute type std::shared_ptr<INBodyAmp> g_pNBody; // The current integrator // Particle data structures. std::vector<std::shared_ptr<TaskData>> g_deviceData; // Particle colours. D3DXCOLOR g_particleColor; std::vector<D3DCOLOR> g_particleColors; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_RESETPARTICLES 5 #define IDC_COMPUTETYPECOMBO 6 #define IDC_NBODIES_LABEL 7 #define IDC_NBODIES_SLIDER 8 #define IDC_NBODIES_TEXT 9 #define IDC_FPS_TEXT 10 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CorrectNumberOfParticles(); inline void SetBodyText(); bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ); void CALLBACK OnD3D11DestroyDevice( void* pUserContext ); void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); void InitApp(); void RenderText(); //-------------------------------------------------------------------------------------- // Helper function to compile an hlsl shader from file, // its binary compiled code is returned //-------------------------------------------------------------------------------------- HRESULT CompileShaderFromFile( WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) { HRESULT hr = S_OK; WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) ); CComPtr<ID3DBlob> pErrorBlob = nullptr; D3DX11CompileFromFile(str, nullptr, nullptr, szEntryPoint, szShaderModel, D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_DEBUG, 0, nullptr, ppBlobOut, &pErrorBlob, nullptr); if ( FAILED(hr) ) { if (pErrorBlob != nullptr) OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() ); } return hr; } //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // NOTE: This application leaks memory on shutdown due DLL unload ordering issues. // // {619} normal block at 0x00000011ADD99E10, 152 bytes long. // Data: < > 10 9F D9 AD 11 00 00 00 E0 B6 CE AF 11 00 00 00 // // See the C++ AMP blog for further details. // Enable run-time memory check for debug builds. #if defined(DEBUG) || defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); InitApp(); //DXUTInit( true, true, L"-forceref" ); // Force Create a ref device so that feature level D3D_FEATURE_LEVEL_11_0 is guaranteed DXUTInit( true, true ); // Use this line instead to try to Create a hardware device DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"C++ AMP N-Body Simulation Demo" ); DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, 1280, 800 ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_d3dSettingsDlg.Init( &g_dialogResourceManager ); g_HUD.Init( &g_dialogResourceManager ); g_sampleUI.Init( &g_dialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int y = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, y, 170, 23 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, y += 26, 170, 23, VK_F2 ); g_HUD.AddButton( IDC_RESETPARTICLES, L"Reset particles", 0, y += 26, 170, 22, VK_F2 ); WCHAR szTemp[256]; swprintf_s( szTemp, L"Bodies: %d", g_numParticles ); g_HUD.AddStatic( IDC_NBODIES_LABEL, szTemp, -20, y += 34, 125, 22 ); g_HUD.AddSlider( IDC_NBODIES_SLIDER, -20, y += 34, 170, 22, 1, g_maxParticles/g_particleNumStepSize ); CDXUTComboBox* pComboBox = nullptr; g_HUD.AddComboBox( IDC_COMPUTETYPECOMBO, -133, y += 34, 300, 26, L'G', false, &pComboBox ); // The ordering of these names must match the FrameProcessorType enumeration. std::wstring processorNames[] = { std::wstring(L"C++ AMP Simple Model "), // kCpuSingle std::wstring(L"C++ AMP Tiled Model 64 "), std::wstring(L"C++ AMP Tiled Model 128 "), std::wstring(L"C++ AMP Tiled Model 256 "), std::wstring(L"C++ AMP Tiled Model 512 "), // kSingleTile512 std::wstring(L"C++ AMP Tiled Model 64: xx GPUs"), // kMultiTile64 std::wstring(L"C++ AMP Tiled Model 128:xx GPUs"), std::wstring(L"C++ AMP Tiled Model 256:xx GPUs"), std::wstring(L"C++ AMP Tiled Model 512:xx GPUs") // kMultiTile512 }; WCHAR buf[3]; if (_itow_s(static_cast<int>(AmpUtils::GetGpuAccelerators().size()), buf, 3, 10) == 0) for (int i = kMultiTile64; i <= kMultiTile512; ++i) processorNames[i].replace(24, 2, buf); std::wstring path = accelerator(accelerator::default_accelerator).device_path; // If there is a GPU accelerator then use it. // Otherwise add a REF accelerator and display warning. for (int i = kSingleSimple; i <= kSingleTile512; ++i) pComboBox->AddItem(processorNames[i].c_str(), nullptr); g_eComputeType = kSingleTile256; // If there us more than one GPU then allow the user to use them together. if (AmpUtils::GetGpuAccelerators().size() >= 2) { for (int i = kMultiTile64; i <= kMultiTile512; ++i) pComboBox->AddItem(processorNames[i].c_str(), nullptr); g_eComputeType = kMultiTile256; } g_HUD.GetComboBox( IDC_COMPUTETYPECOMBO )->SetSelectedByData((void*)g_eComputeType); pComboBox->SetSelectedByIndex(g_eComputeType); g_HUD.GetSlider( IDC_NBODIES_SLIDER )->SetValue( (g_numParticles / g_particleNumStepSize) ); g_particleColors.resize(kMultiTile512 + 1); g_particleColors[kSingleSimple] = D3DXCOLOR( 0.05f, 1.0f, 0.05f, 1.0f ); g_particleColors[kSingleTile64] = D3DXCOLOR( 0.05f, 1.0f, 0.05f, 1.0f ); g_particleColors[kSingleTile128] = D3DXCOLOR( 0.05f, 1.0f, 0.05f, 1.0f ); g_particleColors[kSingleTile256] = D3DXCOLOR( 0.05f, 1.0f, 0.05f, 1.0f ); g_particleColors[kSingleTile512] = D3DXCOLOR( 0.05f, 1.0f, 0.05f, 1.0f ); g_particleColors[kMultiTile64] = D3DXCOLOR( 0.05f, 0.05f, 1.0f, 1.0f ); g_particleColors[kMultiTile128] = D3DXCOLOR( 0.05f, 0.05f, 1.0f, 1.0f ); g_particleColors[kMultiTile256] = D3DXCOLOR( 0.05f, 0.05f, 1.0f, 1.0f ); g_particleColors[kMultiTile512] = D3DXCOLOR( 0.05f, 0.05f, 1.0f, 1.0f ); g_particleColor = g_particleColors[g_eComputeType]; g_sampleUI.SetCallback( OnGUIEvent ); #if (defined(DEBUG) || defined(_DEBUG)) if (AmpUtils::GetGpuAccelerators().empty()) MessageBox(DXUTGetHWND(), L"No C++ AMP GPU hardware accelerator detected,\nusing the REF or WARP accelerator.\n\nTo see better performance run on C++ AMP\nenabled hardware.", L"No C++ AMP Hardware Accelerator Detected", MB_ICONEXCLAMATION); #endif #ifdef FORCE_WARP // Force use of the Warp accelerator, even if a better GPU exists. For testing only. accelerator::set_default(accelerator::direct3d_warp); OutputDebugStringW(L"Forcing application to use the WARP accelerator"); #endif } //-------------------------------------------------------------------------------------- // Create particle buffers for use during rendering. //-------------------------------------------------------------------------------------- HRESULT CreateParticleBuffer( ID3D11Device* pd3dDevice ) { HRESULT hr = S_OK; D3D11_BUFFER_DESC bufferDesc = { g_maxParticles * sizeof( ParticleVertex ), D3D11_USAGE_DEFAULT, D3D11_BIND_VERTEX_BUFFER, 0, 0 }; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData, sizeof( D3D11_SUBRESOURCE_DATA ) ); std::vector<ParticleVertex> vertices(g_maxParticles); std::for_each(vertices.begin(), vertices.end(), [](ParticleVertex& v){ v.color = D3DXCOLOR( 1, 1, 0.2f, 1 ); }); resourceData.pSysMem = &vertices[0]; g_pParticleBuffer = nullptr; V_RETURN( pd3dDevice->CreateBuffer( &bufferDesc, &resourceData, &g_pParticleBuffer ) ); return hr; } //-------------------------------------------------------------------------------------- // Load particles. Two clusters set to collide. //-------------------------------------------------------------------------------------- void LoadParticles() { const float centerSpread = g_Spread * 0.50f; // Create particles in CPU memory. ParticlesCpu particles(g_maxParticles); for (int i = 0; i < g_maxParticles; i += g_particleNumStepSize) { LoadClusterParticles(particles, i, (g_particleNumStepSize / 2), float_3(centerSpread, 0.0f, 0.0f), float_3( 0, 0, -20), g_Spread); LoadClusterParticles(particles, (i + g_particleNumStepSize / 2), ((g_particleNumStepSize + 1) / 2), float_3(-centerSpread, 0.0f, 0.0f), float_3( 0, 0, 20), g_Spread); } // Copy particles to GPU memory. index<1> begin(0); extent<1> end(g_maxParticles); for (size_t i = 0; i < g_deviceData.size(); ++i) { array_view<float_3, 1> posView = g_deviceData[i]->DataOld->pos.section(index<1>(begin), extent<1>(end)); copy(particles.pos.begin(), posView); array_view<float_3, 1> velView = g_deviceData[i]->DataOld->vel.section(index<1>(begin), extent<1>(end)); copy(particles.vel.begin(), velView); } } //-------------------------------------------------------------------------------------- // Integrator class factory. //-------------------------------------------------------------------------------------- std::shared_ptr<INBodyAmp> NBodyFactory(ComputeType type) { switch (type) { case kSingleSimple: return std::make_shared<NBodyAmpSimple>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass); break; case kSingleTile64: return std::make_shared<NBodyAmpTiled<64>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass); break; case kSingleTile128: return std::make_shared<NBodyAmpTiled<128>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass); break; case kSingleTile256: return std::make_shared<NBodyAmpTiled<256>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass); break; case kSingleTile512: return std::make_shared<NBodyAmpTiled<512>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass); break; case kMultiTile64: return std::make_shared<NBodyAmpMultiTiled<64>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass, g_maxParticles); break; case kMultiTile128: return std::make_shared<NBodyAmpMultiTiled<128>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass, g_maxParticles); break; case kMultiTile256: return std::make_shared<NBodyAmpMultiTiled<256>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass, g_maxParticles); break; case kMultiTile512: return std::make_shared<NBodyAmpMultiTiled<512>>(g_softeningSquared, g_dampingFactor, g_deltaTime, g_particleMass, g_maxParticles); break; default: assert(false); return nullptr; break; } } //-------------------------------------------------------------------------------------- // Create buffers and hook them up to DirectX. //-------------------------------------------------------------------------------------- HRESULT CreateParticlePosBuffer(ID3D11Device* pd3dDevice) { HRESULT hr = S_OK; accelerator_view renderView = concurrency::direct3d::create_accelerator_view(reinterpret_cast<IUnknown*>(pd3dDevice)); g_deviceData = CreateTasks(g_maxParticles, renderView); LoadParticles(); g_pParticlePosOld = nullptr; g_pParticlePosNew = nullptr; // Particles from GPU zero are the ones synced with the graphics buffers. // Attach AMP array of positions to D3D buffer. hr = concurrency::direct3d::get_buffer( g_deviceData[0]->DataOld->pos)->QueryInterface(__uuidof(ID3D11Buffer), reinterpret_cast<LPVOID*>(&g_pParticlePosOld)); V_RETURN(hr); hr = concurrency::direct3d::get_buffer( g_deviceData[0]->DataNew->pos)->QueryInterface(__uuidof(ID3D11Buffer), reinterpret_cast<LPVOID*>(&g_pParticlePosNew)); V_RETURN(hr) D3D11_SHADER_RESOURCE_VIEW_DESC resourceDesc; ZeroMemory(&resourceDesc, sizeof(resourceDesc)); resourceDesc.Format = DXGI_FORMAT_R32_TYPELESS; resourceDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX; resourceDesc.BufferEx.FirstElement = 0; resourceDesc.BufferEx.NumElements = (g_maxParticles * sizeof(float_3)) / sizeof(float); resourceDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW; g_pParticlePosRvOld = nullptr; g_pParticlePosRvNew = nullptr; hr = pd3dDevice->CreateShaderResourceView(g_pParticlePosOld, &resourceDesc, &g_pParticlePosRvOld); V_RETURN(hr); hr = pd3dDevice->CreateShaderResourceView(g_pParticlePosNew, &resourceDesc, &g_pParticlePosRvNew); V_RETURN(hr); g_pParticlePosUavOld = nullptr; g_pParticlePosUavNew = nullptr; D3D11_UNORDERED_ACCESS_VIEW_DESC viewDesc; ZeroMemory(&viewDesc, sizeof(D3D11_UNORDERED_ACCESS_VIEW_DESC)); viewDesc.Format = DXGI_FORMAT_R32_TYPELESS; viewDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; viewDesc.Buffer.FirstElement = 0; viewDesc.Buffer.NumElements = (g_maxParticles * sizeof(float_3)) / sizeof(float); viewDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW; hr = pd3dDevice->CreateUnorderedAccessView(g_pParticlePosOld, &viewDesc, &g_pParticlePosUavOld); V_RETURN(hr); hr = pd3dDevice->CreateUnorderedAccessView(g_pParticlePosNew, &viewDesc, &g_pParticlePosUavNew); V_RETURN(hr); return hr; } //-------------------------------------------------------------------------------------- // Create render buffer. //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { assert( pDeviceSettings->ver == DXUT_D3D11_DEVICE ); // Disable vsync pDeviceSettings->d3d11.SyncInterval = 0; g_d3dSettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetEnabled( false ); // For the first device created if it is a REF device, optionally display a warning dialog box static bool s_IsFirstTime = true; if( s_IsFirstTime ) { s_IsFirstTime = false; if( ( DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) || ( DXUT_D3D11_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) ) { DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } } return true; } //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove(double fTime, float fElapsedTime, void* pUserContext) { g_pNBody->Integrate(g_deviceData, g_numParticles); std::for_each(g_deviceData.begin(), g_deviceData.end(), [](std::shared_ptr<TaskData>& t) { std::swap(t->DataOld, t->DataNew); }); std::swap(g_pParticlePosOld, g_pParticlePosNew); std::swap(g_pParticlePosRvOld, g_pParticlePosRvNew); std::swap(g_pParticlePosUavOld, g_pParticlePosUavNew); // Update the camera's position based on user input g_camera.FrameMove(fElapsedTime); } //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_dialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_d3dSettingsDlg.IsActive() ) { g_d3dSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_sampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all windows messages to camera so it can respond to user input g_camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void SetBodyText(); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_CHANGEDEVICE: g_d3dSettingsDlg.SetActive( !g_d3dSettingsDlg.IsActive() ); break; case IDC_RESETPARTICLES: LoadParticles(); break; case IDC_COMPUTETYPECOMBO: { CDXUTComboBox* pComboBox = static_cast<CDXUTComboBox*>(pControl); g_eComputeType = static_cast<ComputeType>(pComboBox->GetSelectedIndex()); g_particleColor = g_particleColors[g_eComputeType]; g_pNBody = NBodyFactory(g_eComputeType); CorrectNumberOfParticles(); SetBodyText(); g_FpsStatistics.clear(); } break; case IDC_NBODIES_SLIDER: { CDXUTSlider* pSlider = static_cast<CDXUTSlider*>(pControl); g_numParticles = pSlider->GetValue() * g_particleNumStepSize; CorrectNumberOfParticles(); SetBodyText(); g_FpsStatistics.clear(); } break; } } // For the multi-accelerator integrator there must be at least one tile of particles per GPU. void CorrectNumberOfParticles() { const int minParticles = static_cast<int>(g_deviceData.size() * g_pNBody->TileSize()); if ((g_eComputeType >= kMultiTile) && (g_numParticles < minParticles)) { g_numParticles = minParticles; g_HUD.GetSlider( IDC_NBODIES_SLIDER )->SetValue( g_numParticles / g_particleNumStepSize ); } } void SetBodyText() { WCHAR szTemp[256]; swprintf_s( szTemp, L"Bodies: %d", g_numParticles ); g_HUD.GetStatic( IDC_NBODIES_LABEL )->SetText( szTemp ); } bool CALLBACK IsD3D11DeviceAcceptable(const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext) { // reject any device which doesn't support CS4x return (DeviceInfo->ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x != false); } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to Create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnD3D11DestroyDevice callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice(ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext) { HRESULT hr = S_OK; D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS ho; V_RETURN( pd3dDevice->CheckFeatureSupport( D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho) ) ); CComPtr<ID3D11DeviceContext> pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_dialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_d3dSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = std::unique_ptr<CDXUTTextHelper>(new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_dialogResourceManager, 15 )); CComPtr<ID3DBlob> pBlobRenderParticlesVS; CComPtr<ID3DBlob> pBlobRenderParticlesGS; CComPtr<ID3DBlob> pBlobRenderParticlesPS; // Create the shaders V_RETURN( CompileShaderFromFile( L"ParticleDrawGpu.hlsl", "VSParticleDraw", "vs_4_0", &pBlobRenderParticlesVS) ); V_RETURN( CompileShaderFromFile( L"ParticleDrawGpu.hlsl", "GSParticleDraw", "gs_4_0", &pBlobRenderParticlesGS) ); V_RETURN( CompileShaderFromFile( L"ParticleDrawGpu.hlsl", "PSParticleDraw", "ps_4_0", &pBlobRenderParticlesPS) ); g_pRenderParticlesVS = nullptr; g_pRenderParticlesGS = nullptr; g_pRenderParticlesPS = nullptr; V_RETURN( pd3dDevice->CreateVertexShader( pBlobRenderParticlesVS->GetBufferPointer(), pBlobRenderParticlesVS->GetBufferSize(), nullptr, &g_pRenderParticlesVS ) ); V_RETURN( pd3dDevice->CreateGeometryShader( pBlobRenderParticlesGS->GetBufferPointer(), pBlobRenderParticlesGS->GetBufferSize(), nullptr, &g_pRenderParticlesGS ) ); V_RETURN( pd3dDevice->CreatePixelShader( pBlobRenderParticlesPS->GetBufferPointer(), pBlobRenderParticlesPS->GetBufferSize(), nullptr, &g_pRenderParticlesPS ) ); // Create our vertex input layout const D3D11_INPUT_ELEMENT_DESC layout[] = { { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; g_pParticleVertexLayout = nullptr; V_RETURN( pd3dDevice->CreateInputLayout( layout, sizeof( layout ) / sizeof( layout[0] ), pBlobRenderParticlesVS->GetBufferPointer(), pBlobRenderParticlesVS->GetBufferSize(), &g_pParticleVertexLayout ) ); // Create NBody object g_pNBody = NBodyFactory(g_eComputeType); V_RETURN(CreateParticleBuffer(pd3dDevice)); V_RETURN(CreateParticlePosBuffer(pd3dDevice)); // Setup constant buffer D3D11_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; bufferDesc.ByteWidth = sizeof( ResourceData ); g_pConstantBuffer = nullptr; V_RETURN( pd3dDevice->CreateBuffer(&bufferDesc, nullptr, &g_pConstantBuffer)); // Load the Particle Texture WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\Particle.dds" ) ); g_pShaderResView = nullptr; V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3dDevice, str, nullptr, nullptr, &g_pShaderResView, nullptr ) ); D3D11_SAMPLER_DESC samplerDesc; ZeroMemory( &samplerDesc, sizeof(samplerDesc) ); samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; g_pSampleStateLinear = nullptr; V_RETURN(pd3dDevice->CreateSamplerState(&samplerDesc, &g_pSampleStateLinear)); D3D11_BLEND_DESC blendStateDesc; ZeroMemory( &blendStateDesc, sizeof(blendStateDesc) ); blendStateDesc.RenderTarget[0].BlendEnable = TRUE; blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; g_pBlendingStateParticle = nullptr; V_RETURN(pd3dDevice->CreateBlendState( &blendStateDesc, &g_pBlendingStateParticle)); D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory( &depthStencilDesc, sizeof(depthStencilDesc) ); depthStencilDesc.DepthEnable = false; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; g_pDepthStencilState = nullptr; pd3dDevice->CreateDepthStencilState(&depthStencilDesc, &g_pDepthStencilState); // Setup the camera's view parameters D3DXVECTOR3 vecEye( -g_Spread * 2, g_Spread * 4, -g_Spread * 3 ); D3DXVECTOR3 vecAt ( 0.0f, 0.0f, 0.0f ); g_camera.SetViewParams( &vecEye, &vecAt ); return S_OK; } HRESULT CALLBACK OnD3D11ResizedSwapChain(ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext) { HRESULT hr = S_OK; V_RETURN( g_dialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); V_RETURN( g_d3dSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); // Setup the camera's projection parameters float aspect = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_camera.SetProjParams( D3DX_PI / 4, aspect, 10.0f, 500000.0f ); g_camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_camera.SetButtonMasks( 0, MOUSE_WHEEL, MOUSE_LEFT_BUTTON | MOUSE_MIDDLE_BUTTON | MOUSE_RIGHT_BUTTON ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_sampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); g_sampleUI.SetSize( 170, 300 ); return hr; } void CALLBACK OnD3D11ReleasingSwapChain(void* pUserContext) { g_dialogResourceManager.OnD3D11ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Create particle buffers for use during rendering. //-------------------------------------------------------------------------------------- void RenderText() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos( 2, 0 ); g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( false ) ); g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() ); g_pTxtHelper->SetInsertionPos( 20, 60 ); g_pTxtHelper->DrawFormattedTextLine( L"Bodies: %d", g_numParticles ); g_FpsStatistics.push_front(DXUTGetFPS()); if (g_FpsStatistics.size() > 10) g_FpsStatistics.pop_back(); const float fps = accumulate(g_FpsStatistics.begin(), g_FpsStatistics.end(), 0.0f) / g_FpsStatistics.size(); // Estimate the number of FLOPs based on 20 FLOPs per particle-particle interaction. g_pTxtHelper->DrawFormattedTextLine( L"FPS: %.2f", fps ); const float gflops = (g_numParticles / 1000.0f) * (g_numParticles / 1000.0f) * fps * 20 / 1000.0f; g_pTxtHelper->DrawFormattedTextLine( L"GFlops: %.2f ", gflops ); g_pTxtHelper->End(); } bool RenderParticles(ID3D11DeviceContext* pd3dImmediateContext, D3DXMATRIX& view, D3DXMATRIX& projection) { CComPtr<ID3D11BlendState> pBlendState0; CComPtr<ID3D11DepthStencilState> pDepthStencilState0; UINT SampleMask0, StencilRef0; D3DXCOLOR BlendFactor0; pd3dImmediateContext->OMGetBlendState( &pBlendState0, &BlendFactor0.r, &SampleMask0 ); pd3dImmediateContext->OMGetDepthStencilState( &pDepthStencilState0, &StencilRef0 ); pd3dImmediateContext->VSSetShader( g_pRenderParticlesVS, nullptr, 0 ); pd3dImmediateContext->GSSetShader( g_pRenderParticlesGS, nullptr, 0 ); pd3dImmediateContext->PSSetShader( g_pRenderParticlesPS, nullptr, 0 ); pd3dImmediateContext->IASetInputLayout( g_pParticleVertexLayout ); // Set IA parameters, don't need to pass arrays to IASetVertexBuffers as there is only one buffer. const UINT stride = sizeof(ParticleVertex); const UINT offset = 0; pd3dImmediateContext->IASetVertexBuffers(0, 1, &g_pParticleBuffer.p, &stride, &offset); pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST ); // Don't need to pass array to VSSetShaderResources as there is only one buffer. pd3dImmediateContext->VSSetShaderResources(0, 1, &g_pParticlePosRvOld.p); D3D11_MAPPED_SUBRESOURCE mappedResource; pd3dImmediateContext->Map( g_pConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); ResourceData* pCBGS = static_cast<ResourceData*>(mappedResource.pData); D3DXMatrixMultiply( &pCBGS->worldViewProj, &view, &projection ); D3DXMatrixInverse( &pCBGS->inverseView, nullptr, &view ); pCBGS->color = g_particleColor; pd3dImmediateContext->Unmap( g_pConstantBuffer, 0 ); pd3dImmediateContext->GSSetConstantBuffers( 0, 1, &g_pConstantBuffer.p); pd3dImmediateContext->PSSetShaderResources( 0, 1, &g_pShaderResView.p); pd3dImmediateContext->PSSetSamplers( 0, 1, &g_pSampleStateLinear.p); pd3dImmediateContext->OMSetBlendState( g_pBlendingStateParticle, D3DXCOLOR( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF ); pd3dImmediateContext->OMSetDepthStencilState( g_pDepthStencilState, 0 ); pd3dImmediateContext->Draw(g_numParticles, 0); ID3D11ShaderResourceView* ppSRVnullptr[1] = { nullptr }; pd3dImmediateContext->VSSetShaderResources(0, 1, ppSRVnullptr); pd3dImmediateContext->PSSetShaderResources( 0, 1, ppSRVnullptr ); pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 ); pd3dImmediateContext->OMSetBlendState( pBlendState0, &BlendFactor0.r, SampleMask0 ); pd3dImmediateContext->OMSetDepthStencilState( pDepthStencilState0, StencilRef0 ); return true; } void CALLBACK OnD3D11FrameRender(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext) { // If the settings dialog is being shown, then render it instead of rendering the app's scene if (g_d3dSettingsDlg.IsActive()) { g_d3dSettingsDlg.OnRender( fElapsedTime ); return; } const float clearColor[4] = { 0.0, 0.0, 0.0, 0.0 }; ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView(); pd3dImmediateContext->ClearRenderTargetView( pRTV, clearColor ); ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView(); pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 ); D3DXMATRIX view; D3DXMATRIX projection; // Get the projection & view matrix from the camera class projection = *g_camera.GetProjMatrix(); view = *g_camera.GetViewMatrix(); // Render the particles RenderParticles( pd3dImmediateContext, view, projection ); g_HUD.OnRender( fElapsedTime ); g_sampleUI.OnRender( fElapsedTime ); RenderText(); } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnD3D11CreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11DestroyDevice(void* pUserContext) { g_dialogResourceManager.OnD3D11DestroyDevice(); g_d3dSettingsDlg.OnD3D11DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); }
45.183537
184
0.632398
AdeMiller
81d1300e1f418c9f7b6b6a28c3195c33cd388869
23,636
cpp
C++
Engine/source/gui/worldEditor/worldEditorSelection.cpp
RichardRanft/OmniEngine.Net
3363364e8c4514d5ef18574ce2200368e5946df4
[ "MIT", "Unlicense" ]
1
2015-01-21T06:12:21.000Z
2015-01-21T06:12:21.000Z
Engine/source/gui/worldEditor/worldEditorSelection.cpp
lukaspj/OmniEngine.Net
85edaa3e8afbb016352ce5784147cb9fe5fe35c1
[ "MIT", "Unlicense" ]
null
null
null
Engine/source/gui/worldEditor/worldEditorSelection.cpp
lukaspj/OmniEngine.Net
85edaa3e8afbb016352ce5784147cb9fe5fe35c1
[ "MIT", "Unlicense" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "gui/worldEditor/worldEditorSelection.h" #include "gui/worldEditor/worldEditor.h" #include "scene/sceneObject.h" IMPLEMENT_CONOBJECT( WorldEditorSelection ); ConsoleDocClass( WorldEditorSelection, "@brief Specialized simset that stores the objects selected by the World Editor\n\n" "Editor use only.\n\n" "@internal" ); //----------------------------------------------------------------------------- WorldEditorSelection::WorldEditorSelection() : mCentroidValid(false), mAutoSelect(false), mPrevCentroid(0.0f, 0.0f, 0.0f), mContainsGlobalBounds(false) { // Selections are transient by default. setCanSave( false ); setEditorOnly( true ); } //----------------------------------------------------------------------------- WorldEditorSelection::~WorldEditorSelection() { } //----------------------------------------------------------------------------- void WorldEditorSelection::initPersistFields() { Parent::initPersistFields(); } //----------------------------------------------------------------------------- void WorldEditorSelection::setCanSave( bool value ) { if( getCanSave() == value ) return; Parent::setCanSave( value ); // If we went from being transient to being persistent, // make sure all objects in the selection have persistent IDs. if( getCanSave() ) for( iterator iter = begin(); iter != end(); ++ iter ) ( *iter )->getOrCreatePersistentId(); } //----------------------------------------------------------------------------- bool WorldEditorSelection::objInSet( SimObject* obj ) { if( !mIsResolvingPIDs ) resolvePIDs(); lock(); bool result = false; for( iterator iter = begin(); iter != end(); ++ iter ) { if( obj == *iter ) { result = true; break; } WorldEditorSelection* set = dynamic_cast< WorldEditorSelection* >( *iter ); if( set && set->objInSet( obj ) ) { result = true; break; } } unlock(); return result; } //----------------------------------------------------------------------------- void WorldEditorSelection::addObject( SimObject* obj ) { // Return if object is already in selection. if( objInSet( obj ) ) return; // Refuse to add object if this selection is locked. if( isLocked() ) return; // Prevent adding us to ourselves. if( obj == this ) return; // If the object is itself a selection set, make sure we // don't create a cycle. WorldEditorSelection* selection = dynamic_cast< WorldEditorSelection* >( obj ); if( selection && !selection->objInSet( this ) ) return; // Refuse to add any of our parents. for( SimGroup* group = getGroup(); group != NULL; group = group->getGroup() ) if( obj == group ) return; invalidateCentroid(); Parent::addObject( obj ); if( mAutoSelect ) WorldEditor::markAsSelected( obj, true ); return; } //----------------------------------------------------------------------------- void WorldEditorSelection::removeObject( SimObject* obj ) { if( !objInSet( obj ) ) return; // Refuse to remove object if this selection is locked. if( isLocked() ) return; invalidateCentroid(); Parent::removeObject( obj ); if( mAutoSelect ) WorldEditor::markAsSelected( obj, false ); return; } //----------------------------------------------------------------------------- bool WorldEditorSelection::containsGlobalBounds() { updateCentroid(); return mContainsGlobalBounds; } //----------------------------------------------------------------------------- void WorldEditorSelection::updateCentroid() { if( mCentroidValid ) return; resolvePIDs(); mCentroidValid = true; mCentroid.set(0,0,0); mBoxCentroid = mCentroid; mBoxBounds.minExtents.set(1e10, 1e10, 1e10); mBoxBounds.maxExtents.set(-1e10, -1e10, -1e10); mContainsGlobalBounds = false; if( empty() ) return; // for( SimSet::iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* obj = dynamic_cast<SceneObject*>( *iter ); if( !obj ) continue; const MatrixF & mat = obj->getTransform(); Point3F wPos; mat.getColumn(3, &wPos); // mCentroid += wPos; // const Box3F& bounds = obj->getWorldBox(); mBoxBounds.minExtents.setMin(bounds.minExtents); mBoxBounds.maxExtents.setMax(bounds.maxExtents); if(obj->isGlobalBounds()) mContainsGlobalBounds = true; } mCentroid /= (F32) size(); mBoxCentroid = mBoxBounds.getCenter(); } //----------------------------------------------------------------------------- const Point3F & WorldEditorSelection::getCentroid() { updateCentroid(); return(mCentroid); } //----------------------------------------------------------------------------- const Point3F & WorldEditorSelection::getBoxCentroid() { updateCentroid(); return(mBoxCentroid); } //----------------------------------------------------------------------------- const Box3F & WorldEditorSelection::getBoxBounds() { updateCentroid(); return(mBoxBounds); } //----------------------------------------------------------------------------- Point3F WorldEditorSelection::getBoxBottomCenter() { updateCentroid(); Point3F bottomCenter = mBoxCentroid; bottomCenter.z -= mBoxBounds.len_z() * 0.5f; return bottomCenter; } //----------------------------------------------------------------------------- void WorldEditorSelection::enableCollision() { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast<SceneObject*>( *iter ); if( object ) object->enableCollision(); } } //----------------------------------------------------------------------------- void WorldEditorSelection::disableCollision() { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( object ) object->disableCollision(); } } //----------------------------------------------------------------------------- void WorldEditorSelection::offset( const Point3F& offset, F32 gridSnap ) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* obj = dynamic_cast<SceneObject*>( *iter ); if( !obj ) continue; MatrixF mat = obj->getTransform(); Point3F wPos; mat.getColumn(3, &wPos); // adjust wPos += offset; if( gridSnap != 0.f ) { wPos.x -= mFmod( wPos.x, gridSnap ); wPos.y -= mFmod( wPos.y, gridSnap ); wPos.z -= mFmod( wPos.z, gridSnap ); } mat.setColumn(3, wPos); obj->setTransform(mat); } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::setPosition(const Point3F & pos) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast<SceneObject*>( *iter ); if( object ) object->setPosition(pos); } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::setCentroidPosition(bool useBoxCenter, const Point3F & pos) { Point3F centroid; if( containsGlobalBounds() ) { centroid = getCentroid(); } else { centroid = useBoxCenter ? getBoxCentroid() : getCentroid(); } offset(pos - centroid); } //----------------------------------------------------------------------------- void WorldEditorSelection::orient(const MatrixF & rot, const Point3F & center) { // Orient all the selected objects to the given rotation for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; MatrixF mat = rot; mat.setPosition( object->getPosition() ); object->setTransform(mat); } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::rotate(const EulerF &rot) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; MatrixF mat = object->getTransform(); MatrixF transform(rot); mat.mul(transform); object->setTransform(mat); } } //----------------------------------------------------------------------------- void WorldEditorSelection::rotate(const EulerF & rot, const Point3F & center) { // single selections will rotate around own axis, multiple about world if(size() == 1) { SceneObject* object = dynamic_cast< SceneObject* >( at( 0 ) ); if( object ) { MatrixF mat = object->getTransform(); Point3F pos; mat.getColumn(3, &pos); // get offset in obj space Point3F offset = pos - center; MatrixF wMat = object->getWorldTransform(); wMat.mulV(offset); // MatrixF transform(EulerF(0,0,0), -offset); transform.mul(MatrixF(rot)); transform.mul(MatrixF(EulerF(0,0,0), offset)); mat.mul(transform); object->setTransform(mat); } } else { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; MatrixF mat = object->getTransform(); Point3F pos; mat.getColumn(3, &pos); // get offset in obj space Point3F offset = pos - center; MatrixF transform(rot); Point3F wOffset; transform.mulV(offset, &wOffset); MatrixF wMat = object->getWorldTransform(); wMat.mulV(offset); // transform.set(EulerF(0,0,0), -offset); mat.setColumn(3, Point3F(0,0,0)); wMat.setColumn(3, Point3F(0,0,0)); transform.mul(wMat); transform.mul(MatrixF(rot)); transform.mul(mat); mat.mul(transform); mat.normalize(); mat.setColumn(3, wOffset + center); object->setTransform(mat); } } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::setRotate(const EulerF & rot) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; MatrixF mat = object->getTransform(); Point3F pos; mat.getColumn(3, &pos); MatrixF rmat(rot); rmat.setPosition(pos); object->setTransform(rmat); } } //----------------------------------------------------------------------------- void WorldEditorSelection::scale(const VectorF & scale) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; VectorF current = object->getScale(); current.convolve(scale); // clamp scale to sensible limits current.setMax( Point3F( 0.01f ) ); current.setMin( Point3F( 1000.0f ) ); object->setScale(current); } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::scale(const VectorF & scale, const Point3F & center) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; VectorF current = object->getScale(); current.convolve(scale); // clamp scale to sensible limits current.setMax( Point3F( 0.01f ) ); current.setMin( Point3F( 1000.0f ) ); // Apply the scale first. If the object's scale doesn't change with // this operation then this object doesn't scale. In this case // we don't want to continue with the offset operation. VectorF prevScale = object->getScale(); object->setScale(current); if( !object->getScale().equal(current) ) continue; // determine the actual scale factor to apply to the object offset // need to account for the scale limiting above to prevent offsets // being reduced to 0 which then cannot be restored by unscaling VectorF adjustedScale = current / prevScale; MatrixF mat = object->getTransform(); Point3F pos; mat.getColumn(3, &pos); Point3F offset = pos - center; offset *= adjustedScale; object->setPosition(offset + center); } } //----------------------------------------------------------------------------- void WorldEditorSelection::setScale(const VectorF & scale) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( object ) object->setScale( scale ); } mCentroidValid = false; } //----------------------------------------------------------------------------- void WorldEditorSelection::setScale(const VectorF & scale, const Point3F & center) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; MatrixF mat = object->getTransform(); Point3F pos; mat.getColumn(3, &pos); Point3F offset = pos - center; offset *= scale; object->setPosition(offset + center); object->setScale(scale); } } //----------------------------------------------------------------------------- void WorldEditorSelection::addSize(const VectorF & newsize) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; if( object->isGlobalBounds() ) continue; const Box3F& bounds = object->getObjBox(); VectorF extent = bounds.getExtents(); VectorF scaledextent = object->getScale() * extent; VectorF scale = (newsize + scaledextent) / scaledextent; object->setScale( object->getScale() * scale ); } } //----------------------------------------------------------------------------- void WorldEditorSelection::setSize(const VectorF & newsize) { for( iterator iter = begin(); iter != end(); ++ iter ) { SceneObject* object = dynamic_cast< SceneObject* >( *iter ); if( !object ) continue; if( object->isGlobalBounds() ) continue; const Box3F& bounds = object->getObjBox(); VectorF extent = bounds.getExtents(); VectorF scale = newsize / extent; object->setScale( scale ); } } //============================================================================= // Console Methods. //============================================================================= // MARK: ---- Console Methods ---- //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, containsGlobalBounds, bool, 2, 2, "() - True if an object with global bounds is contained in the selection." ) { return object->containsGlobalBounds(); } //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, getCentroid, const char*, 2, 2, "() - Return the median of all object positions in the selection." ) { static const U32 bufSize = 256; char* buffer = Con::getReturnBuffer( bufSize ); const Point3F& centroid = object->getCentroid(); dSprintf( buffer, bufSize, "%g %g %g", centroid.x, centroid.y, centroid.z ); return buffer; } //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, getBoxCentroid, const char*, 2, 2, "() - Return the center of the bounding box around the selection." ) { static const U32 bufSize = 256; char* buffer = Con::getReturnBuffer( bufSize ); const Point3F& boxCentroid = object->getBoxCentroid(); dSprintf( buffer, bufSize, "%g %g %g", boxCentroid.x, boxCentroid.y, boxCentroid.z ); return buffer; } //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, offset, void, 3, 4, "( vector delta, float gridSnap=0 ) - Move all objects in the selection by the given delta." ) { F32 x, y, z; dSscanf( argv[ 3 ], "%g %g %g", &x, &y, &z ); F32 gridSnap = 0.f; if( argc > 3 ) gridSnap = dAtof( argv[ 3 ] ); object->offset( Point3F( x, y, z ), gridSnap ); WorldEditor::updateClientTransforms( object ); } //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, union, void, 3, 3, "( SimSet set ) - Add all objects in the given set to this selection." ) { SimSet* selection; if( !Sim::findObject( argv[ 2 ], selection ) ) { Con::errorf( "WorldEditorSelection::union - no SimSet '%s'", argv[ 2 ] ); return; } const U32 numObjects = selection->size(); for( U32 i = 0; i < numObjects; ++ i ) object->addObject( selection->at( i ) ); } //----------------------------------------------------------------------------- ConsoleMethod( WorldEditorSelection, subtract, void, 3, 3, "( SimSet ) - Remove all objects in the given set from this selection." ) { SimSet* selection; if( !Sim::findObject( argv[ 2 ], selection ) ) { Con::errorf( "WorldEditorSelection::subtract - no SimSet '%s'", argv[ 2 ] ); return; } const U32 numObjects = selection->size(); for( U32 i = 0; i < numObjects; ++ i ) object->removeObject( selection->at( i ) ); } //---------------DNTC AUTO-GENERATED---------------// #include <vector> #include <string> #include "core/strings/stringFunctions.h" //---------------DO NOT MODIFY CODE BELOW----------// extern "C" __declspec(dllexport) S32 __cdecl wle_fnWorldEditorSelection_containsGlobalBounds(char * x__object) { WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return 0; bool wle_returnObject; { { {wle_returnObject =object->containsGlobalBounds(); return (S32)(wle_returnObject);} } } } extern "C" __declspec(dllexport) void __cdecl wle_fnWorldEditorSelection_getBoxCentroid(char * x__object, char* retval) { dSprintf(retval,16384,""); WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return; const char* wle_returnObject; { { static const U32 bufSize = 256; char* buffer = Con::getReturnBuffer( bufSize ); const Point3F& boxCentroid = object->getBoxCentroid(); dSprintf( buffer, bufSize, "%g %g %g", boxCentroid.x, boxCentroid.y, boxCentroid.z ); {wle_returnObject =buffer; if (!wle_returnObject) return; dSprintf(retval,16384,"%s",wle_returnObject); return; } } } } extern "C" __declspec(dllexport) void __cdecl wle_fnWorldEditorSelection_getCentroid(char * x__object, char* retval) { dSprintf(retval,16384,""); WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return; const char* wle_returnObject; { { static const U32 bufSize = 256; char* buffer = Con::getReturnBuffer( bufSize ); const Point3F& centroid = object->getCentroid(); dSprintf( buffer, bufSize, "%g %g %g", centroid.x, centroid.y, centroid.z ); {wle_returnObject =buffer; if (!wle_returnObject) return; dSprintf(retval,16384,"%s",wle_returnObject); return; } } } } extern "C" __declspec(dllexport) void __cdecl wle_fnWorldEditorSelection_offset(char * x__object, char * x__a2, char * x__a3) { WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return; const char* a2 = (const char*)x__a2; const char* a3 = (const char*)x__a3; { S32 argc = 4; if ( dStrlen(a3) == 0 ) argc=3; else argc=4; std::vector<const char*> arguments; arguments.push_back(""); arguments.push_back(""); arguments.push_back(a2); if ( argc >3 ) arguments.push_back(a3); const char** argv = &arguments[0]; { F32 x, y, z; dSscanf( argv[ 3 ], "%g %g %g", &x, &y, &z ); F32 gridSnap = 0.f; if( argc > 3 ) gridSnap = dAtof( argv[ 3 ] ); object->offset( Point3F( x, y, z ), gridSnap ); WorldEditor::updateClientTransforms( object ); } } } extern "C" __declspec(dllexport) void __cdecl wle_fnWorldEditorSelection_subtract(char * x__object, char * x__a2) { WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return; const char* a2 = (const char*)x__a2; { S32 argc = 3; argc=3; std::vector<const char*> arguments; arguments.push_back(""); arguments.push_back(""); arguments.push_back(a2); const char** argv = &arguments[0]; { SimSet* selection; if( !Sim::findObject( argv[ 2 ], selection ) ) { Con::errorf( "WorldEditorSelection::subtract - no SimSet '%s'", argv[ 2 ] ); return; } const U32 numObjects = selection->size(); for( U32 i = 0; i < numObjects; ++ i ) object->removeObject( selection->at( i ) ); } } } extern "C" __declspec(dllexport) void __cdecl wle_fnWorldEditorSelection_union(char * x__object, char * x__a2) { WorldEditorSelection* object; Sim::findObject(x__object, object ); if (!object) return; const char* a2 = (const char*)x__a2; { S32 argc = 3; argc=3; std::vector<const char*> arguments; arguments.push_back(""); arguments.push_back(""); arguments.push_back(a2); const char** argv = &arguments[0]; { SimSet* selection; if( !Sim::findObject( argv[ 2 ], selection ) ) { Con::errorf( "WorldEditorSelection::union - no SimSet '%s'", argv[ 2 ] ); return; } const U32 numObjects = selection->size(); for( U32 i = 0; i < numObjects; ++ i ) object->addObject( selection->at( i ) ); } } } //---------------END DNTC AUTO-GENERATED-----------//
25.691304
151
0.546285
RichardRanft
81d48f61adb55c012d64cff3d2451011438537c6
4,101
cpp
C++
src/Exception.cpp
markuspf/velocypack
0cf8f21764f0336c32925ccd48f488cb8068a097
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Exception.cpp
markuspf/velocypack
0cf8f21764f0336c32925ccd48f488cb8068a097
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Exception.cpp
markuspf/velocypack
0cf8f21764f0336c32925ccd48f488cb8068a097
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include <ostream> #include "velocypack/velocypack-common.h" #include "velocypack/Exception.h" using namespace arangodb::velocypack; Exception::Exception(ExceptionType type, char const* msg) noexcept : _type(type), _msg(msg) {} char const* Exception::message(ExceptionType type) noexcept { switch (type) { case InternalError: return "Internal error"; case NotImplemented: return "Not implemented"; case NoJsonEquivalent: return "Type has no equivalent in JSON"; case ParseError: return "Parse error"; case UnexpectedControlCharacter: return "Unexpected control character"; case DuplicateAttributeName: return "Duplicate attribute name"; case IndexOutOfBounds: return "Index out of bounds"; case NumberOutOfRange: return "Number out of range"; case InvalidUtf8Sequence: return "Invalid UTF-8 sequence"; case InvalidAttributePath: return "Invalid attribute path"; case InvalidValueType: return "Invalid value type for operation"; case NeedCustomTypeHandler: return "Cannot execute operation without custom type handler"; case NeedAttributeTranslator: return "Cannot execute operation without attribute translator"; case CannotTranslateKey: return "Cannot translate key"; case KeyNotFound: return "Key not found"; case BadTupleSize: return "Array size does not match tuple size"; case TooDeepNesting: return "Too deep nesting in Array/Object"; case BuilderNotSealed: return "Builder value not yet sealed"; case BuilderNeedOpenObject: return "Need open Object"; case BuilderNeedOpenArray: return "Need open Array"; case BuilderNeedSubvalue: return "Need subvalue in current Object or Array"; case BuilderNeedOpenCompound: return "Need open compound value (Array or Object)"; case BuilderUnexpectedType: return "Unexpected type"; case BuilderUnexpectedValue: return "Unexpected value"; case BuilderExternalsDisallowed: return "Externals are not allowed in this configuration"; case BuilderKeyAlreadyWritten: return "The key of the next key/value pair is already written"; case BuilderKeyMustBeString: return "The key of the next key/value pair must be a string"; case BuilderCustomDisallowed: return "Custom types are not allowed in this configuration"; case BuilderTagsDisallowed: return "Tagged types are not allowed in this configuration"; case BuilderBCDDisallowed: return "BCD types are not allowed in this configuration"; case ValidatorInvalidType: return "Invalid type found in binary data"; case ValidatorInvalidLength: return "Invalid length found in binary data"; case UnknownError: default: return "Unknown error"; } } std::ostream& operator<<(std::ostream& stream, Exception const* ex) { stream << "[Exception " << ex->what() << "]"; return stream; } std::ostream& operator<<(std::ostream& stream, Exception const& ex) { return operator<<(stream, &ex); }
35.051282
80
0.682273
markuspf
81d61b6d27ee2e797b6f3cf390084e5abd99ea23
21,788
cpp
C++
Sources/Extras/CoreMediaIO/DeviceAbstractionLayer/Devices/DP/Base/CMIO_DP_ControlDictionary.cpp
nnanhthu/QuickomVC
6d4641336dd5d515238c94feb8f6a025fc8d181b
[ "MIT" ]
170
2018-11-28T10:20:54.000Z
2022-03-29T01:54:43.000Z
Sources/Extras/CoreMediaIO/DeviceAbstractionLayer/Devices/DP/Base/CMIO_DP_ControlDictionary.cpp
nnanhthu/QuickcomVirtualCamera
4eba93196549a9ad8ee63fb5a741586098e9ca5b
[ "MIT" ]
19
2018-12-03T15:06:54.000Z
2022-02-11T00:02:59.000Z
Sources/Extras/CoreMediaIO/DeviceAbstractionLayer/Devices/DP/Base/CMIO_DP_ControlDictionary.cpp
nnanhthu/QuickcomVirtualCamera
4eba93196549a9ad8ee63fb5a741586098e9ca5b
[ "MIT" ]
25
2018-11-29T02:15:09.000Z
2021-12-28T20:56:35.000Z
/* File: CMIO_DP_ControlDictionary.cpp Abstract: n/a Version: 1.2 */ //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Self Include #include "CMIO_DP_ControlDictionary.h" // CA Public Utilility Includes #include "CACFArray.h" #include "CACFDictionary.h" #include "CACFString.h" // System Includes #include <IOKit/IOTypes.h> #include <IOKit/video/IOVideoTypes.h> namespace { //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetBoolean //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- bool GetBoolean(const CACFDictionary& dictionary, const CFStringRef key) { bool answer = false; dictionary.GetBool(key, answer); return answer; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetUInt32 //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 GetUInt32(const CACFDictionary& dictionary, const CFStringRef key) { UInt32 answer = 0; dictionary.GetUInt32(key, answer); return answer; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetUInt64 //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt64 GetUInt64(const CACFDictionary& dictionary, const CFStringRef key) { UInt64 answer = 0; dictionary.GetUInt64(key, answer); return answer; } } namespace CMIO { namespace DP { //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Create() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFMutableDictionaryRef ControlDictionary::Create(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, const CACFString& name, bool isReadOnly, UInt32 variant) { CACFDictionary answer = CACFDictionary(false); if (answer.IsValid()) { // Fill out the info, starting with the control ID answer.AddUInt32(CFSTR(kIOVideoControlKey_ControlID), controlID); // Do the base class answer.AddUInt32(CFSTR(kIOVideoControlKey_BaseClass), baseClass); // Do the class answer.AddUInt32(CFSTR(kIOVideoControlKey_Class), derivedClass); // Do the scope answer.AddUInt32(CFSTR(kIOVideoControlKey_Scope), scope); // Do the element answer.AddUInt32(CFSTR(kIOVideoControlKey_Element), element); // Do the is read only value answer.AddBool(CFSTR(kIOVideoControlKey_IsReadOnly), isReadOnly); // Do the variant answer.AddUInt32(CFSTR(kIOVideoControlKey_Variant), variant); // Do the name if (name.IsValid()) { answer.AddString(CFSTR(kIOVideoControlKey_Name), name.GetCFString()); } } return (answer.GetCFMutableDictionary()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CreateBooleanControl() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFMutableDictionaryRef ControlDictionary::CreateBooleanControl(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, bool value, const CACFString& name, bool isReadOnly, UInt32 variant) { // Do the general fields CACFDictionary answer(Create(controlID, baseClass, derivedClass, scope, element, name, isReadOnly, variant), false); if (answer.IsValid()) { // Do the value answer.AddBool(CFSTR(kIOVideoControlKey_Value), value); } return (answer.GetCFMutableDictionary()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CreateSelectorControl() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFMutableDictionaryRef ControlDictionary::CreateSelectorControl(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, UInt32 value, CACFArray& selectorMap, const CACFString& name, bool isReadOnly, UInt32 variant) { // Do the general fields CACFDictionary answer(Create(controlID, baseClass, derivedClass, scope, element, name, isReadOnly, variant), false); if (answer.IsValid()) { // Do the value answer.AddUInt32(CFSTR(kIOVideoControlKey_Value), value); // Do the range map if (selectorMap.IsValid()) { answer.AddArray(CFSTR(kIOVideoSelectorControlKey_SelectorMap), selectorMap.GetCFArray()); } } return (answer.GetCFMutableDictionary()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetControlByID() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFMutableDictionaryRef ControlDictionary::GetControlByID(const CACFArray& controlList, UInt32 controlID) { // Note that this routine require that the returned dictionary not be released CACFDictionary answer; CFMutableDictionaryRef returnDict = NULL; CFDictionaryRef cfanswer; UInt32 count, i; if (controlList.IsValid()) { count = controlList.GetNumberItems(); for (i = 0 ; i< count; ++i) { if (controlList.GetDictionary(i, cfanswer)) { CACFDictionary interimAnswer(cfanswer, false); if (interimAnswer.IsValid()) { if (controlID == ControlDictionary::GetControlID(interimAnswer)) { returnDict = interimAnswer.GetCFMutableDictionary(); break; } } } } } return returnDict; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetControlID() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetControlID(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_ControlID)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetControlID() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetControlID(CACFDictionary& dictionary, UInt32 controlID) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_ControlID), controlID); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetBaseClass() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetBaseClass(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_BaseClass)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetBaseClass() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetBaseClass(CACFDictionary& dictionary, UInt32 baseClass) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_BaseClass), baseClass); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetClass() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetClass(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_Class)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetClass() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetClass(CACFDictionary& dictionary, UInt32 derivedClass) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_Class), derivedClass); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetScope() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetScope(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_Scope)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetScope() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetScope(CACFDictionary& dictionary, UInt32 scope) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_Scope), scope); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetElement() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetElement(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_Element)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetElement() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetElement(CACFDictionary& dictionary, UInt32 element) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_Element), element); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // IsReadOnly() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- bool ControlDictionary::IsReadOnly(const CACFDictionary& dictionary) { return GetBoolean(dictionary, CFSTR(kIOVideoControlKey_IsReadOnly)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetIsReadOnly() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetIsReadOnly(CACFDictionary& dictionary, bool isReadOnly) { dictionary.AddBool(CFSTR(kIOVideoControlKey_IsReadOnly), isReadOnly); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetVariant() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetVariant(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_Variant)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetVariant() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetVariant(CACFDictionary& dictionary, UInt32 variant) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_Variant), variant); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CopyName() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFStringRef ControlDictionary::CopyName(const CACFDictionary& dictionary) { // Get the value from the dictionary and make sure it's a string CFStringRef answer; dictionary.GetString(CFSTR(kIOVideoControlKey_Name), answer); return answer; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetName() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetName(CACFDictionary& dictionary, const CACFString& name) { dictionary.AddString(CFSTR(kIOVideoControlKey_Name), name.GetCFString()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetBooleanControlValue() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- bool ControlDictionary::GetBooleanControlValue(const CACFDictionary& dictionary) { return GetBoolean(dictionary, CFSTR(kIOVideoControlKey_Value)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetBooleanControlValue() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetBooleanControlValue(CACFDictionary& dictionary, bool value) { dictionary.AddBool(CFSTR(kIOVideoControlKey_Value), value); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // GetSelectorControlValue() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- UInt32 ControlDictionary::GetSelectorControlValue(const CACFDictionary& dictionary) { return GetUInt32(dictionary, CFSTR(kIOVideoControlKey_Value)); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetSelectorControlValue() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetSelectorControlValue(CACFDictionary& dictionary, UInt32 value) { dictionary.AddUInt32(CFSTR(kIOVideoControlKey_Value), value); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CopySelectorControlSelectorMap() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFArrayRef ControlDictionary::CopySelectorControlSelectorMap(const CACFDictionary& dictionary) { CFArrayRef answer; // Get the value from the dictionary and make sure it's an array dictionary.GetArray(CFSTR(kIOVideoSelectorControlKey_SelectorMap), answer); return answer; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // SetSelectorControlSelectorMap() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void ControlDictionary::SetSelectorControlSelectorMap(CACFDictionary& dictionary, CACFArray& selectorMap) { dictionary.AddArray(CFSTR(kIOVideoSelectorControlKey_SelectorMap), selectorMap.GetCFArray()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CreateSelectorControlSelectorMapItem() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFDictionaryRef ControlDictionary::CreateSelectorControlSelectorMapItem(UInt32 value, const CACFString& name) { CACFDictionary answer = CACFDictionary(false); if (answer.IsValid()) { // Do the value answer.AddUInt32(CFSTR(kIOVideoSelectorControlSelectorMapItemKey_Value), value); // Do the starting name answer.AddString(CFSTR(kIOVideoSelectorControlSelectorMapItemKey_Name), name.GetCFString()); } return (answer.GetCFDictionary()); } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // CreateSelectorControlSelectorMapItem() //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CFDictionaryRef ControlDictionary::CreateSelectorControlSelectorMapItem(UInt32 value, const CACFString& name, UInt32 kind) { CACFDictionary answer = CACFDictionary(false); if (answer.IsValid()) { // Do the value answer.AddUInt32(CFSTR(kIOVideoSelectorControlSelectorMapItemKey_Value), value); // Do the starting name answer.AddString(CFSTR(kIOVideoSelectorControlSelectorMapItemKey_Name), name.GetCFString()); // Do the kind answer.AddUInt32(CFSTR(kIOVideoSelectorControlSelectorMapItemKey_Kind), kind); } return (answer.GetCFDictionary()); } }}
55.159494
246
0.329447
nnanhthu
81d822767a2f6d5af43642d68d38fd4c8a77df40
9,454
cpp
C++
test/frame/test_manager.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
1
2021-02-10T15:29:46.000Z
2021-02-10T15:29:46.000Z
test/frame/test_manager.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
null
null
null
test/frame/test_manager.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
null
null
null
/* * test_manager.cpp * * Created on: 2014年3月11日 * Author: owent * * Released under the MIT license */ #include <cstring> #include <iostream> #include <sstream> #include <string> #include <vector> #include "cli/cmd_option.h" #include "cli/cmd_option_phoenix.h" #include "cli/shell_font.h" #include "test_manager.h" test_manager::pick_param_str_t::pick_param_str_t(const char *in) : str_(in) {} test_manager::pick_param_str_t::pick_param_str_t(const std::string &in) : str_(in.c_str()) {} bool test_manager::pick_param_str_t::operator==(const pick_param_str_t &other) const { return strcmp(str_, other.str_) == 0; } bool test_manager::pick_param_str_t::operator!=(const pick_param_str_t &other) const { return strcmp(str_, other.str_) != 0; } bool test_manager::pick_param_str_t::operator>=(const pick_param_str_t &other) const { return strcmp(str_, other.str_) >= 0; } bool test_manager::pick_param_str_t::operator>(const pick_param_str_t &other) const { return strcmp(str_, other.str_) > 0; } bool test_manager::pick_param_str_t::operator<=(const pick_param_str_t &other) const { return strcmp(str_, other.str_) <= 0; } bool test_manager::pick_param_str_t::operator<(const pick_param_str_t &other) const { return strcmp(str_, other.str_) < 0; } test_manager::test_manager() { success_counter_ptr = failed_counter_ptr = NULL; success_ = 0; failed_ = 0; } test_manager::~test_manager() {} void test_manager::append(const std::string &test_name, const std::string &case_name, case_ptr_type ptr) { tests_[test_name].push_back(std::make_pair(case_name, ptr)); } #ifdef UTILS_TEST_MACRO_TEST_ENABLE_BOOST_TEST boost::unit_test::test_suite *&test_manager::test_suit() { static boost::unit_test::test_suite *ret = NULL; return ret; } int test_manager::run() { using namespace boost::unit_test; for (test_data_type::iterator iter = tests_.begin(); iter != tests_.end(); ++iter) { test_suit() = BOOST_TEST_SUITE(iter->first.c_str()); for (test_type::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { test_suit()->add(make_test_case(callback0<>(iter2->second->func_), iter2->first.c_str())); iter2->second->run(); } framework::master_test_suite().add(test_suit()); } return 0; } #else int test_manager::run() { success_ = 0; failed_ = 0; clock_t all_begin_time = clock(); util::cli::shell_stream ss(std::cout); ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << util::cli::shell_font_style::SHELL_FONT_SPEC_BOLD << "[==========] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << "Running " << tests_.size() << " test(s)" << std::endl; for (test_data_type::iterator iter = tests_.begin(); iter != tests_.end(); ++iter) { bool check_test_group_passed = run_cases_.empty(); bool check_test_group_has_cases = false; if (!check_test_group_passed) { check_test_group_passed = run_cases_.end() != run_cases_.find(iter->first); } if (!check_test_group_passed) { check_test_group_has_cases = run_groups_.end() != run_groups_.find(iter->first); } // skip unknown groups if (!check_test_group_passed && !check_test_group_has_cases) { continue; } size_t run_group_count = 0; ss() << std::endl << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << util::cli::shell_font_style::SHELL_FONT_SPEC_BOLD << "[----------] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << iter->second.size() << " test case(s) from " << iter->first << std::endl; clock_t test_begin_time = clock(); for (test_type::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { bool check_test_case_passed = run_cases_.empty() || check_test_group_passed; if (!check_test_case_passed) { check_test_case_passed = run_cases_.end() != run_cases_.find(iter2->first); if (!check_test_case_passed) { std::string full_name; full_name.reserve(iter->first.size() + 1 + iter2->first.size()); full_name = iter->first + "." + iter2->first; check_test_case_passed = run_cases_.end() != run_cases_.find(full_name); } } // skip unknown cases if (!check_test_case_passed) { continue; } ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << "[ RUN ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << iter->first << "." << iter2->first << std::endl; clock_t case_begin_time = clock(); iter2->second->run(); clock_t case_end_time = clock(); if (0 == iter2->second->failed_) { ++success_; ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << "[ OK ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << iter->first << "." << iter2->first << " (" << get_expire_time(case_begin_time, case_end_time) << ")" << std::endl; } else { ++failed_; ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_RED << "[ FAILED ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << iter->first << "." << iter2->first << " (" << get_expire_time(case_begin_time, case_end_time) << ")" << std::endl; } ++run_group_count; } clock_t test_end_time = clock(); ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << util::cli::shell_font_style::SHELL_FONT_SPEC_BOLD << "[----------] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << run_group_count << " test case(s) from " << iter->first << " (" << get_expire_time(test_begin_time, test_end_time) << " total)" << std::endl; } clock_t all_end_time = clock(); ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << util::cli::shell_font_style::SHELL_FONT_SPEC_BOLD << "[==========] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << (success_ + failed_) << " test(s) ran." << " (" << get_expire_time(all_begin_time, all_end_time) << " total)" << std::endl; ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_GREEN << "[ PASSED ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << success_ << " test case(s)." << std::endl; if (failed_ > 0) { ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_RED << "[ FAILED ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << failed_ << " test case(s), listed below:" << std::endl; for (test_data_type::iterator iter = tests_.begin(); iter != tests_.end(); ++iter) { for (test_type::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { if (iter2->second->failed_ > 0) { ss() << util::cli::shell_font_style::SHELL_FONT_COLOR_RED << "[ FAILED ] " << util::cli::shell_font_style::SHELL_FONT_SPEC_NULL << iter->first << "." << iter2->first << std::endl; } } } } return (0 == failed_) ? 0 : -failed_; } #endif void test_manager::set_cases(const std::vector<std::string> &case_names) { run_cases_.clear(); run_groups_.clear(); for (size_t i = 0; i < case_names.size(); ++i) { run_cases_.insert(case_names[i]); std::string::size_type split_idx = case_names[i].find('.'); if (split_idx != std::string::npos) { run_groups_.insert(case_names[i].substr(0, split_idx)); } } } test_manager &test_manager::me() { static test_manager ret; return ret; } std::string test_manager::get_expire_time(clock_t begin, clock_t end) { std::stringstream ss; double ms = 1000.0 * (end - begin) / CLOCKS_PER_SEC; ss << ms << " ms"; return ss.str(); } int run_tests(int argc, char *argv[]) { std::vector<std::string> run_cases; const char * version = "1.0.0"; bool is_help = false; bool is_show_version = false; util::cli::cmd_option::ptr_type cmd_opts = util::cli::cmd_option::create(); cmd_opts->bind_cmd("-h, --help, help", util::cli::phoenix::set_const(is_help, true)) ->set_help_msg(" show help message and exit."); cmd_opts->bind_cmd("-v, --version, version", util::cli::phoenix::set_const(is_show_version, true)) ->set_help_msg(" show version and exit."); cmd_opts->bind_cmd("-r, --run, run", util::cli::phoenix::push_back(run_cases)) ->set_help_msg("[case names...] only run specify cases."); cmd_opts->start(argc, argv); if (is_help) { std::cout << *cmd_opts << std::endl; return 0; } if (is_show_version) { std::cout << version << std::endl; return 0; } test_manager::me().set_cases(run_cases); return test_manager::me().run(); }
40.575107
139
0.591919
tangzhenquan
81dd704359816e69341c161204b56aa71781dfb4
14,962
cc
C++
src/lib/socket/socket.cc
easel/v8cgi
0ac37452006803fb7bc83e64e934b4009aabc910
[ "BSD-3-Clause" ]
4
2016-01-31T08:49:35.000Z
2021-07-12T17:31:42.000Z
src/lib/socket/socket.cc
easel/v8cgi
0ac37452006803fb7bc83e64e934b4009aabc910
[ "BSD-3-Clause" ]
null
null
null
src/lib/socket/socket.cc
easel/v8cgi
0ac37452006803fb7bc83e64e934b4009aabc910
[ "BSD-3-Clause" ]
1
2017-11-28T13:02:40.000Z
2017-11-28T13:02:40.000Z
/** * Socket library. Provides a simple OO abstraction atop several socket-related functions. */ #include <v8.h> #include "macros.h" #include "common.h" #include <stdlib.h> #include <errno.h> #include <string.h> #ifdef windows # include <winsock2.h> # include <ws2tcpip.h> # define close(s) closesocket(s) #else # include <unistd.h> # include <sys/socket.h> # include <sys/un.h> # include <sys/param.h> # include <arpa/inet.h> # include <netinet/in.h> # include <netdb.h> #endif #ifndef MAXHOSTNAMELEN # define MAXHOSTNAMELEN 64 #endif #ifndef INVALID_SOCKET # define INVALID_SOCKET -1 #endif #ifndef SOCKET_ERROR # define SOCKET_ERROR -1 #endif namespace { v8::Persistent<v8::Function> socketFunc; typedef union sock_addr { struct sockaddr_in in; #ifndef windows struct sockaddr_un un; #endif struct sockaddr_in6 in6; } sock_addr_t; /** * Universal address creator. * @param {char *} address Stringified addres * @param {int} port Port number * @param {int} family Address family * @param {sock_addr_t *} result Target data structure * @param {socklen_t *} len Result length */ inline int create_addr(char * address, int port, int family, sock_addr_t * result, socklen_t * len) { unsigned int length = strlen(address); switch (family) { #ifndef windows case PF_UNIX: { struct sockaddr_un *addr = (struct sockaddr_un*) result; memset(addr, 0, sizeof(sockaddr_un)); if (length >= sizeof(addr->sun_path)) { JS_ERROR("Unix socket path too long"); return 1; } addr->sun_family = AF_UNIX; memcpy(addr->sun_path, address, length); addr->sun_path[length] = '\0'; *len = length + (sizeof(*addr) - sizeof(addr->sun_path)); } break; #endif case PF_INET: { struct sockaddr_in *addr = (struct sockaddr_in*) result; memset(addr, 0, sizeof(*addr)); addr->sin_family = AF_INET; #ifdef windows int size = sizeof(struct sockaddr_in); int pton_ret = WSAStringToAddress(address, AF_INET, NULL, (sockaddr *) result, &size); if (pton_ret != 0) { return 1; } #else int pton_ret = inet_pton(AF_INET, address, & addr->sin_addr.s_addr); if (pton_ret == 0) { return 1; } #endif addr->sin_port = htons((short)port); *len = sizeof(*addr); } break; case PF_INET6: { struct sockaddr_in6 *addr = (struct sockaddr_in6*) result; memset(addr, 0, sizeof(*addr)); addr->sin6_family = AF_INET6; #ifdef windows int size = sizeof(struct sockaddr_in6); int pton_ret = WSAStringToAddress(address, AF_INET6, NULL, (sockaddr *) result, &size); if (pton_ret != 0) { return 1; } #else int pton_ret = inet_pton(AF_INET6, address, addr->sin6_addr.s6_addr); if (pton_ret == 0) { return 1; } #endif addr->sin6_port = htons((short)port); *len = sizeof(*addr); } break; } return 0; } /** * Returns JS array with values describing remote address. * For UNIX socket, only one item is present. For AF_INET and * AF_INET6, array contains [address, port]. */ inline v8::Handle<v8::Value> create_peer(sockaddr * addr) { switch (addr->sa_family) { #ifndef windows case AF_UNIX: { v8::Handle<v8::Array> result = v8::Array::New(1); sockaddr_un * addr_un = (sockaddr_un *) addr; result->Set(JS_INT(0), JS_STR(addr_un->sun_path)); return result; } break; #endif case AF_INET6: { v8::Handle<v8::Array> result = v8::Array::New(2); char * buf = new char[INET6_ADDRSTRLEN]; sockaddr_in6 * addr_in6 = (sockaddr_in6 *) addr; #ifdef windows DWORD len = INET6_ADDRSTRLEN; WSAAddressToString(addr, sizeof(struct sockaddr), NULL, buf, &len); #else inet_ntop(AF_INET6, addr_in6->sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN); #endif result->Set(JS_INT(0), JS_STR(buf)); result->Set(JS_INT(1), JS_INT(ntohs(addr_in6->sin6_port))); delete[] buf; return result; } break; case AF_INET: { v8::Handle<v8::Array> result = v8::Array::New(2); char * buf = new char[INET_ADDRSTRLEN]; sockaddr_in * addr_in = (sockaddr_in *) addr; #ifdef windows DWORD len = INET_ADDRSTRLEN; WSAAddressToString(addr, sizeof(struct sockaddr), NULL, buf, &len); #else inet_ntop(AF_INET, & addr_in->sin_addr.s_addr, buf, INET_ADDRSTRLEN); #endif result->Set(JS_INT(0), JS_STR(buf)); result->Set(JS_INT(1), JS_INT(ntohs(addr_in->sin_port))); delete[] buf; return result; } break; } return v8::Undefined(); } /** * Socket constructor * @param {int} family * @param {int} type * @param {int} [proto] */ JS_METHOD(_socket) { ASSERT_CONSTRUCTOR; if (args.Length() < 2) { return JS_TYPE_ERROR("Invalid call format. Use 'new Socket(family, type, [proto])'"); } int offset = (args[0]->IsExternal() ? 1 : 0); int family = args[offset + 0]->Int32Value(); int type = args[offset + 1]->Int32Value(); int proto = args[offset + 2]->Int32Value(); int s = -1; if (args[0]->IsExternal()) { v8::Handle<v8::External> tmp = v8::Handle<v8::External>::Cast(args[0]); s = *((int *) tmp->Value()); } else { s = socket(family, type, proto); } SAVE_VALUE(0, JS_INT(s)); SAVE_VALUE(1, JS_BOOL(false)); args.This()->Set(JS_STR("family"), JS_INT(family)); args.This()->Set(JS_STR("type"), JS_INT(type)); args.This()->Set(JS_STR("proto"), JS_INT(proto)); if (s == INVALID_SOCKET) { return JS_ERROR(strerror(errno)); } else { return args.This(); } } JS_METHOD(_getprotobyname) { v8::String::Utf8Value name(args[0]); struct protoent * result = getprotobyname(*name); if (result) { return JS_INT(result->p_proto); } else { return JS_ERROR("Cannot retrieve protocol number"); } } JS_METHOD(_getaddrinfo) { v8::String::Utf8Value name(args[0]); int family = args[1]->IntegerValue(); struct addrinfo hints, * servinfo; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; int result = getaddrinfo(*name, NULL, &hints, &servinfo); if (result != 0) { return JS_ERROR(gai_strerror(result)); } v8::Local<v8::Object> item = create_peer(servinfo->ai_addr)->ToObject(); freeaddrinfo(servinfo); return item->Get(JS_INT(0)); } JS_METHOD(_getnameinfo) { v8::String::Utf8Value name(args[0]); int family = args[1]->IntegerValue(); if (family == 0) { family = PF_INET; } char hostname[NI_MAXHOST]; sock_addr_t addr; socklen_t len = 0; int result = create_addr(*name, 0, family, &addr, &len); if (result != 0) { return JS_ERROR("Malformed address"); } result = getnameinfo((sockaddr *) & addr, len, hostname, NI_MAXHOST, NULL, 0, 0); if (result != 0) { return JS_ERROR(gai_strerror(result)); } else { return JS_STR(hostname); } } JS_METHOD(_gethostname) { v8::HandleScope handle_scope; char * buf = new char[MAXHOSTNAMELEN+1]; gethostname(buf, MAXHOSTNAMELEN); v8::Handle<v8::Value> result = JS_STR(buf); delete[] buf; return result; } JS_METHOD(_connect) { int family = args.This()->Get(JS_STR("family"))->Int32Value(); int sock = LOAD_VALUE(0)->Int32Value(); int argcount = 1; if (family != PF_UNIX) { argcount = 2; } if (args.Length() < argcount) { return JS_TYPE_ERROR("Bad argument count. Use 'socket.connect(address, [port])'"); } v8::String::Utf8Value address(args[0]); int port = args[1]->Int32Value(); sock_addr_t addr; socklen_t len = 0; int result = create_addr(* address, port, family, &addr, &len); if (result != 0) { return JS_ERROR("Malformed address"); } result = connect(sock, (sockaddr *) &addr, len); if (result) { return JS_ERROR(strerror(errno)); } else { return args.This(); } } JS_METHOD(_bind) { int family = args.This()->Get(JS_STR("family"))->Int32Value(); int sock = LOAD_VALUE(0)->Int32Value(); if (args.Length() < 1) { return JS_TYPE_ERROR("Bad argument count. Use 'socket.bind(address, [port])'"); } v8::String::Utf8Value address(args[0]); int port = args[1]->Int32Value(); sock_addr_t addr; socklen_t len = 0; int result = create_addr(*address, port, family, &addr, &len); if (result != 0) { return JS_ERROR("Malformed address"); } result = bind(sock, (sockaddr *) &addr, len); if (result) { return JS_ERROR(strerror(errno)); } else { return args.This(); } } JS_METHOD(_listen) { int sock = LOAD_VALUE(0)->Int32Value(); int num = args[0]->Int32Value(); if (args.Length() == 0) { num = 5; } int result = listen(sock, num); if (result) { return JS_ERROR(strerror(errno)); } else { return args.This(); } } JS_METHOD(_accept) { int sock = LOAD_VALUE(0)->Int32Value(); int sock2 = accept(sock, NULL, NULL); if (sock2 == INVALID_SOCKET) { return JS_ERROR(strerror(errno)); } else { v8::Handle<v8::Value> argv[4]; argv[0] = v8::External::New(&sock2); // dummy field argv[1] = args.This()->Get(JS_STR("family")); argv[2] = args.This()->Get(JS_STR("type")); argv[3] = args.This()->Get(JS_STR("proto")); return socketFunc->NewInstance(4, argv); } } JS_METHOD(_send) { int sock = LOAD_VALUE(0)->Int32Value(); if (args.Length() < 1) { return JS_TYPE_ERROR("Bad argument count. Use 'socket.send(data, [address], [port])'"); } sock_addr_t taddr; sockaddr * target = NULL; socklen_t len = 0; ssize_t result; if (args.Length() > 1) { int family = args.This()->Get(JS_STR("family"))->Int32Value(); v8::String::Utf8Value address(args[1]); int port = args[2]->Int32Value(); int r = create_addr(*address, port, family, &taddr, &len); if (r != 0) { return JS_ERROR("Malformed address"); } target = (sockaddr *) &taddr; } if (args[0]->IsArray()) { v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]); uint32_t arrlen = arr->Length(); char * buf = new char[arrlen]; for (unsigned int i=0;i<arrlen;i++) { buf[i] = (char) arr->Get(JS_INT(i))->IntegerValue(); } result = sendto(sock, buf, arrlen, 0, target, len); delete[] buf; } else { v8::String::Utf8Value data(args[0]); result = sendto(sock, *data, data.length(), 0, target, len); } if (result == SOCKET_ERROR) { return JS_ERROR(strerror(errno)); } else { return args.This(); } } JS_METHOD(_receive) { int sock = LOAD_VALUE(0)->Int32Value(); int count = args[0]->Int32Value(); int type = args.This()->Get(JS_STR("type"))->Int32Value(); char * data = new char[count]; sock_addr_t addr; socklen_t len = 0; ssize_t result = recvfrom(sock, data, count, 0, (sockaddr *) &addr, &len); if (result == SOCKET_ERROR) { delete[] data; return JS_ERROR(strerror(errno)); } else { v8::Handle<v8::Value> output; if (args.Length() > 1 && args[1]->IsTrue()) { output = JS_CHARARRAY((char *) data, result); } else { output = JS_STR(data, result); } v8::Handle<v8::Value> text = JS_STR(data, result); delete[] data; if (type == SOCK_DGRAM) { SAVE_VALUE(1, create_peer((sockaddr *) &addr)); } return output; } } JS_METHOD(_socketclose) { int sock = LOAD_VALUE(0)->Int32Value(); int result = close(sock); if (result == SOCKET_ERROR) { return JS_ERROR(strerror(errno)); } else { return v8::Undefined(); } } JS_METHOD(_setoption) { if (args.Length() != 2) { return JS_TYPE_ERROR("Bad argument count. Use 'socket.setOption(name, value)'"); } int sock = LOAD_VALUE(0)->Int32Value(); int name = args[0]->Int32Value(); int value = args[1]->Int32Value(); int result = setsockopt(sock, SOL_SOCKET, name, (char *) &value, sizeof(int)); if (result == 0) { return args.This(); } else { return JS_ERROR(strerror(errno)); } } JS_METHOD(_getoption) { if (args.Length() < 1) { return JS_TYPE_ERROR("Bad argument count. Use 'socket.getOption(name, [length])'"); } int sock = LOAD_VALUE(0)->Int32Value(); int name = args[0]->Int32Value(); if (args.Length() == 2) { int length = args[1]->Int32Value(); char * buf = new char[length]; int result = getsockopt(sock, SOL_SOCKET, name, buf, (socklen_t *) &length); if (result == 0) { v8::Handle<v8::Value> response = JS_STR(buf, length); delete[] buf; return response; } else { delete[] buf; return JS_ERROR(strerror(errno)); } } else { unsigned int buf; int length = sizeof(buf); int result = getsockopt(sock, SOL_SOCKET, name, (char *) &buf, (socklen_t *) &length); if (result == 0) { return JS_INT(buf); } else { return JS_ERROR(strerror(errno)); } } } JS_METHOD(_getpeername) { int sock = LOAD_VALUE(0)->Int32Value(); if (!LOAD_VALUE(1)->IsTrue()) { sock_addr_t addr; socklen_t len = sizeof(sock_addr_t); int result = getpeername(sock, (sockaddr *) &addr, &len); if (result == 0) { SAVE_VALUE(1, create_peer((sockaddr *) &addr)); } else { return JS_ERROR(strerror(errno)); } } return LOAD_VALUE(1); } } SHARED_INIT() { v8::HandleScope handle_scope; #ifdef windows WSADATA wsaData; WORD wVersionRequested = MAKEWORD(2, 0); WSAStartup(wVersionRequested, &wsaData); #endif v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_socket); ft->SetClassName(JS_STR("Socket")); /** * Constants (Socket.*) */ ft->Set(JS_STR("PF_INET"), JS_INT(PF_INET)); ft->Set(JS_STR("PF_INET6"), JS_INT(PF_INET6)); ft->Set(JS_STR("PF_UNIX"), JS_INT(PF_UNIX)); ft->Set(JS_STR("IPPROTO_TCP"), JS_INT(IPPROTO_TCP)); ft->Set(JS_STR("IPPROTO_UDP"), JS_INT(IPPROTO_UDP)); ft->Set(JS_STR("SOCK_STREAM"), JS_INT(SOCK_STREAM)); ft->Set(JS_STR("SOCK_DGRAM"), JS_INT(SOCK_DGRAM)); ft->Set(JS_STR("SOCK_RAW"), JS_INT(SOCK_RAW)); ft->Set(JS_STR("SO_REUSEADDR"), JS_INT(SO_REUSEADDR)); ft->Set(JS_STR("SO_BROADCAST"), JS_INT(SO_BROADCAST)); ft->Set(JS_STR("SO_KEEPALIVE"), JS_INT(SO_KEEPALIVE)); ft->Set(JS_STR("getProtoByName"), v8::FunctionTemplate::New(_getprotobyname)->GetFunction()); ft->Set(JS_STR("getAddrInfo"), v8::FunctionTemplate::New(_getaddrinfo)->GetFunction()); ft->Set(JS_STR("getNameInfo"), v8::FunctionTemplate::New(_getnameinfo)->GetFunction()); ft->Set(JS_STR("getHostName"), v8::FunctionTemplate::New(_gethostname)->GetFunction()); v8::Handle<v8::ObjectTemplate> it = ft->InstanceTemplate(); it->SetInternalFieldCount(2); /* sock, peername */ v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate(); /** * Prototype methods (new Socket().*) */ pt->Set("connect", v8::FunctionTemplate::New(_connect)); pt->Set("send", v8::FunctionTemplate::New(_send)); pt->Set("receive", v8::FunctionTemplate::New(_receive)); pt->Set("bind", v8::FunctionTemplate::New(_bind)); pt->Set("listen", v8::FunctionTemplate::New(_listen)); pt->Set("accept", v8::FunctionTemplate::New(_accept)); pt->Set("close", v8::FunctionTemplate::New(_socketclose)); pt->Set("setOption", v8::FunctionTemplate::New(_setoption)); pt->Set("getOption", v8::FunctionTemplate::New(_getoption)); pt->Set("getPeerName", v8::FunctionTemplate::New(_getpeername)); exports->Set(JS_STR("Socket"), ft->GetFunction()); socketFunc = v8::Persistent<v8::Function>::New(ft->GetFunction()); }
27.105072
119
0.650715
easel
81defe5efd2f0ed797e47949e8dc5f3d7ea874f7
927
cpp
C++
Solutions/1-50/43/Solution.cpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
2
2021-07-16T13:30:10.000Z
2021-07-16T18:17:40.000Z
Solutions/1-50/43/Solution.cpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
null
null
null
Solutions/1-50/43/Solution.cpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
1
2021-04-16T22:56:07.000Z
2021-04-16T22:56:07.000Z
#include <algorithm> #include <boost/multiprecision/cpp_int.hpp> #include <iostream> #include <numeric> #include <string> #include <vector> using namespace std; using boost::multiprecision::cpp_int; int main(int argc, char *argv[]) { vector<cpp_int> nums; string base = "0123456789"; do { // Convert to integers. int a = stoull(base.substr(1, 3)); int b = stoull(base.substr(2, 3)); int c = stoull(base.substr(3, 3)); int d = stoull(base.substr(4, 3)); int e = stoull(base.substr(5, 3)); int f = stoull(base.substr(6, 3)); int g = stoull(base.substr(7, 3)); if((a % 2 == 0) && (b % 3 == 0) && (c % 5 == 0) && (d % 7 == 0) && (e % 11 == 0) && (f % 13 == 0) && (g % 17 == 0)) { nums.push_back((cpp_int)stoull(base)); } } while(next_permutation(base.begin(), base.end())); cpp_int sum = 0; for(const auto &n : nums) { sum += n; } cout << sum << endl; return 0; }
28.090909
120
0.571737
kitegi
81e215a986b7b39587f83c100af2fe357878b728
8,632
cpp
C++
mediainfo/MediaInfoLib/Source/MediaInfo/Audio/File_Ape.cpp
pavel-pimenov/sandbox
d29b6cb42f93953d36dfc648cdd168e90c9daf83
[ "MIT" ]
null
null
null
mediainfo/MediaInfoLib/Source/MediaInfo/Audio/File_Ape.cpp
pavel-pimenov/sandbox
d29b6cb42f93953d36dfc648cdd168e90c9daf83
[ "MIT" ]
null
null
null
mediainfo/MediaInfoLib/Source/MediaInfo/Audio/File_Ape.cpp
pavel-pimenov/sandbox
d29b6cb42f93953d36dfc648cdd168e90c9daf83
[ "MIT" ]
null
null
null
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_APE_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Audio/File_Ape.h" using namespace std; using namespace ZenLib; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Infos //*************************************************************************** //--------------------------------------------------------------------------- int32u Ape_SamplesPerFrame(int16u Version, int16u CompressionLevel) { if (Version>=3950) return 73728*4; else if (Version>=3900) return 73728; else if (Version>=3800 && CompressionLevel==4000) return 73728; else return 9216; } //--------------------------------------------------------------------------- const char* Ape_Codec_Settings(int16u Setting) { switch (Setting) { case 1000 : return "Fast"; case 2000 : return "Normal"; case 3000 : return "High"; case 4000 : return "Extra-high"; case 5000 : return "Insane"; default : return ""; } } //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- File_Ape::File_Ape() :File__Analyze(), File__Tags_Helper() { //File__Tags_Helper Base=this; } //*************************************************************************** // Streams management //*************************************************************************** //--------------------------------------------------------------------------- void File_Ape::Streams_Finish() { //Filling int64u CompressedSize=File_Size-TagsSize; float32 CompressionRatio=((float32)UncompressedSize)/CompressedSize; int64u BitRate=Duration?(CompressedSize*8*1000/Duration):0; Fill(Stream_Audio, 0, Audio_Compression_Ratio, CompressionRatio); Fill(Stream_Audio, 0, Audio_BitRate, BitRate); File__Tags_Helper::Streams_Finish(); } //*************************************************************************** // Buffer //*************************************************************************** //--------------------------------------------------------------------------- bool File_Ape::FileHeader_Begin() { if (!File__Tags_Helper::FileHeader_Begin()) return false; //Testing if (Buffer_Size<Buffer_Offset+4) return false; if (Buffer[Buffer_Offset ]!=0x4D //"MAC " || Buffer[Buffer_Offset+1]!=0x41 || Buffer[Buffer_Offset+2]!=0x43 || Buffer[Buffer_Offset+3]!=0x20) { File__Tags_Helper::Reject("APE"); return false; } return true; } //--------------------------------------------------------------------------- void File_Ape::FileHeader_Parse() { //Parsing int32u SampleRate=0, TotalFrames=0, FinalFrameSamples=0, SamplesPerFrame=0, SeekElements; int16u Version, CompressionLevel=0, Flags=0, Channels=0, Resolution=0; Skip_C4( "Identifier"); Get_L2 (Version, "Version"); if (Version<3980) //<3.98 { bool Resolution8=false, Resolution24=false, no_wav_header; Get_L2 (CompressionLevel, "CompressionLevel"); Param_Info1(Ape_Codec_Settings(CompressionLevel)); Get_L2 (Flags, "FormatFlags"); Get_Flags (Flags, 0, Resolution8, "8-bit"); Skip_Flags(Flags, 1, "crc-32"); Skip_Flags(Flags, 2, "peak_level"); Get_Flags (Flags, 3, Resolution24, "24-bit"); Skip_Flags(Flags, 4, "seek_elements"); Get_Flags (Flags, 5, no_wav_header, "no_wav_header"); if (Resolution8) Resolution=8; else if (Resolution24) Resolution=24; else Resolution=16; Get_L2 (Channels, "Channels"); Get_L4 (SampleRate, "SampleRate"); Skip_L4( "WavHeaderDataBytes"); Skip_L4( "WavTerminatingBytes"); Get_L4 (TotalFrames, "TotalFrames"); Get_L4 (FinalFrameSamples, "FinalFrameSamples"); SamplesPerFrame=Ape_SamplesPerFrame(Version, CompressionLevel); Skip_L4( "PeakLevel"); Get_L4 (SeekElements, "SeekElements"); if (!no_wav_header) Skip_XX(44, "RIFF header"); Skip_XX(SeekElements*4, "Seek table"); } else { Skip_L2( "Version_High"); Skip_L4( "DescriptorBytes"); Skip_L4( "HeaderBytes"); Skip_L4( "SeekTableBytes"); Skip_L4( "WavHeaderDataBytes"); Skip_L4( "APEFrameDataBytes"); Skip_L4( "APEFrameDataBytesHigh"); Skip_L4( "WavTerminatingDataBytes"); Skip_L16( "FileMD5"); Get_L2 (CompressionLevel, "CompressionLevel"); Param_Info1(Ape_Codec_Settings(CompressionLevel)); Get_L2 (Flags, "FormatFlags"); Get_L4 (SamplesPerFrame, "BlocksPerFrame"); Get_L4 (FinalFrameSamples, "FinalFrameBlocks"); Get_L4 (TotalFrames, "TotalFrames"); Get_L2 (Resolution, "BitsPerSample"); Get_L2 (Channels, "Channels"); Get_L4 (SampleRate, "SampleRate"); } FILLING_BEGIN(); //Coherancy int32u Samples=(TotalFrames-1)*SamplesPerFrame+FinalFrameSamples; if (Samples==0 || SampleRate==0 || Channels==0 || Resolution==0) { File__Tags_Helper::Reject("APE"); return; } //Filling File__Tags_Helper::Accept("APE"); File__Tags_Helper::Streams_Fill(); Duration=((int64u)Samples)*1000/SampleRate; UncompressedSize=Samples*Channels*(Resolution/8); File__Tags_Helper::Stream_Prepare(Stream_Audio); Fill(Stream_Audio, 0, Audio_Format, "Monkey's Audio"); Fill(Stream_Audio, 0, Audio_Encoded_Library_Settings, Ape_Codec_Settings(CompressionLevel)); Fill(Stream_Audio, 0, Audio_Codec, "APE"); Fill(Stream_Audio, 0, Audio_BitDepth, Resolution); Fill(Stream_Audio, 0, Audio_Channel_s_, Channels); Fill(Stream_Audio, 0, Audio_SamplingRate, SampleRate); Fill(Stream_Audio, 0, Audio_Duration, Duration); //No more need data File__Tags_Helper::Finish("APE"); FILLING_END(); } } //NameSpace #endif //MEDIAINFO_APE_YES
40.909953
135
0.41323
pavel-pimenov
81e4b5a4aec9a4379f523c26dfc488ec3dab5633
3,334
cpp
C++
Day Two/DayTwo.cpp
Heartbroken-Git/Advent-Code-2017
d7284621983693e2bbd88b021912a401a480494f
[ "WTFPL" ]
null
null
null
Day Two/DayTwo.cpp
Heartbroken-Git/Advent-Code-2017
d7284621983693e2bbd88b021912a401a480494f
[ "WTFPL" ]
null
null
null
Day Two/DayTwo.cpp
Heartbroken-Git/Advent-Code-2017
d7284621983693e2bbd88b021912a401a480494f
[ "WTFPL" ]
null
null
null
#include <iostream> using namespace std; const int NB_ROWS = 16; const int NB_COLS = 16; const int INPUT[NB_ROWS][NB_COLS] = {{5048, 177, 5280, 5058, 4504, 3805, 5735, 220, 4362, 1809, 1521, 230, 772, 1088, 178, 1794}, {6629, 3839, 258, 4473, 5961, 6539, 6870, 4140, 4638, 387, 7464, 229, 4173, 5706, 185, 271}, {5149, 2892, 5854, 2000, 256, 3995, 5250, 249, 3916, 184, 2497, 210, 4601, 3955, 1110, 5340}, {153, 468, 550, 126, 495, 142, 385, 144, 165, 188, 609, 182, 439, 545, 608, 319}, {1123, 104, 567, 1098, 286, 665, 1261, 107, 227, 942, 1222, 128, 1001, 122, 69, 139}, {111, 1998, 1148, 91, 1355, 90, 202, 1522, 1496, 1362, 1728, 109, 2287, 918, 2217, 1138}, {426, 372, 489, 226, 344, 431, 67, 124, 120, 386, 348, 153, 242, 133, 112, 369}, {1574, 265, 144, 2490, 163, 749, 3409, 3086, 154, 151, 133, 990, 1002, 3168, 588, 2998}, {173, 192, 2269, 760, 1630, 215, 966, 2692, 3855, 3550, 468, 4098, 3071, 162, 329, 3648}, {1984, 300, 163, 5616, 4862, 586, 4884, 239, 1839, 169, 5514, 4226, 5551, 3700, 216, 5912}, {1749, 2062, 194, 1045, 2685, 156, 3257, 1319, 3199, 2775, 211, 213, 1221, 198, 2864, 2982}, {273, 977, 89, 198, 85, 1025, 1157, 1125, 69, 94, 919, 103, 1299, 998, 809, 478}, {1965, 6989, 230, 2025, 6290, 2901, 192, 215, 4782, 6041, 6672, 7070, 7104, 207, 7451, 5071}, {1261, 77, 1417, 1053, 2072, 641, 74, 86, 91, 1878, 1944, 2292, 1446, 689, 2315, 1379}, {296, 306, 1953, 3538, 248, 1579, 4326, 2178, 5021, 2529, 794, 5391, 4712, 3734, 261, 4362}, {2426, 192, 1764, 288, 4431, 2396, 2336, 854, 2157, 216, 4392, 3972, 229, 244, 4289, 1902}}; // PART ONE int answerPartOne(const int input[NB_ROWS][NB_COLS]) { int results = 0; for (int i = 0; i < NB_ROWS; i++) { int min = 99999999; int max = 0; for (int j = 0; j < NB_COLS; j++) { if (input[i][j] < min) { min = input[i][j]; } if (input[i][j] > max) { max = input[i][j]; } } results += max - min; } return results; } // PART TWO int returnDivided(const int row[NB_COLS]) { for (int i = 0; i < NB_COLS; i++) { for (int j = 0; j < i; j++) { if (row[i] % row[j] == 0) { return row[i] / row[j]; } } for (int j = i + 1; j < NB_COLS; j++) { if (row[i] % row[j] == 0) { return row[i] / row[j]; } } } } int answerPartTwo(const int input[NB_ROWS][NB_COLS]) { int results = 0; for (int i = 0; i < NB_ROWS; i++) { results += returnDivided(INPUT[i]); } return results; } // MAIN int main() { cout << "Answer for Part One = " << answerPartOne(INPUT) << endl; cout << "Answer for Part Two = " << answerPartTwo(INPUT) << endl; return 0; }
42.74359
129
0.454709
Heartbroken-Git
81e8a29839be1131be37ec1eae739962694fe642
22,846
cc
C++
squid/squid3-3.3.8.spaceify/src/comm/ModSelect.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/comm/ModSelect.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/comm/ModSelect.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 05 Socket Functions * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * */ #include "squid.h" #if USE_SELECT #include "anyp/PortCfg.h" #include "comm/Connection.h" #include "comm/Loops.h" #include "fde.h" #include "globals.h" #include "ICP.h" #include "mgr/Registration.h" #include "SquidTime.h" #include "StatCounters.h" #include "StatHist.h" #include "Store.h" #include "SquidConfig.h" #if HAVE_SYS_STAT_H #include <sys/stat.h> #endif #if HAVE_ERRNO_H #include <errno.h> #endif static int MAX_POLL_TIME = 1000; /* see also Comm::QuickPollRequired() */ #ifndef howmany #define howmany(x, y) (((x)+((y)-1))/(y)) #endif #ifndef NBBY #define NBBY 8 #endif #define FD_MASK_BYTES sizeof(fd_mask) #define FD_MASK_BITS (FD_MASK_BYTES*NBBY) /* STATIC */ static int examine_select(fd_set *, fd_set *); static int fdIsTcpListener(int fd); static int fdIsUdpListener(int fd); static int fdIsDns(int fd); static OBJH commIncomingStats; static int comm_check_incoming_select_handlers(int nfds, int *fds); static void comm_select_dns_incoming(void); static void commUpdateReadBits(int fd, PF * handler); static void commUpdateWriteBits(int fd, PF * handler); static struct timeval zero_tv; static fd_set global_readfds; static fd_set global_writefds; static int nreadfds; static int nwritefds; /* * Automatic tuning for incoming requests: * * INCOMING sockets are the ICP and HTTP ports. We need to check these * fairly regularly, but how often? When the load increases, we * want to check the incoming sockets more often. If we have a lot * of incoming ICP, then we need to check these sockets more than * if we just have HTTP. * * The variables 'incoming_udp_interval' and 'incoming_tcp_interval' * determine how many normal I/O events to process before checking * incoming sockets again. Note we store the incoming_interval * multipled by a factor of (2^INCOMING_FACTOR) to have some * pseudo-floating point precision. * * The variable 'udp_io_events' and 'tcp_io_events' counts how many normal * I/O events have been processed since the last check on the incoming * sockets. When io_events > incoming_interval, its time to check incoming * sockets. * * Every time we check incoming sockets, we count how many new messages * or connections were processed. This is used to adjust the * incoming_interval for the next iteration. The new incoming_interval * is calculated as the current incoming_interval plus what we would * like to see as an average number of events minus the number of * events just processed. * * incoming_interval = incoming_interval + target_average - number_of_events_processed * * There are separate incoming_interval counters for DNS, UDP and TCP events * * You can see the current values of the incoming_interval's, as well as * a histogram of 'incoming_events' by asking the cache manager * for 'comm_incoming', e.g.: * * % ./client mgr:comm_incoming * * Caveats: * * - We have MAX_INCOMING_INTEGER as a magic upper limit on * incoming_interval for both types of sockets. At the * largest value the cache will effectively be idling. * * - The higher the INCOMING_FACTOR, the slower the algorithm will * respond to load spikes/increases/decreases in demand. A value * between 3 and 8 is recommended. */ #define MAX_INCOMING_INTEGER 256 #define INCOMING_FACTOR 5 #define MAX_INCOMING_INTERVAL (MAX_INCOMING_INTEGER << INCOMING_FACTOR) static int udp_io_events = 0; static int dns_io_events = 0; static int tcp_io_events = 0; static int incoming_udp_interval = 16 << INCOMING_FACTOR; static int incoming_dns_interval = 16 << INCOMING_FACTOR; static int incoming_tcp_interval = 16 << INCOMING_FACTOR; #define commCheckUdpIncoming (++udp_io_events > (incoming_udp_interval>> INCOMING_FACTOR)) #define commCheckDnsIncoming (++dns_io_events > (incoming_dns_interval>> INCOMING_FACTOR)) #define commCheckTcpIncoming (++tcp_io_events > (incoming_tcp_interval>> INCOMING_FACTOR)) void Comm::SetSelect(int fd, unsigned int type, PF * handler, void *client_data, time_t timeout) { fde *F = &fd_table[fd]; assert(fd >= 0); assert(F->flags.open); debugs(5, 5, HERE << "FD " << fd << ", type=" << type << ", handler=" << handler << ", client_data=" << client_data << ", timeout=" << timeout); if (type & COMM_SELECT_READ) { F->read_handler = handler; F->read_data = client_data; commUpdateReadBits(fd, handler); } if (type & COMM_SELECT_WRITE) { F->write_handler = handler; F->write_data = client_data; commUpdateWriteBits(fd, handler); } if (timeout) F->timeout = squid_curtime + timeout; } void Comm::ResetSelect(int fd) { } static int fdIsUdpListener(int fd) { if (icpIncomingConn != NULL && fd == icpIncomingConn->fd) return 1; if (icpOutgoingConn != NULL && fd == icpOutgoingConn->fd) return 1; return 0; } static int fdIsDns(int fd) { if (fd == DnsSocketA) return 1; if (fd == DnsSocketB) return 1; return 0; } static int fdIsTcpListener(int fd) { for (const AnyP::PortCfg *s = Config.Sockaddr.http; s; s = s->next) { if (s->listenConn != NULL && s->listenConn->fd == fd) return 1; } return 0; } static int comm_check_incoming_select_handlers(int nfds, int *fds) { int i; int fd; int maxfd = 0; PF *hdl = NULL; fd_set read_mask; fd_set write_mask; FD_ZERO(&read_mask); FD_ZERO(&write_mask); incoming_sockets_accepted = 0; for (i = 0; i < nfds; ++i) { fd = fds[i]; if (fd_table[fd].read_handler) { FD_SET(fd, &read_mask); if (fd > maxfd) maxfd = fd; } if (fd_table[fd].write_handler) { FD_SET(fd, &write_mask); if (fd > maxfd) maxfd = fd; } } if (maxfd++ == 0) return -1; getCurrentTime(); ++ statCounter.syscalls.selects; if (select(maxfd, &read_mask, &write_mask, NULL, &zero_tv) < 1) return incoming_sockets_accepted; for (i = 0; i < nfds; ++i) { fd = fds[i]; if (FD_ISSET(fd, &read_mask)) { if ((hdl = fd_table[fd].read_handler) != NULL) { fd_table[fd].read_handler = NULL; commUpdateReadBits(fd, NULL); hdl(fd, fd_table[fd].read_data); } else { debugs(5, DBG_IMPORTANT, "comm_select_incoming: FD " << fd << " NULL read handler"); } } if (FD_ISSET(fd, &write_mask)) { if ((hdl = fd_table[fd].write_handler) != NULL) { fd_table[fd].write_handler = NULL; commUpdateWriteBits(fd, NULL); hdl(fd, fd_table[fd].write_data); } else { debugs(5, DBG_IMPORTANT, "comm_select_incoming: FD " << fd << " NULL write handler"); } } } return incoming_sockets_accepted; } static void comm_select_udp_incoming(void) { int nfds = 0; int fds[2]; int nevents; udp_io_events = 0; if (Comm::IsConnOpen(icpIncomingConn)) { fds[nfds] = icpIncomingConn->fd; ++nfds; } if (Comm::IsConnOpen(icpOutgoingConn) && icpIncomingConn != icpOutgoingConn) { fds[nfds] = icpOutgoingConn->fd; ++nfds; } if (nfds == 0) return; nevents = comm_check_incoming_select_handlers(nfds, fds); incoming_udp_interval += Config.comm_incoming.udp.average - nevents; if (incoming_udp_interval < 0) incoming_udp_interval = 0; if (incoming_udp_interval > MAX_INCOMING_INTERVAL) incoming_udp_interval = MAX_INCOMING_INTERVAL; if (nevents > INCOMING_UDP_MAX) nevents = INCOMING_UDP_MAX; statCounter.comm_udp_incoming.count(nevents); } static void comm_select_tcp_incoming(void) { int nfds = 0; int fds[MAXTCPLISTENPORTS]; int nevents; tcp_io_events = 0; // XXX: only poll sockets that won't be deferred. But how do we identify them? for (const AnyP::PortCfg *s = Config.Sockaddr.http; s; s = s->next) { if (Comm::IsConnOpen(s->listenConn)) { fds[nfds] = s->listenConn->fd; ++nfds; } } nevents = comm_check_incoming_select_handlers(nfds, fds); incoming_tcp_interval += Config.comm_incoming.tcp.average - nevents; if (incoming_tcp_interval < 0) incoming_tcp_interval = 0; if (incoming_tcp_interval > MAX_INCOMING_INTERVAL) incoming_tcp_interval = MAX_INCOMING_INTERVAL; if (nevents > INCOMING_TCP_MAX) nevents = INCOMING_TCP_MAX; statCounter.comm_tcp_incoming.count(nevents); } #define DEBUG_FDBITS 0 /* Select on all sockets; call handlers for those that are ready. */ comm_err_t Comm::DoSelect(int msec) { fd_set readfds; fd_set pendingfds; fd_set writefds; PF *hdl = NULL; int fd; int maxfd; int num; int pending; int calldns = 0, calludp = 0, calltcp = 0; int maxindex; unsigned int k; int j; #if DEBUG_FDBITS int i; #endif fd_mask *fdsp; fd_mask *pfdsp; fd_mask tmask; struct timeval poll_time; double timeout = current_dtime + (msec / 1000.0); fde *F; do { double start; getCurrentTime(); start = current_dtime; if (commCheckUdpIncoming) comm_select_udp_incoming(); if (commCheckDnsIncoming) comm_select_dns_incoming(); if (commCheckTcpIncoming) comm_select_tcp_incoming(); calldns = calludp = calltcp = 0; maxfd = Biggest_FD + 1; memcpy(&readfds, &global_readfds, howmany(maxfd, FD_MASK_BITS) * FD_MASK_BYTES); memcpy(&writefds, &global_writefds, howmany(maxfd, FD_MASK_BITS) * FD_MASK_BYTES); /* remove stalled FDs, and deal with pending descriptors */ pending = 0; FD_ZERO(&pendingfds); maxindex = howmany(maxfd, FD_MASK_BITS); fdsp = (fd_mask *) & readfds; for (j = 0; j < maxindex; ++j) { if ((tmask = fdsp[j]) == 0) continue; /* no bits here */ for (k = 0; k < FD_MASK_BITS; ++k) { if (!EBIT_TEST(tmask, k)) continue; /* Found a set bit */ fd = (j * FD_MASK_BITS) + k; if (FD_ISSET(fd, &readfds) && fd_table[fd].flags.read_pending) { FD_SET(fd, &pendingfds); ++pending; } } } #if DEBUG_FDBITS for (i = 0; i < maxfd; ++i) { /* Check each open socket for a handler. */ if (fd_table[i].read_handler) { assert(FD_ISSET(i, &readfds)); } if (fd_table[i].write_handler) { assert(FD_ISSET(i, &writefds)); } } #endif if (nreadfds + nwritefds == 0) { assert(shutting_down); return COMM_SHUTDOWN; } if (msec > MAX_POLL_TIME) msec = MAX_POLL_TIME; if (pending) msec = 0; for (;;) { poll_time.tv_sec = msec / 1000; poll_time.tv_usec = (msec % 1000) * 1000; ++ statCounter.syscalls.selects; num = select(maxfd, &readfds, &writefds, NULL, &poll_time); ++ statCounter.select_loops; if (num >= 0 || pending > 0) break; if (ignoreErrno(errno)) break; debugs(5, DBG_CRITICAL, "comm_select: select failure: " << xstrerror()); examine_select(&readfds, &writefds); return COMM_ERROR; /* NOTREACHED */ } if (num < 0 && !pending) continue; getCurrentTime(); debugs(5, num ? 5 : 8, "comm_select: " << num << "+" << pending << " FDs ready"); statCounter.select_fds_hist.count(num); if (num == 0 && pending == 0) continue; /* Scan return fd masks for ready descriptors */ fdsp = (fd_mask *) & readfds; pfdsp = (fd_mask *) & pendingfds; maxindex = howmany(maxfd, FD_MASK_BITS); for (j = 0; j < maxindex; ++j) { if ((tmask = (fdsp[j] | pfdsp[j])) == 0) continue; /* no bits here */ for (k = 0; k < FD_MASK_BITS; ++k) { if (tmask == 0) break; /* no more bits left */ if (!EBIT_TEST(tmask, k)) continue; /* Found a set bit */ fd = (j * FD_MASK_BITS) + k; EBIT_CLR(tmask, k); /* this will be done */ #if DEBUG_FDBITS debugs(5, 9, "FD " << fd << " bit set for reading"); assert(FD_ISSET(fd, &readfds)); #endif if (fdIsUdpListener(fd)) { calludp = 1; continue; } if (fdIsDns(fd)) { calldns = 1; continue; } if (fdIsTcpListener(fd)) { calltcp = 1; continue; } F = &fd_table[fd]; debugs(5, 6, "comm_select: FD " << fd << " ready for reading"); if (NULL == (hdl = F->read_handler)) (void) 0; else { F->read_handler = NULL; F->flags.read_pending = 0; commUpdateReadBits(fd, NULL); hdl(fd, F->read_data); ++ statCounter.select_fds; if (commCheckUdpIncoming) comm_select_udp_incoming(); if (commCheckDnsIncoming) comm_select_dns_incoming(); if (commCheckTcpIncoming) comm_select_tcp_incoming(); } } } fdsp = (fd_mask *) & writefds; for (j = 0; j < maxindex; ++j) { if ((tmask = fdsp[j]) == 0) continue; /* no bits here */ for (k = 0; k < FD_MASK_BITS; ++k) { if (tmask == 0) break; /* no more bits left */ if (!EBIT_TEST(tmask, k)) continue; /* Found a set bit */ fd = (j * FD_MASK_BITS) + k; EBIT_CLR(tmask, k); /* this will be done */ #if DEBUG_FDBITS debugs(5, 9, "FD " << fd << " bit set for writing"); assert(FD_ISSET(fd, &writefds)); #endif if (fdIsUdpListener(fd)) { calludp = 1; continue; } if (fdIsDns(fd)) { calldns = 1; continue; } if (fdIsTcpListener(fd)) { calltcp = 1; continue; } F = &fd_table[fd]; debugs(5, 6, "comm_select: FD " << fd << " ready for writing"); if ((hdl = F->write_handler)) { F->write_handler = NULL; commUpdateWriteBits(fd, NULL); hdl(fd, F->write_data); ++ statCounter.select_fds; if (commCheckUdpIncoming) comm_select_udp_incoming(); if (commCheckDnsIncoming) comm_select_dns_incoming(); if (commCheckTcpIncoming) comm_select_tcp_incoming(); } } } if (calludp) comm_select_udp_incoming(); if (calldns) comm_select_dns_incoming(); if (calltcp) comm_select_tcp_incoming(); getCurrentTime(); statCounter.select_time += (current_dtime - start); return COMM_OK; } while (timeout > current_dtime); debugs(5, 8, "comm_select: time out: " << squid_curtime); return COMM_TIMEOUT; } static void comm_select_dns_incoming(void) { int nfds = 0; int fds[3]; int nevents; dns_io_events = 0; if (DnsSocketA < 0 && DnsSocketB < 0) return; if (DnsSocketA >= 0) { fds[nfds] = DnsSocketA; ++nfds; } if (DnsSocketB >= 0) { fds[nfds] = DnsSocketB; ++nfds; } nevents = comm_check_incoming_select_handlers(nfds, fds); if (nevents < 0) return; incoming_dns_interval += Config.comm_incoming.dns.average - nevents; if (incoming_dns_interval < Config.comm_incoming.dns.min_poll) incoming_dns_interval = Config.comm_incoming.dns.min_poll; if (incoming_dns_interval > MAX_INCOMING_INTERVAL) incoming_dns_interval = MAX_INCOMING_INTERVAL; if (nevents > INCOMING_DNS_MAX) nevents = INCOMING_DNS_MAX; statCounter.comm_dns_incoming.count(nevents); } void Comm::SelectLoopInit(void) { zero_tv.tv_sec = 0; zero_tv.tv_usec = 0; FD_ZERO(&global_readfds); FD_ZERO(&global_writefds); nreadfds = nwritefds = 0; Mgr::RegisterAction("comm_select_incoming", "comm_incoming() stats", commIncomingStats, 0, 1); } /* * examine_select - debug routine. * * I spend the day chasing this core dump that occurs when both the client * and the server side of a cache fetch simultaneoulsy abort the * connection. While I haven't really studied the code to figure out how * it happens, the snippet below may prevent the cache from exitting: * * Call this from where the select loop fails. */ static int examine_select(fd_set * readfds, fd_set * writefds) { int fd = 0; fd_set read_x; fd_set write_x; struct timeval tv; AsyncCall::Pointer ch = NULL; fde *F = NULL; struct stat sb; debugs(5, DBG_CRITICAL, "examine_select: Examining open file descriptors..."); for (fd = 0; fd < Squid_MaxFD; ++fd) { FD_ZERO(&read_x); FD_ZERO(&write_x); tv.tv_sec = tv.tv_usec = 0; if (FD_ISSET(fd, readfds)) FD_SET(fd, &read_x); else if (FD_ISSET(fd, writefds)) FD_SET(fd, &write_x); else continue; ++ statCounter.syscalls.selects; errno = 0; if (!fstat(fd, &sb)) { debugs(5, 5, "FD " << fd << " is valid."); continue; } F = &fd_table[fd]; debugs(5, DBG_CRITICAL, "FD " << fd << ": " << xstrerror()); debugs(5, DBG_CRITICAL, "WARNING: FD " << fd << " has handlers, but it's invalid."); debugs(5, DBG_CRITICAL, "FD " << fd << " is a " << fdTypeStr[F->type] << " called '" << F->desc << "'"); debugs(5, DBG_CRITICAL, "tmout:" << F->timeoutHandler << " read:" << F->read_handler << " write:" << F->write_handler); for (ch = F->closeHandler; ch != NULL; ch = ch->Next()) debugs(5, DBG_CRITICAL, " close handler: " << ch); if (F->closeHandler != NULL) { commCallCloseHandlers(fd); } else if (F->timeoutHandler != NULL) { debugs(5, DBG_CRITICAL, "examine_select: Calling Timeout Handler"); ScheduleCallHere(F->timeoutHandler); } F->closeHandler = NULL; F->timeoutHandler = NULL; F->read_handler = NULL; F->write_handler = NULL; FD_CLR(fd, readfds); FD_CLR(fd, writefds); } return 0; } static void commIncomingStats(StoreEntry * sentry) { storeAppendPrintf(sentry, "Current incoming_udp_interval: %d\n", incoming_udp_interval >> INCOMING_FACTOR); storeAppendPrintf(sentry, "Current incoming_dns_interval: %d\n", incoming_dns_interval >> INCOMING_FACTOR); storeAppendPrintf(sentry, "Current incoming_tcp_interval: %d\n", incoming_tcp_interval >> INCOMING_FACTOR); storeAppendPrintf(sentry, "\n"); storeAppendPrintf(sentry, "Histogram of events per incoming socket type\n"); storeAppendPrintf(sentry, "ICP Messages handled per comm_select_udp_incoming() call:\n"); statCounter.comm_udp_incoming.dump(sentry, statHistIntDumper); storeAppendPrintf(sentry, "DNS Messages handled per comm_select_dns_incoming() call:\n"); statCounter.comm_dns_incoming.dump(sentry, statHistIntDumper); storeAppendPrintf(sentry, "HTTP Messages handled per comm_select_tcp_incoming() call:\n"); statCounter.comm_tcp_incoming.dump(sentry, statHistIntDumper); } void commUpdateReadBits(int fd, PF * handler) { if (handler && !FD_ISSET(fd, &global_readfds)) { FD_SET(fd, &global_readfds); ++nreadfds; } else if (!handler && FD_ISSET(fd, &global_readfds)) { FD_CLR(fd, &global_readfds); --nreadfds; } } void commUpdateWriteBits(int fd, PF * handler) { if (handler && !FD_ISSET(fd, &global_writefds)) { FD_SET(fd, &global_writefds); ++nwritefds; } else if (!handler && FD_ISSET(fd, &global_writefds)) { FD_CLR(fd, &global_writefds); --nwritefds; } } /* Called by async-io or diskd to speed up the polling */ void Comm::QuickPollRequired(void) { MAX_POLL_TIME = 10; } #endif /* USE_SELECT */
27.997549
127
0.582597
spaceify
81e90055a4fd33b8c83255a27cc7bf0879e2e687
1,527
inl
C++
lib/nimg/pixel.inl
4rknova/asciimg
f907d530c3f7bb22e4b374da2e5d4cb6308a78eb
[ "MIT" ]
3
2017-12-01T09:39:27.000Z
2021-03-23T06:02:41.000Z
lib/nimg/pixel.inl
4rknova/asciimg
f907d530c3f7bb22e4b374da2e5d4cb6308a78eb
[ "MIT" ]
1
2022-03-05T23:39:57.000Z
2022-03-05T23:41:41.000Z
lib/nimg/pixel.inl
4rknova/asciimg
f907d530c3f7bb22e4b374da2e5d4cb6308a78eb
[ "MIT" ]
null
null
null
#ifndef NIMG_PIXEL_INL_INCLUDED #define NIMG_PIXEL_INL_INCLUDED #ifndef NIMG_PIXEL_H_INCLUDED error "pixel.h must be included before pixel.inl" #endif /* NIMG_PIXEL_H_INCLUDED */ namespace nimg { namespace util { #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ static inline pixel32_t rgba_c_to_pixel32(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { return (pixel32_t)(((uint32_t)r << 24) + ((uint32_t)g << 16) + ((uint32_t)b << 8) + (uint32_t)a); } static inline pixel32_t rgba_f_to_pixel32(scalar_t r, scalar_t g, scalar_t b, scalar_t a) { pixel32_t pix = 0; /* Do some basic tone mapping. */ scalar_t fmax = 0.0f; fmax = r > fmax ? r : fmax; fmax = g > fmax ? g : fmax; fmax = b > fmax ? b : fmax; scalar_t scale = 1.0f; if (fmax > 1.0f) { scale = 1.f / fmax; } scalar_t cr = r * scale * 255.0f; scalar_t cg = g * scale * 255.0f; scalar_t cb = b * scale * 255.0f; pix = rgba_c_to_pixel32((char)cr, (char)cg, (char)cb, (char)ca); return pix; } static inline unsigned char get_pixel32_r(pixel32_t c) { return (c & 0xFF000000) >> 24; } static inline unsigned char get_pixel32_g(pixel32_t c) { return (c & 0x00FF0000) >> 16; } static inline unsigned char get_pixel32_b(pixel32_t c) { return (c & 0x0000FF00) >> 8; } static inline unsigned char get_pixel32_a(pixel32_t c) { return c & 0x000000FF; } #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ } /* namespace util */ } /* namespace nimg */ #endif /* NIMG_PIXEL_INL_INCLUDED */
21.208333
109
0.67649
4rknova
81ef98d6692e4cd62fb3ee57abf026e58c6d2230
2,350
cc
C++
src/firstGreedy.cc
vanessavvp/DAA-pr07-parallel-machine-scheduling-problem
f5d5d1fb9e1b2abe0bafa3d1ce5ddfa79535fb02
[ "MIT" ]
null
null
null
src/firstGreedy.cc
vanessavvp/DAA-pr07-parallel-machine-scheduling-problem
f5d5d1fb9e1b2abe0bafa3d1ce5ddfa79535fb02
[ "MIT" ]
null
null
null
src/firstGreedy.cc
vanessavvp/DAA-pr07-parallel-machine-scheduling-problem
f5d5d1fb9e1b2abe0bafa3d1ce5ddfa79535fb02
[ "MIT" ]
1
2021-05-08T08:48:49.000Z
2021-05-08T08:48:49.000Z
/** * PROJECT HEADER * @input firstGreedy.cc * @author: Vanessa Valentina Villalba Perez * Contact: alu0101265704@ull.edu.es * @date: 24/04/2021 * Subject: Diseño y Análisis de Algoritmos * Practice: Numberº7 * Purpose: Parallel Machine Scheduling Problem with Dependent Setup Times */ #include "../include/firstGreedy.h" Solution FirstGreedy::execute(Problem problem) { Solution solution(problem.getNumberOfMachines()); int taskDone = 0; // First part - Finds the smallests values for the total time and adds the task for (int i = 0; i < solution.getSize(); i++) { Task firstTask = problem.findTaskWithLessTotalTime(0); int firstTaskIndex = firstTask.getTaskID(); solution[i].setTask(problem.getTasksMatrix()[0][firstTaskIndex]); problem.setTaskExecuted(firstTaskIndex); solution[i].setTCT(firstTask.getTotalTime()); taskDone++; } problem.setTaskExecuted(0); // Second part while (taskDone < problem.getNumberOfTasks()) { int lessIncrement = INT16_MAX; int increment = INT16_MAX; int bestTaskPosition = 0; int possibleTCT = 0; int bestMachine = 0; std::vector<Task> tasksCopy; Task bestTask; for (int i = 0; i < solution.getSize(); i++) { for (int j = 0; j < solution[i].getTasks().size(); j++){ int actualTask = solution[i].getTasks()[j].getTaskID(); for (int k = 1; k <= problem.getNumberOfTasks(); k++) { Task task = problem.getTasksMatrix()[actualTask][k]; if (task.isExecuted() == false) { possibleTCT = solution.evaluateObjectiveFunction(task, i, j + 1); increment = possibleTCT - solution[i].getTCT(); // Finds the leaser increment that a specific task could add // and stores the values where it will be added inside the // solution if (increment < lessIncrement) { bestMachine = solution[i].getMachineID(); lessIncrement = increment; bestTaskPosition = j + 1; bestTask = task; } } } } } problem.setTaskExecuted(bestTask.getTaskID()); solution[bestMachine].setTaskPosition(bestTask, bestTaskPosition); solution[bestMachine].calculateTCT(); solution.calculateObjectiveFunction(); taskDone++; } return solution; }
34.057971
81
0.640426
vanessavvp
81f1ae6b0896471187f2460c9d4fc9e419b76f4e
1,043
cpp
C++
src/diff/deltas/type_members_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
3
2017-07-02T08:33:22.000Z
2019-03-16T00:48:11.000Z
src/diff/deltas/type_members_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
null
null
null
src/diff/deltas/type_members_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
null
null
null
#include "type_members_delta.hpp" #include "../../json_writer.hpp" #include "../../unity_type.hpp" namespace zizany { type_members_delta::type_members_delta(const delta_set_operation operation_, const type_identity &identity_, const member_path &path_, const unity_type &added_type_) : delta(), operation(operation_), identity(identity_), path(path_), added_type(added_type_) { } void type_members_delta::print_action(json_writer &writer) const { writer.add_string(operation == delta_set_operation::add ? "add type member" : "remove type member"); } void type_members_delta::print_details(json_writer &writer) const { writer.start_object(); writer.add_key("identity"); identity.print(writer); writer.add_key("path"); path.print(writer); writer.add_key("added_type"); added_type.print(writer, /*print_defaults:*/false, /*print_magic:*/true); writer.end_object(); } }
31.606061
169
0.644295
kmichel
81f3c68269f137abe299445e7d4e033b8559e4cf
1,669
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/main(7).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/main(7).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/main(7).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include <iostream> #include "UnsortedType.cpp" using namespace std; int main() { UnsortedType<int> List; int items; cout<<"Enter four items: "<<endl; for(int i=0;i<4;i++) { cin>>items; List.InsertItem(items); } cout<<endl; int temp; for(int i=0;i<4;i++) { List.GetNextItem(temp); cout<< temp<<" "; } int length = List.LengthIs(); cout<<"\nList length is: "<<length<<endl; List.InsertItem(1); int v = 4 ; bool f = true ; List.RetrieveItem(v,f); if (f == true) { cout<<"Item is not found"<<endl; } else { cout<<"Item not found"<<endl; } int v1 = 5 ; bool f1 = true ; List.RetrieveItem(v1,f1); if (f1 == true) { cout<<"Item is found"<<endl; } else { cout<<"Item not found"<<endl; } int v2 = 9 ; bool f2 = true ; List.RetrieveItem(v2,f2); if (f2 == true) { cout<<"Item is found"<<endl; } else { cout<<"Item not found"<<endl; } int v3 = 10 ; bool f3 = true ; List.RetrieveItem(v3,f3); if (f3 == true) { cout<<"Item is found"<<endl; } else { cout<<"Item not found"<<endl; } bool full = List.IsFull(); if (full == true) { cout<<"List is full"<<endl; ; } else { cout<<"List not full"<<endl; } List.DeleteItem(5); bool full1 = List.IsFull(); if (full1 == true) { cout<<"List is full"<<endl; ; } else { cout<<"List not full"<<endl; } List.DeleteItem(6); }
14.144068
45
0.467945
diptu
81f87815db1b02e654663d14117f02b1be4a2a6d
1,147
cpp
C++
TouchGFX/generated/fonts/src/Kerning_trebucbd_40_4bpp.cpp
timagr615/ILI9488_touchGFX
5d3695f09a440edefe3d0ddf727e08c7fd5e5bd2
[ "MIT" ]
null
null
null
TouchGFX/generated/fonts/src/Kerning_trebucbd_40_4bpp.cpp
timagr615/ILI9488_touchGFX
5d3695f09a440edefe3d0ddf727e08c7fd5e5bd2
[ "MIT" ]
null
null
null
TouchGFX/generated/fonts/src/Kerning_trebucbd_40_4bpp.cpp
timagr615/ILI9488_touchGFX
5d3695f09a440edefe3d0ddf727e08c7fd5e5bd2
[ "MIT" ]
null
null
null
#include <touchgfx/Font.hpp> FONT_KERNING_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::KerningNode kerning_trebucbd_40_4bpp[] FONT_KERNING_LOCATION_FLASH_ATTRIBUTE = { { 0x0050, -1 }, // (First char = [0x0050, P], Second char = [0x0020, ], Kerning dist = -1) { 0x0050, -5 }, // (First char = [0x0050, P], Second char = [0x002E, .], Kerning dist = -5) { 0x0057, -3 }, // (First char = [0x0057, W], Second char = [0x002E, .], Kerning dist = -3) { 0x0072, -5 }, // (First char = [0x0072, r], Second char = [0x002E, .], Kerning dist = -5) { 0x0050, -2 }, // (First char = [0x0050, P], Second char = [0x0061, a], Kerning dist = -2) { 0x0057, -1 }, // (First char = [0x0057, W], Second char = [0x0061, a], Kerning dist = -1) { 0x0072, -1 }, // (First char = [0x0072, r], Second char = [0x0061, a], Kerning dist = -1) { 0x0050, -2 }, // (First char = [0x0050, P], Second char = [0x006F, o], Kerning dist = -2) { 0x0057, -1 }, // (First char = [0x0057, W], Second char = [0x006F, o], Kerning dist = -1) { 0x0057, -1 }, // (First char = [0x0057, W], Second char = [0x0072, r], Kerning dist = -1) };
71.6875
108
0.581517
timagr615
81f91e5d62ea1b21dc10f088a614ed54bad12d96
5,850
cpp
C++
MMOCoreORB/src/server/zone/objects/tangible/tool/SurveyToolImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/tangible/tool/SurveyToolImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/tangible/tool/SurveyToolImplementation.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #include "engine/engine.h" #include "server/zone/objects/tangible/tool/SurveyTool.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" #include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h" #include "server/zone/objects/player/sui/SuiWindowType.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "templates/tangible/tool/SurveyToolTemplate.h" #include "server/zone/objects/tangible/tool/sui/SurveyToolSetRangeSuiCallback.h" #include "server/zone/objects/tangible/tool/sui/SurveyToolApproveRadioactiveSuiCallback.h" #include "server/zone/objects/player/sessions/survey/SurveySession.h" void SurveyToolImplementation::loadTemplateData(SharedObjectTemplate* templateData) { TangibleObjectImplementation::loadTemplateData(templateData); SurveyToolTemplate* surveyToolData = dynamic_cast<SurveyToolTemplate*>(templateData); if (surveyToolData == nullptr) { throw Exception("invalid template for SurveyTool"); } type = surveyToolData->getToolType(); surveyType = surveyToolData->getSurveyType(); surveyAnimation = surveyToolData->getSurveyAnimation(); sampleAnimation = surveyToolData->getSampleAnimation(); } void SurveyToolImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { TangibleObjectImplementation::fillObjectMenuResponse(menuResponse, player); menuResponse->addRadialMenuItem(135, 3, "@sui:tool_options"); menuResponse->addRadialMenuItemToRadialID(135,133, 3, "@sui:survey_range"); } int SurveyToolImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { PlayerObject* playerObject = player->getPlayerObject(); if(isASubChildOf(player)) { if (!playerObject->hasAbility("survey")) { player->sendSystemMessage("@error_message:insufficient_skill"); return 0; } if (selectedID == 20) { // use object int range = getRange(player); if(range <= 0) { sendRangeSui(player); return 0; } Locker locker(_this.getReferenceUnsafeStaticCast()); ManagedReference<SurveySession*> session = player->getActiveSession(SessionFacadeType::SURVEY).castTo<SurveySession*>(); if(session == nullptr) { session = new SurveySession(player); session->initializeSession(_this.getReferenceUnsafeStaticCast()); } session->setOpenSurveyTool(_this.getReferenceUnsafeStaticCast()); ManagedReference<ResourceManager*> resourceManager = cast<ResourceManager*>(server->getZoneServer()->getResourceManager()); if(resourceManager == nullptr) { error("null resource manager"); return 0; } resourceManager->sendResourceListForSurvey(player, getToolType(), getSurveyType()); return 0; } if (selectedID == 133) { // Set Tool Range sendRangeSui(player); return 0; } } return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID); } void SurveyToolImplementation::sendRangeSui(CreatureObject* player) { int surveyMod = player->getSkillMod("surveying"); ManagedReference<SuiListBox*> suiToolRangeBox = new SuiListBox(player, SuiWindowType::SURVEY_TOOL_RANGE, 0); suiToolRangeBox->setPromptTitle("@base_player:swg"); suiToolRangeBox->setPromptText("@survey:select_range"); if (surveyMod >= 20) suiToolRangeBox->addMenuItem("64m", 0); if (surveyMod >= 35) suiToolRangeBox->addMenuItem("256m", 1); if (surveyMod >= 55) suiToolRangeBox->addMenuItem("512m", 2); if (surveyMod >= 75) suiToolRangeBox->addMenuItem("1024m", 3); if (surveyMod >= 100) suiToolRangeBox->addMenuItem("2048m", 4); if (surveyMod >= 120) suiToolRangeBox->addMenuItem("4096m", 5); suiToolRangeBox->setUsingObject(_this.getReferenceUnsafeStaticCast()); suiToolRangeBox->setCallback(new SurveyToolSetRangeSuiCallback(server->getZoneServer())); player->getPlayerObject()->addSuiBox(suiToolRangeBox); player->sendMessage(suiToolRangeBox->generateMessage()); } int SurveyToolImplementation::getRange(CreatureObject* player) { int surveyMod = player->getSkillMod("surveying"); int rangeBasedOnSkill = getSkillBasedRange(surveyMod); if (range > rangeBasedOnSkill) setRange(rangeBasedOnSkill); return range; } int SurveyToolImplementation::getSkillBasedRange(int skillLevel) { if (skillLevel >= 120) return 4096; else if (skillLevel >= 100) return 2048; else if (skillLevel >= 75) return 1024; else if (skillLevel >= 55) return 512; else if (skillLevel >= 35) return 256; else if (skillLevel >= 20) return 64; return 0; } void SurveyToolImplementation::setRange(int r) { range = r; // Distance the tool checks during survey // Set number of grid points in survey SUI 3x3 to 5x5 if (range >= 256) { points = 5; } else if (range >= 128) { points = 4; } else { points = 3; } } void SurveyToolImplementation::sendRadioactiveWarning(CreatureObject* player) { ManagedReference<SuiMessageBox* > messageBox = new SuiMessageBox(player, SuiWindowType::SAMPLE_RADIOACTIVE_CONFIRM); messageBox->setPromptTitle("Confirm Radioactive Sample"); messageBox->setPromptText("Sampling a radioactive material will result in harmful effects. Are you sure you wish to continue?"); messageBox->setCancelButton(true, ""); messageBox->setCallback(new SurveyToolApproveRadioactiveSuiCallback(server->getZoneServer())); messageBox->setUsingObject(_this.getReferenceUnsafeStaticCast()); player->getPlayerObject()->addSuiBox(messageBox); player->sendMessage(messageBox->generateMessage()); } void SurveyToolImplementation::consentRadioactiveSample(CreatureObject* player) { radioactiveOk = true; player->sendSystemMessage("@survey:radioactive_sample_unknown"); }
31.967213
129
0.767179
V-Fib
81f948772b86b8a29812ea7c61940fea3de11fff
1,868
cpp
C++
core/TextureData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/TextureData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/TextureData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
#include "TextureData.hpp" #include <iostream> #include "../libs/stb_image.h" TextureData::TextureData(std::string texturePath) { // Save path information this->path = texturePath; // Set type this->type = TEXTURE_UCHAR; // Load texture from file data = stbi_load(this->path.c_str(), &width, &height, &channels, 0); // If we couldn't load the texture, throw an exception if (!data) { throw new std::runtime_error(std::string("Error loading texture: " + this->path).c_str()); } } TextureData::TextureData(int width, int height, glm::vec4 color) { // Reset path information this->path = ""; // Set width, height, and channels this->width = width; this->height = height; this->channels = 4; // Set type this->type = TEXTURE_FLOAT; // Create data array float *fdata = new float[width*height * this->channels]; int size = width * height; int index = 0; for (int i = 0; i < size; i++) { fdata[index++] = color.r; fdata[index++] = color.g; fdata[index++] = color.b; fdata[index++] = color.a; } data = (unsigned char*)fdata; } TextureData::TextureData(int width, int height, unsigned char color) { // Reset path information this->path = ""; // Set type this->type = TEXTURE_UCHAR; // Set width, height, and channels this->width = width; this->height = height; this->channels = 1; // Create data array unsigned char* udata = new unsigned char[width*height]; int size = width * height; for (int i = 0; i < size; i++) { udata[i] = color; } data = udata; } TextureData::~TextureData() { if (data) { delete[] data; } } int TextureData::getWidth() { return width; } int TextureData::getHeight() { return height; } int TextureData::getChannels() { return channels; } string TextureData::getPath() { return path; } TextureType TextureData::getType() { return type; } void* TextureData::getData() { return data; }
23.35
92
0.663276
jmppmj
3b4a0518b87d5005d31bff3e05586c4752488b7b
2,152
cpp
C++
MonoNative/mscorlib/System/Reflection/mscorlib_System_Reflection_ReflectionContext.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative/mscorlib/System/Reflection/mscorlib_System_Reflection_ReflectionContext.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative/mscorlib/System/Reflection/mscorlib_System_Reflection_ReflectionContext.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_ReflectionContext.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_TypeInfo.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_Assembly.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Reflection { //Public Methods mscorlib::System::Reflection::TypeInfo ReflectionContext::GetTypeForObject(mscorlib::System::Object value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Reflection", "ReflectionContext", 0, NULL, "GetTypeForObject", __native_object__, 1, __parameter_types__, __parameters__, NULL); return mscorlib::System::Reflection::TypeInfo(__result__); } mscorlib::System::Reflection::Assembly ReflectionContext::MapAssembly(mscorlib::System::Reflection::Assembly assembly) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(assembly).name()); __parameters__[0] = (MonoObject*)assembly; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Reflection", "ReflectionContext", 0, NULL, "MapAssembly", __native_object__, 1, __parameter_types__, __parameters__, NULL); return mscorlib::System::Reflection::Assembly(__result__); } mscorlib::System::Reflection::TypeInfo ReflectionContext::MapType(mscorlib::System::Reflection::TypeInfo type) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(type).name()); __parameters__[0] = (MonoObject*)type; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Reflection", "ReflectionContext", 0, NULL, "MapType", __native_object__, 1, __parameter_types__, __parameters__, NULL); return mscorlib::System::Reflection::TypeInfo(__result__); } } } }
42.196078
199
0.750929
brunolauze
3b4bd633767cf38e6f2d0da3172953734e733b0f
2,774
cpp
C++
cpp-GEngine/Sprite.cpp
leftidev/cpp-GEngine
fb1a000336f8295386c5e9e401072cfe0679b587
[ "MIT" ]
4
2016-04-02T05:52:59.000Z
2021-05-15T21:03:17.000Z
deps/include/GEngine/Sprite.cpp
lefti-/cpp-Gravity-Gizmo
b9ddde976a6585f2c9cc978372146383f19dd00d
[ "MIT" ]
null
null
null
deps/include/GEngine/Sprite.cpp
lefti-/cpp-Gravity-Gizmo
b9ddde976a6585f2c9cc978372146383f19dd00d
[ "MIT" ]
1
2016-04-13T17:25:44.000Z
2016-04-13T17:25:44.000Z
#include <cstddef> #include "Vertex.h" #include "ResourceManager.h" #include "Sprite.h" namespace GEngine { Sprite::Sprite() { _vboID = 0; } Sprite::~Sprite() { if (_vboID != 0) { glDeleteBuffers(1, &_vboID); } } // Initializes the sprite VBO. x, y, width, and height are // in the normalized device coordinate space. so, [-1, 1]. void Sprite::init(float x, float y, float width, float height, std::string texturePath) { _x = x; _y = y; _width = width; _height = height; _texture = ResourceManager::getTexture(texturePath); // Generate the buffer if it hasn't already been generated if (_vboID == 0) { // Generate vertex buffer object ID glGenBuffers(1, &_vboID); } // This array will hold our vertex data // We need 6 vertices, and each vertex has 2 floats for X and Y Vertex vertexData[6]; // First Triangle // Top right vertexData[0].setPosition(x + width, y + height); vertexData[0].setUV(1.0f, 1.0f); // Top left vertexData[1].setPosition(x, y + height); vertexData[1].setUV(0.0f, 1.0f); // Bottom left vertexData[2].setPosition(x, y); vertexData[2].setUV(0.0f, 0.0f); // Second Triangle // Bottom left vertexData[3].setPosition(x, y); vertexData[3].setUV(0.0f, 0.0f); // Bottom right vertexData[4].setPosition(x + width, y); vertexData[4].setUV(1.0f, 0.0f); // Top right vertexData[5].setPosition(x + width, y + height); vertexData[5].setUV(1.0f, 1.0f); for (int i = 0; i < 6; i++) { vertexData[i].setColor(255, 255, 255, 255); } // Bind the vertex buffer object (active buffer) glBindBuffer(GL_ARRAY_BUFFER, _vboID); // Upload the buffer data to GPU glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); // Unbind the buffer glBindBuffer(GL_ARRAY_BUFFER, 0); } // Draws the sprite to the screen void Sprite::draw() { glBindTexture(GL_TEXTURE_2D, _texture.id); // Bind the buffer object glBindBuffer(GL_ARRAY_BUFFER, _vboID); // Tell OpenGL that we want to use the first attribute array glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); // This is the position attribute pointer glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position)); // This is the color attribute pointer glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color)); // This is the UV attribute pointer glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, uv)); // Draw the 6 vertices to the screen glDrawArrays(GL_TRIANGLES, 0, 6); // Disable the vertex attrib array glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); // Unbind the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); } }
25.218182
104
0.709805
leftidev
3b4c7fce17e3293df7f023dc4f5a0dd45c5b4dae
2,546
hpp
C++
modules/filters/include/toffy/viewers/cloudviewpcl.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/filters/include/toffy/viewers/cloudviewpcl.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/filters/include/toffy/viewers/cloudviewpcl.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Simon Vogl <svogl@voxel.at> Angel Merino-Sastre <amerino@voxel.at> 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. */ #pragma once #include <vector> #include "toffy/filter.hpp" #include <boost/thread.hpp> #include <pcl/segmentation/organized_multi_plane_segmentation.h> namespace toffy { /** * @brief 3d Viewer for PointCloud2 using PCL * @ingroup Viewers * * Show PointCloud2 (new PCL standard) int a viewer. * The viewer runs in a separated thread that updates continuoslly to provide * interaction. * * @todo There is a mayor issue with the viewer. In linux, GTK does not delete * the viewer in any case. When we try to instanciate a viewer again in the * same process, it just crash. * * \section ex1 Xml Configuration * @include cloudviewpcl.xml * */ class CloudViewPCL : public Filter { public: static const std::string id_name; ///< Filter identifier CloudViewPCL(); virtual ~CloudViewPCL(); virtual bool filter(const Frame& in, Frame& out); virtual boost::property_tree::ptree getConfig() const; void updateConfig(const boost::property_tree::ptree &pt); /** * @brief Getter signal status * @param s */ void signal(int s); private: std::string _in_cloud; boost::thread _thread; volatile int _signal; ///< Interthread flag. Used for check the thread status double _coordSize; pcl::PCLPointCloud2Ptr _planar; ///< Aux std::vector<std::string> _cloudNames; /**< Keep all cloud names in Frame to be displayed*/ std::vector<pcl::PCLPointCloud2Ptr> _clouds; volatile bool _newCloud; /*< Interthread flag to advice a runtime change in the clouds to display */ static std::size_t _filter_counter; /** * @brief Internal loop called within the thread that keeps the viewer * running. */ void loopViewer(); //boomerang //std::vector<float> _cube; //pcl::PointCloud<pcl::PointXYZ> _poly1, _poly2; //pcl::PointCloud<pcl::Normal>::Ptr normal_cloud; }; }
27.673913
81
0.699136
voxel-dot-at
3b5354fef2127f9bf998fd9014549c4087a96382
41,063
cpp
C++
maya/AbcExport/AttributesWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
maya/AbcExport/AttributesWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
maya/AbcExport/AttributesWriter.cpp
nebkor/ardent-embic
4eab1c4f089438bd26636f4be3be3efa83bc8338
[ "MIT" ]
null
null
null
//-***************************************************************************** // // Copyright (c) 2009-2011, // Sony Pictures Imageworks Inc. and // Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Sony Pictures Imageworks, nor // Industrial Light & Magic, nor the names of their contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //-***************************************************************************** #include "AttributesWriter.h" #include "MayaUtility.h" namespace Abc = Alembic::Abc; namespace AbcGeom = Alembic::AbcGeom; namespace AbcA = Alembic::AbcCoreAbstract; namespace { static const char * cAttrScope = "_AbcGeomScope"; static const char * cAttrType = "_AbcType"; // returns true if a plug is of a simple numeric data type bool isDataAttr(const MPlug & iParent) { MObject obj = iParent.asMObject(); switch (obj.apiType()) { case MFn::kData2Double: case MFn::kData3Double: case MFn::kData4Double: case MFn::kData2Float: case MFn::kData3Float: case MFn::kData2Int: case MFn::kData3Int: case MFn::kData2Short: case MFn::kData3Short: case MFn::kStringData: case MFn::kStringArrayData: case MFn::kFloatVectorArrayData: case MFn::kVectorArrayData: case MFn::kFloatArrayData: case MFn::kDoubleArrayData: case MFn::kIntArrayData: case MFn::kPointArrayData: case MFn::kUInt64ArrayData: return true; default: return false; } return false; } AbcGeom::GeometryScope strToScope(MString iStr) { iStr.toLowerCase(); if (iStr == "vtx") { return AbcGeom::kVertexScope; } else if (iStr == "fvr") { return AbcGeom::kFacevaryingScope; } else if (iStr == "uni") { return AbcGeom::kUniformScope; } else if (iStr == "var") { return AbcGeom::kVaryingScope; } return AbcGeom::kConstantScope; } // returns true if the string ends with _AbcGeomScope or _AbcType bool endsWithArbAttr(const std::string & iStr) { size_t len = iStr.size(); return (len >= 13 && iStr.compare(len - 13, 13, cAttrScope) == 0) || (len >= 8 && iStr.compare(len - 8, 8, cAttrType) == 0); } void createPropertyFromNumeric(MFnNumericData::Type iType, const MObject& iAttr, const MPlug& iPlug, Abc::OCompoundProperty & iParent, Alembic::Util::uint32_t iTimeIndex, AbcGeom::GeometryScope iScope, std::vector < PlugAndObjArray > & oArrayVec) { std::string plugName = iPlug.partialName(0, 0, 0, 0, 0, 1).asChar(); switch (iType) { case MFnNumericData::kBoolean: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OBoolGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::kByte: case MFnNumericData::kChar: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OCharGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::kShort: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OInt16GeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::kInt: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OInt32GeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::kFloat: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OFloatGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::kDouble: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::ODoubleGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k2Short: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV2sGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k3Short: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV3sGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k2Int: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV2iGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k3Int: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV3iGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k2Float: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV2fGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k3Float: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; MFnAttribute mfnAttr(iAttr); if (mfnAttr.isUsedAsColor()) { AbcGeom::OC3fGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } else { AbcGeom::OV3fGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } oArrayVec.push_back(p); } break; case MFnNumericData::k2Double: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV2dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k3Double: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OV3dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnNumericData::k4Double: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcA::DataType dtype(Alembic::Util::kFloat64POD, 4); p.prop = Abc::OArrayProperty(iParent, plugName, dtype, iTimeIndex); oArrayVec.push_back(p); } break; default: break; } } bool MFnNumericDataToSample(MFnNumericData::Type iType, const MPlug& iPlug, Abc::OArrayProperty & oProp) { unsigned int numElements = iPlug.numElements(); bool isArray = iPlug.isArray(); unsigned int dimSize = numElements; if (!isArray) dimSize = 1; switch (iType) { case MFnNumericData::kBoolean: { std::vector< Alembic::Util::bool_t > val(dimSize); if (!isArray) { val[0] = iPlug.asBool(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asBool(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::kByte: case MFnNumericData::kChar: { std::vector< Alembic::Util::int8_t > val(dimSize); if (!isArray) { val[0] = iPlug.asChar(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asChar(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::kShort: { std::vector< Alembic::Util::int16_t > val(dimSize); if (!isArray) { val[0] = iPlug.asShort(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asShort(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::kInt: { std::vector< Alembic::Util::int32_t > val(dimSize); if (!isArray) { val[0] = iPlug.asInt(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asInt(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::kFloat: { std::vector<float> val(dimSize); if (!isArray) { val[0] = iPlug.asFloat(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asFloat(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::kDouble: { std::vector<double> val(dimSize); if (!isArray) { val[0] = iPlug.asDouble(); } else { for (unsigned int i = 0; i < numElements; ++i) { val[i] = iPlug[i].asDouble(); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k2Short: { std::vector< Alembic::Util::int16_t > val(dimSize*2); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData2Short(val[0], val[1]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData2Short(val[2*i], val[2*i+1]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k3Short: { std::vector< Alembic::Util::int16_t > val(dimSize*3); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData3Short(val[0], val[1], val[2]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData3Short(val[3*i], val[3*i+1], val[3*i+2]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k2Int: { std::vector< Alembic::Util::int32_t > val(dimSize*2); if (!isArray) { int val0, val1; MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData2Int(val0, val1); val[0] = Alembic::Util::int32_t(val0); val[1] = Alembic::Util::int32_t(val1); } else { for (unsigned int i = 0; i < numElements; ++i) { int val0, val1; MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData2Int(val0, val1); val[2*i] = Alembic::Util::int32_t(val0); val[2*i+1] = Alembic::Util::int32_t(val1); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k3Int: { std::vector< Alembic::Util::int32_t > val(dimSize*3); if (!isArray) { int val0, val1, val2; MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData3Int(val0, val1, val2); val[0] = Alembic::Util::int32_t(val0); val[1] = Alembic::Util::int32_t(val1); val[2] = Alembic::Util::int32_t(val2); } else { for (unsigned int i = 0; i < numElements; ++i) { int val0, val1, val2; MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData3Int(val0, val1, val2); val[3*i] = Alembic::Util::int32_t(val0); val[3*i+1] = Alembic::Util::int32_t(val1); val[3*i+2] = Alembic::Util::int32_t(val2); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k2Float: { std::vector<float> val(dimSize*2); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData2Float(val[0], val[1]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData2Float(val[2*i], val[2*i+1]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k3Float: { std::vector<float> val(dimSize*3); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData3Float(val[0], val[1], val[2]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData3Float(val[3*i], val[3*i+1], val[3*i+2]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k2Double: { std::vector<double> val(dimSize*2); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData2Double(val[0], val[1]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData2Double(val[2*i], val[2*i+1]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k3Double: { std::vector<double> val(dimSize*3); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData3Double(val[0], val[1], val[2]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData3Double(val[3*i], val[3*i+1], val[3*i+2]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; case MFnNumericData::k4Double: { std::vector<double> val(dimSize*4); if (!isArray) { MFnNumericData numdFn(iPlug.asMObject()); numdFn.getData4Double(val[0], val[1], val[2], val[3]); } else { for (unsigned int i = 0; i < numElements; ++i) { MFnNumericData numdFn(iPlug[i].asMObject()); numdFn.getData4Double(val[4*i], val[4*i+1], val[4*i+2], val[4*i+3]); } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(dimSize)); oProp.set(samp); } break; default: return false; break; } return true; } bool MFnTypedDataToSample(MFnData::Type iType, const MPlug& iPlug, Abc::OArrayProperty & oProp) { size_t numElements = iPlug.numElements(); bool isArray = iPlug.isArray(); size_t dimSize = numElements; if (!isArray) dimSize = 1; switch (iType) { case MFnData::kNumeric: { MFnNumericData numObj(iPlug.asMObject()); return MFnNumericDataToSample(numObj.numericType(), iPlug, oProp); } break; case MFnData::kString: { std::vector< std::string > val(1); val[0] = iPlug.asString().asChar(); AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(1)); oProp.set(samp); } break; case MFnData::kStringArray: { MFnStringArrayData arr(iPlug.asMObject()); unsigned int length = arr.length(); std::vector< std::string > val(length); for (unsigned int i = 0; i < length; i++) { val[i] = arr[i].asChar(); } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(length)); oProp.set(samp); } break; case MFnData::kDoubleArray: { MFnDoubleArrayData arr(iPlug.asMObject()); unsigned int length = arr.length(); std::vector< double > val(length); for (unsigned int i = 0; i < length; i++) { val[i] = arr[i]; } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(length)); oProp.set(samp); } break; case MFnData::kIntArray: { MFnIntArrayData arr(iPlug.asMObject()); unsigned int length = arr.length(); std::vector< Alembic::Util::int32_t > val(length); for (unsigned int i = 0; i < length; i++) { val[i] = arr[i]; } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(length)); oProp.set(samp); } break; case MFnData::kPointArray: { MFnPointArrayData arr(iPlug.asMObject()); unsigned int length = arr.length(); unsigned int extent = oProp.getDataType().getExtent(); std::vector< double > val(length*extent); for (unsigned int i = 0; i < length; i++) { MPoint pt(arr[i]); val[extent*i] = pt.x; val[extent*i+1] = pt.y; if (extent > 2) val[extent*i+2] = pt.z; if (extent > 3) val[extent*i+3] = pt.w; } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(length)); oProp.set(samp); } break; case MFnData::kVectorArray: { MFnVectorArrayData arr(iPlug.asMObject()); unsigned int length = arr.length(); unsigned int extent = oProp.getDataType().getExtent(); std::vector< double > val(length*extent); for (unsigned int i = 0; i < length; i++) { MVector v(arr[i]); val[extent*i] = v.x; val[extent*i+1] = v.y; if (extent > 2) val[extent*i+2] = v.z; } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(length)); oProp.set(samp); } break; case MFnData::kMatrix: { MFnMatrixData arr(iPlug.asMObject()); MMatrix mat = arr.matrix(); std::vector<double> val(16); unsigned int i = 0; for (unsigned int r = 0; r < 4; r++) { for (unsigned int c = 0; c < 4; c++, i++) { val[i] = mat[r][c]; } } AbcA::ArraySample samp(&(val.front()), oProp.getDataType(), Alembic::Util::Dimensions(1)); oProp.set(samp); } break; default: return false; break; } return true; } bool attributeToPropertyPair(const MObject& iAttr, const MPlug& iPlug, Abc::OArrayProperty & oProp) { if (iAttr.hasFn(MFn::kTypedAttribute)) { MFnTypedAttribute typedAttr(iAttr); return MFnTypedDataToSample(typedAttr.attrType(), iPlug, oProp); } else if (iAttr.hasFn(MFn::kNumericAttribute)) { MFnNumericAttribute numAttr(iAttr); return MFnNumericDataToSample(numAttr.unitType(), iPlug, oProp); } else if (iAttr.hasFn(MFn::kUnitAttribute)) { double val = iPlug.asDouble(); AbcA::ArraySample samp(&val, oProp.getDataType(), Alembic::Util::Dimensions(1)); oProp.set(samp); return true; } else if (iAttr.hasFn(MFn::kEnumAttribute)) { Alembic::Util::int16_t val = iPlug.asShort(); AbcA::ArraySample samp(&val, oProp.getDataType(), Alembic::Util::Dimensions(1)); oProp.set(samp); return true; } return false; } void createPropertyFromMFnAttr(const MObject& iAttr, const MPlug& iPlug, Abc::OCompoundProperty & iParent, Alembic::Util::uint32_t iTimeIndex, AbcGeom::GeometryScope iScope, const MString & iTypeStr, std::vector < PlugAndObjArray > & oArrayVec) { // for some reason we have just 1 of the elements of an array, bail if (iPlug.isElement()) return; MStatus stat; std::string plugName = iPlug.partialName(0, 0, 0, 0, 0, 1).asChar(); if (iAttr.hasFn(MFn::kNumericAttribute)) { MFnNumericAttribute numFn(iAttr, &stat); if (!stat) { MString err = "Couldn't instantiate MFnNumericAttribute\n\tType: "; err += iAttr.apiTypeStr(); MGlobal::displayError(err); return; } createPropertyFromNumeric(numFn.unitType(), iAttr, iPlug, iParent, iTimeIndex, iScope, oArrayVec); } else if (iAttr.hasFn(MFn::kTypedAttribute)) { MFnTypedAttribute typeFn(iAttr, &stat); if (!stat) { MString err = "Couldn't instantiate MFnTypedAttribute\n\tType: "; err += iAttr.apiTypeStr(); MGlobal::displayError(err); return; } switch (typeFn.attrType()) { case MFnData::kString: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OStringGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnData::kStringArray: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OStringGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnData::kDoubleArray: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::ODoubleGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnData::kIntArray: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OInt32GeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnData::kPointArray: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; if (iTypeStr == "point2") { AbcGeom::OP2dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } else { AbcGeom::OP3dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } oArrayVec.push_back(p); } break; case MFnData::kVectorArray: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; if (iTypeStr == "vector2") { AbcGeom::OV2dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } else if (iTypeStr == "normal2") { AbcGeom::ON2dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } else if (iTypeStr == "normal3") { AbcGeom::ON3dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } else { AbcGeom::OV3dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); } oArrayVec.push_back(p); } break; case MFnData::kMatrix: { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OM44dGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } break; case MFnData::kNumeric: { MFnNumericAttribute numAttr(iPlug.asMObject()); createPropertyFromNumeric(numAttr.unitType(), iAttr, iPlug, iParent, iTimeIndex, iScope, oArrayVec); } break; default: { // get the full property name for the warning MString msg = "WARNING: Couldn't convert "; msg += iPlug.partialName(1, 0, 0, 0, 1, 1); msg += " to a property, so skipping."; MGlobal::displayWarning(msg); } break; } } else if (iAttr.hasFn(MFn::kUnitAttribute)) { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::ODoubleGeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } else if (iAttr.hasFn(MFn::kEnumAttribute)) { PlugAndObjArray p; p.plug = iPlug; p.obj = iAttr; AbcGeom::OInt16GeomParam gp(iParent, plugName, false, iScope, 1, iTimeIndex); p.prop = gp.getValueProperty(); oArrayVec.push_back(p); } } } AttributesWriter::AttributesWriter( Alembic::Abc::OCompoundProperty & iParent, Alembic::Abc::OObject & iParentObj, const MFnDagNode & iNode, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs) { PlugAndObjScalar visPlug; unsigned int attrCount = iNode.attributeCount(); unsigned int i; std::vector< PlugAndObjArray > staticPlugObjArrayVec; for (i = 0; i < attrCount; i++) { MObject attr = iNode.attribute(i); MFnAttribute mfnAttr(attr); MPlug plug = iNode.findPlug(attr, true); // if it is not readable, then bail without any more checking if (!mfnAttr.isReadable() || plug.isNull()) continue; MString propName = plug.partialName(0, 0, 0, 0, 0, 1); std::string propStr = propName.asChar(); // we handle visibility in a special way if (propStr == "visibility") { if (iArgs.writeVisibility) { visPlug.plug = plug; visPlug.obj = attr; visPlug.propParent = iParentObj; } continue; } if (!iParent.valid() || !matchFilterOrAttribs(plug, iArgs)) { continue; } int sampType = util::getSampledType(plug); MPlug scopePlug = iNode.findPlug(propName + cAttrScope); AbcGeom::GeometryScope scope = AbcGeom::kUnknownScope; if (!scopePlug.isNull()) { scope = strToScope(scopePlug.asString()); } MString typeStr; MPlug typePlug = iNode.findPlug(propName + cAttrType); if (!typePlug.isNull()) { typeStr= typePlug.asString(); } switch (sampType) { // static case 0: { createPropertyFromMFnAttr(attr, plug, iParent, 0, scope, typeStr, staticPlugObjArrayVec); } break; // sampled case 1: // curve treat like sampled case 2: { createPropertyFromMFnAttr(attr, plug, iParent, iTimeIndex, scope, typeStr, mPlugObjArrayVec); } break; } } std::vector< PlugAndObjArray >::iterator j = staticPlugObjArrayVec.begin(); std::vector< PlugAndObjArray >::iterator jend = staticPlugObjArrayVec.end(); // write the statics for (; j != jend; j++) { MString propName = j->plug.partialName(0, 0, 0, 0, 0, 1); bool filledProp = attributeToPropertyPair(j->obj, j->plug, j->prop); if (!filledProp) { MString msg = "WARNING: Couldn't get static property "; msg += j->plug.partialName(1, 0, 0, 0, 1, 1); msg += ", so skipping."; MGlobal::displayWarning(msg); continue; } } j = mPlugObjArrayVec.begin(); jend = mPlugObjArrayVec.end(); for (; j != jend; j++) { MString propName = j->plug.partialName(0, 0, 0, 0, 0, 1); bool filledProp = attributeToPropertyPair(j->obj, j->plug,j->prop); if (!filledProp) { MString msg = "WARNING: Couldn't get static property "; msg += j->plug.partialName(1, 0, 0, 0, 1, 1); msg += ", so skipping."; MGlobal::displayWarning(msg); continue; } } if (!visPlug.plug.isNull()) { int retVis = util::getVisibilityType(visPlug.plug); // visible will go on the top most compound Abc::OCompoundProperty parent = visPlug.propParent.getProperties(); switch (retVis) { // static visibility 0 case case 1: { Alembic::Util::int8_t visVal = Alembic::AbcGeom::kVisibilityHidden; Abc::OCharProperty bp = Alembic::AbcGeom::CreateVisibilityProperty( visPlug.propParent, 0); bp.set(visVal); } break; // animated visibility 0 case case 2: { Alembic::Util::int8_t visVal = Alembic::AbcGeom::kVisibilityHidden; Abc::OCharProperty bp = Alembic::AbcGeom::CreateVisibilityProperty( visPlug.propParent, iTimeIndex); bp.set(visVal); visPlug.prop = bp; mAnimVisibility = visPlug; } break; // animated visibility 1 case case 3: { // dont add if we are forcing static (no frame range specified) if (iTimeIndex == 0) { break; } mAnimVisibility = visPlug; Alembic::Util::int8_t visVal = Alembic::AbcGeom::kVisibilityDeferred; Abc::OCharProperty bp = Alembic::AbcGeom::CreateVisibilityProperty( visPlug.propParent, iTimeIndex); bp.set(visVal); visPlug.prop = bp; mAnimVisibility = visPlug; } break; // dont write any visibility default: break; } } } bool AttributesWriter::matchFilterOrAttribs(const MPlug & iPlug, const JobArgs & iArgs) { MString propName = iPlug.partialName(0, 0, 0, 0, 0, 1); std::string name = propName.asChar(); if (name.find("[") != std::string::npos) { return false; } std::vector<std::string>::const_iterator f; std::vector<std::string>::const_iterator fEnd = iArgs.prefixFilters.end(); for (f = iArgs.prefixFilters.begin(); f != fEnd; ++f) { // check the prefilter and ignore those that match but end with // arb attr if (f->length() > 0 && name.compare(0, f->length(), *f) == 0 && !endsWithArbAttr(name) && ( !iPlug.isChild() || !isDataAttr(iPlug.parent()) )) { return true; } } // check our specific list of attributes if (iArgs.attribs.find(name) != iArgs.attribs.end()) { return true; } return false; } bool AttributesWriter::hasAnyAttr(const MFnDagNode & iNode, const JobArgs & iArgs) { unsigned int attrCount = iNode.attributeCount(); unsigned int i; std::vector< PlugAndObjArray > staticPlugObjArrayVec; for (i = 0; i < attrCount; i++) { MObject attr = iNode.attribute(i); MFnAttribute mfnAttr(attr); MPlug plug = iNode.findPlug(attr, true); // if it is not readable, then bail without any more checking if (!mfnAttr.isReadable() || plug.isNull()) { continue; } if (matchFilterOrAttribs(plug, iArgs)) { return true; } } return false; } AttributesWriter::~AttributesWriter() { // if this happens to be set, clear it out before propParent goes out // of scope to work around issue 171 mAnimVisibility.prop.reset(); } bool AttributesWriter::isAnimated() { return !mPlugObjArrayVec.empty() || !mAnimVisibility.plug.isNull(); } void AttributesWriter::write() { std::vector< PlugAndObjArray >::iterator j = mPlugObjArrayVec.begin(); std::vector< PlugAndObjArray >::iterator jend = mPlugObjArrayVec.end(); for (; j != jend; j++) { MString propName = j->plug.partialName(0, 0, 0, 0, 0, 1); bool filledProp = attributeToPropertyPair(j->obj, j->plug, j->prop); if (!filledProp) { MString msg = "WARNING: Couldn't get sampled property "; msg += j->plug.partialName(1, 0, 0, 0, 1, 1); msg += ", so skipping."; MGlobal::displayWarning(msg); continue; } } if (!mAnimVisibility.plug.isNull()) { Alembic::Util::int8_t visVal = -1; if (!mAnimVisibility.plug.asBool()) { visVal = 0; } mAnimVisibility.prop.set(&visVal); } }
29.842297
80
0.489735
nebkor
3b5b63cc8e23153073febc697d4a2c4ff40382cd
16,664
cc
C++
src/shell_content_browser_client.cc
ghrhomeDist/node-webkit
5fc6d07a60a05dd57f76cb6171fe909c3ee5e1e7
[ "MIT" ]
45
2015-02-06T07:42:18.000Z
2018-05-21T02:15:15.000Z
src/shell_content_browser_client.cc
mcdongWang/node-webkit
e3cfc89e2458eafec81880c2ad5ef81cbf68f6ed
[ "MIT" ]
null
null
null
src/shell_content_browser_client.cc
mcdongWang/node-webkit
e3cfc89e2458eafec81880c2ad5ef81cbf68f6ed
[ "MIT" ]
15
2015-01-23T05:39:08.000Z
2017-11-02T11:32:27.000Z
// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/shell_content_browser_client.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/file_util.h" #include "base/strings/string_util.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" //#include "chrome/common/child_process_logging.h" #include "components/breakpad/app/breakpad_client.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/gpu/compositor_util.h" #include "content/nw/src/browser/printing/printing_message_filter.h" #include "content/public/browser/browser_url_handler.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_switches.h" #include "content/public/common/renderer_preferences.h" #include "content/public/common/url_constants.h" #include "content/nw/src/api/dispatcher_host.h" #if defined(OS_MACOSX) #include "content/nw/src/breakpad_mac.h" #elif defined(OS_POSIX) #include "content/nw/src/breakpad_linux.h" #endif #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/browser/printing/print_job_manager.h" #include "content/nw/src/browser/shell_devtools_delegate.h" #include "content/nw/src/shell_quota_permission_context.h" #include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h" #include "content/nw/src/media/media_internals.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/nw_shell.h" #include "content/nw/src/nw_version.h" #include "content/nw/src/shell_browser_context.h" #include "content/nw/src/shell_browser_main_parts.h" #include "geolocation/shell_access_token_store.h" #include "url/gurl.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #include "content/common/dom_storage/dom_storage_map.h" #include "webkit/common/webpreferences.h" #include "webkit/common/user_agent/user_agent_util.h" #include "content/common/plugin_list.h" #include "content/public/browser/plugin_service.h" #if defined(OS_LINUX) #include "base/linux_util.h" #include "content/nw/src/crash_handler_host_linux.h" #endif using base::FileDescriptor; namespace { #if defined(OS_POSIX) && !defined(OS_MACOSX) int GetCrashSignalFD(const CommandLine& command_line) { std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); if (process_type == switches::kRendererProcess) return RendererCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket(); if (process_type == switches::kPluginProcess) return PluginCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket(); if (process_type == switches::kPpapiPluginProcess) return PpapiCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket(); if (process_type == switches::kGpuProcess) return GpuCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket(); return -1; } #endif // defined(OS_POSIX) && !defined(OS_MACOSX) } namespace content { ShellContentBrowserClient::ShellContentBrowserClient() : shell_browser_main_parts_(NULL), master_rph_(NULL) { } ShellContentBrowserClient::~ShellContentBrowserClient() { } BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts( const MainFunctionParams& parameters) { shell_browser_main_parts_ = new ShellBrowserMainParts(parameters); return shell_browser_main_parts_; } bool ShellContentBrowserClient::GetUserAgentManifest(std::string* agent) { std::string user_agent; nw::Package* package = shell_browser_main_parts()->package(); if (package->root()->GetString(switches::kmUserAgent, &user_agent)) { std::string name, version; package->root()->GetString(switches::kmName, &name); package->root()->GetString("version", &version); ReplaceSubstringsAfterOffset(&user_agent, 0, "%name", name); ReplaceSubstringsAfterOffset(&user_agent, 0, "%ver", version); ReplaceSubstringsAfterOffset(&user_agent, 0, "%nwver", NW_VERSION_STRING); ReplaceSubstringsAfterOffset(&user_agent, 0, "%webkit_ver", webkit_glue::GetWebKitVersion()); ReplaceSubstringsAfterOffset(&user_agent, 0, "%osinfo", webkit_glue::BuildOSInfo()); *agent = user_agent; return true; } return false; } WebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView( WebContents* web_contents, RenderViewHostDelegateView** render_view_host_delegate_view, const WebContents::CreateParams& params) { std::string user_agent, rules; nw::Package* package = shell_browser_main_parts()->package(); content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs(); if (GetUserAgentManifest(&user_agent)) { prefs->user_agent_override = user_agent; } if (package->root()->GetString(switches::kmRemotePages, &rules)) prefs->nw_remote_page_rules = rules; prefs->nw_app_root_path = package->path(); prefs->nw_inject_css_fn = params.nw_inject_css_fn; prefs->nw_inject_js_doc_start = params.nw_inject_js_doc_start; prefs->nw_inject_js_doc_end = params.nw_inject_js_doc_end; return NULL; } std::string ShellContentBrowserClient::GetApplicationLocale() { CommandLine* cmd_line = CommandLine::ForCurrentProcess(); std::string pref_locale; if (cmd_line->HasSwitch(switches::kLang)) { pref_locale = cmd_line->GetSwitchValueASCII(switches::kLang); } return l10n_util::GetApplicationLocale(pref_locale); } void ShellContentBrowserClient::AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) { #if defined(OS_MACOSX) if (breakpad::IsCrashReporterEnabled()) { command_line->AppendSwitch(switches::kEnableCrashReporter); } #elif defined(OS_POSIX) if (breakpad::IsCrashReporterEnabled()) { command_line->AppendSwitch(switches::kEnableCrashReporter); } #endif // OS_MACOSX if (command_line->GetSwitchValueASCII("type") != "renderer") return; if (content::IsThreadedCompositingEnabled()) command_line->AppendSwitch(switches::kEnableThreadedCompositing); std::string user_agent; if (!command_line->HasSwitch(switches::kUserAgent) && GetUserAgentManifest(&user_agent)) { command_line->AppendSwitchASCII(switches::kUserAgent, user_agent); } if (child_process_id > 0) { scoped_ptr<content::RenderWidgetHostIterator> widgets = content::RenderWidgetHost::GetRenderWidgetHosts(); while (RenderWidgetHost* widget = widgets->GetNextHost()) { if (widget->GetProcess()->GetID() != child_process_id) continue; if (!widget->IsRenderView()) continue; content::RenderViewHost* host = content::RenderViewHost::From( const_cast<content::RenderWidgetHost*>(widget)); content::Shell* shell = content::Shell::FromRenderViewHost(host); if (shell) { if (!shell->nodejs()) return; if (shell->is_devtools()) { // DevTools should have powerful permissions to load local // files by XHR (e.g. for source map) command_line->AppendSwitch(switches::kNodejs); return; } } } } nw::Package* package = shell_browser_main_parts()->package(); if (package && package->GetUseNode()) { // Allow node.js command_line->AppendSwitch(switches::kNodejs); // Set cwd command_line->AppendSwitchPath(switches::kWorkingDirectory, package->path()); // Check if we have 'node-main'. std::string node_main; if (package->root()->GetString(switches::kNodeMain, &node_main)) command_line->AppendSwitchASCII(switches::kNodeMain, node_main); std::string snapshot_path; if (package->root()->GetString(switches::kSnapshot, &snapshot_path)) command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path); int dom_storage_quota_mb; if (package->root()->GetInteger("dom_storage_quota", &dom_storage_quota_mb)) { content::DOMStorageMap::SetQuotaOverride(dom_storage_quota_mb * 1024 * 1024); command_line->AppendSwitchASCII(switches::kDomStorageQuota, base::IntToString(dom_storage_quota_mb)); } } // without the switch, the destructor of the shell object will // shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and // destory rph immediately. Then the channel error msg is caught by // SuicideOnChannelErrorFilter and the renderer is killed // immediately #if defined(OS_POSIX) command_line->AppendSwitch(switches::kChildCleanExit); #endif } void ShellContentBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( new ShellResourceDispatcherHostDelegate()); ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } std::string ShellContentBrowserClient::GetDefaultDownloadName() { return "download"; } MediaObserver* ShellContentBrowserClient::GetMediaObserver() { return MediaInternals::GetInstance(); } void ShellContentBrowserClient::BrowserURLHandlerCreated( BrowserURLHandler* handler) { } ShellBrowserContext* ShellContentBrowserClient::browser_context() { return shell_browser_main_parts_->browser_context(); } ShellBrowserContext* ShellContentBrowserClient::off_the_record_browser_context() { return shell_browser_main_parts_->off_the_record_browser_context(); } AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() { return new ShellAccessTokenStore(browser_context()); } void ShellContentBrowserClient::OverrideWebkitPrefs( RenderViewHost* render_view_host, const GURL& url, WebPreferences* prefs) { nw::Package* package = shell_browser_main_parts()->package(); // Disable web security. prefs->dom_paste_enabled = true; prefs->javascript_can_access_clipboard = true; prefs->web_security_enabled = true; prefs->allow_file_access_from_file_urls = true; // Open experimental features. prefs->css_variables_enabled = true; // Disable plugins and cache by default. prefs->plugins_enabled = false; prefs->java_enabled = false; base::DictionaryValue* webkit; if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) { webkit->GetBoolean(switches::kmJava, &prefs->java_enabled); webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled); FilePath plugins_dir = package->path(); //PathService::Get(base::DIR_CURRENT, &plugins_dir); plugins_dir = plugins_dir.AppendASCII("plugins"); PluginService* plugin_service = PluginService::GetInstance(); plugin_service->AddExtraPluginDir(plugins_dir); } } bool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost( BrowserContext* browser_context, const GURL& url) { ShellBrowserContext* shell_browser_context = static_cast<ShellBrowserContext*>(browser_context); if (shell_browser_context->pinning_renderer()) return true; else return false; } bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host, const GURL& site_url) { return process_host == master_rph_; } net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext( BrowserContext* content_browser_context, ProtocolHandlerMap* protocol_handlers) { ShellBrowserContext* shell_browser_context = ShellBrowserContextForBrowserContext(content_browser_context); return shell_browser_context->CreateRequestContext(protocol_handlers); } net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContextForStoragePartition( BrowserContext* content_browser_context, const base::FilePath& partition_path, bool in_memory, ProtocolHandlerMap* protocol_handlers) { ShellBrowserContext* shell_browser_context = ShellBrowserContextForBrowserContext(content_browser_context); return shell_browser_context->CreateRequestContextForStoragePartition( partition_path, in_memory, protocol_handlers); } ShellBrowserContext* ShellContentBrowserClient::ShellBrowserContextForBrowserContext( BrowserContext* content_browser_context) { if (content_browser_context == browser_context()) return browser_context(); DCHECK_EQ(content_browser_context, off_the_record_browser_context()); return off_the_record_browser_context(); } printing::PrintJobManager* ShellContentBrowserClient::print_job_manager() { return shell_browser_main_parts_->print_job_manager(); } void ShellContentBrowserClient::RenderProcessHostCreated( RenderProcessHost* host) { int id = host->GetID(); if (!master_rph_) master_rph_ = host; // Grant file: scheme to the whole process, since we impose // per-view access checks. content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme( host->GetID(), chrome::kFileScheme); content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme( host->GetID(), "app"); #if defined(ENABLE_PRINTING) host->AddFilter(new PrintingMessageFilter(id)); #endif } bool ShellContentBrowserClient::IsHandledURL(const GURL& url) { if (!url.is_valid()) return false; DCHECK_EQ(url.scheme(), StringToLowerASCII(url.scheme())); // Keep in sync with ProtocolHandlers added by // ShellURLRequestContextGetter::GetURLRequestContext(). static const char* const kProtocolList[] = { chrome::kFileSystemScheme, chrome::kFileScheme, "app", }; for (size_t i = 0; i < arraysize(kProtocolList); ++i) { if (url.scheme() == kProtocolList[i]) return true; } return false; } void ShellContentBrowserClient::AllowCertificateError( int render_process_id, int render_view_id, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, ResourceType::Type resource_type, bool overridable, bool strict_enforcement, const base::Callback<void(bool)>& callback, content::CertificateRequestResultType* result) { VLOG(1) << "AllowCertificateError: " << request_url; CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kIgnoreCertificateErrors)) { *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE; } else *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY; return; } void ShellContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_allowed_schemes) { ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem( additional_allowed_schemes); additional_allowed_schemes->push_back("app"); } #if defined(OS_POSIX) && !defined(OS_MACOSX) void ShellContentBrowserClient::GetAdditionalMappedFilesForChildProcess( const CommandLine& command_line, int child_process_id, std::vector<FileDescriptorInfo>* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->push_back(FileDescriptorInfo(kCrashDumpSignal, FileDescriptor(crash_signal_fd, false))); } } #endif // defined(OS_POSIX) && !defined(OS_MACOSX) QuotaPermissionContext* ShellContentBrowserClient::CreateQuotaPermissionContext() { return new ShellQuotaPermissionContext(); } } // namespace content
37.113586
107
0.756361
ghrhomeDist
3b5d408abc93f3b3eb11822aa3a880398d4bc274
24,036
cpp
C++
source/games/duke/src/hudweapon_r.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
source/games/duke/src/hudweapon_r.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
source/games/duke/src/hudweapon_r.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
//------------------------------------------------------------------------- /* Copyright (C) 1996, 2003 - 3D Realms Entertainment Copyright (C) 2017-2019 Nuke.YKT Copyright (C) 2020 - Christoph Oelckers This file is part of Duke Nukem 3D version 1.5 - Atomic Edition Duke Nukem 3D 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Original Source: 1996 - Todd Replogle Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms */ //------------------------------------------------------------------------- #include "ns.h" #include "global.h" #include "names_r.h" #include "dukeactor.h" BEGIN_DUKE_NS //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- inline static void hud_drawpal(double x, double y, int tilenum, int shade, int orientation, int p, int scale = 32768) { hud_drawsprite(x, y, scale, 0, tilenum, shade, p, 2 | orientation); } inline static void rdmyospal(double x, double y, int tilenum, int shade, int orientation, int p) { hud_drawpal(x, y, tilenum, shade, orientation, p, 36700); } inline static void rd2myospal(double x, double y, int tilenum, int shade, int orientation, int p) { hud_drawpal(x, y, tilenum, shade, orientation, p, 44040); } inline static void rd3myospal(double x, double y, int tilenum, int shade, int orientation, int p) { hud_drawpal(x, y, tilenum, shade, orientation, p, 47040); } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void displaymasks_r(int snum, int p, double smoothratio) { if (ps[snum].scuba_on) { //int pin = 0; // to get the proper clock value with regards to interpolation we have add a smoothratio based offset to the value. double interpclock = PlayClock + (+TICSPERFRAME/65536.) * smoothratio; int pin = RS_STRETCH; hud_drawsprite((320 - (tileWidth(SCUBAMASK) >> 1) - 15), (200 - (tileHeight(SCUBAMASK) >> 1) + bsinf(interpclock, -10)), 49152, 0, SCUBAMASK, 0, p, 2 + 16 + pin); hud_drawsprite((320 - tileWidth(SCUBAMASK + 4)), (200 - tileHeight(SCUBAMASK + 4)), 65536, 0, SCUBAMASK + 4, 0, p, 2 + 16 + pin); hud_drawsprite(tileWidth(SCUBAMASK + 4), (200 - tileHeight(SCUBAMASK + 4)), 65536, 0, SCUBAMASK + 4, 0, p, 2 + 4 + 16 + pin); hud_drawsprite(35, (-1), 65536, 0, SCUBAMASK + 3, 0, p, 2 + 16 + pin); hud_drawsprite(285, 200, 65536, 1024, SCUBAMASK + 3, 0, p, 2 + 16 + pin); } } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void ShowMotorcycle(double x, double y, int tilenum, int shade, int orientation, int p, double a) { hud_drawsprite(x, y, 34816, a, tilenum, shade, p, 2 | orientation); } void ShowBoat(double x, double y, int tilenum, int shade, int orientation, int p, double a) { hud_drawsprite(x, y, 66048, a, tilenum, shade, p, 2 | orientation); } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void displayweapon_r(int snum, double smoothratio) { int cw; int i, j; double weapon_sway, weapon_xoffset, gun_pos, looking_arc, look_anghalf, hard_landing, TiltStatus; char o,pal; signed char shade; auto p = &ps[snum]; auto kb = &p->kickback_pic; o = 0; if (cl_hudinterpolation) { weapon_sway = interpolatedvaluef(p->oweapon_sway, p->weapon_sway, smoothratio); hard_landing = interpolatedvaluef(p->ohard_landing, p->hard_landing, smoothratio); gun_pos = 80 - interpolatedvaluef(p->oweapon_pos * p->oweapon_pos, p->weapon_pos * p->weapon_pos, smoothratio); TiltStatus = !SyncInput() ? p->TiltStatus : interpolatedvaluef(p->oTiltStatus, p->TiltStatus, smoothratio); } else { weapon_sway = p->weapon_sway; hard_landing = p->hard_landing; gun_pos = 80 - (p->weapon_pos * p->weapon_pos); TiltStatus = p->TiltStatus; } look_anghalf = p->angle.look_anghalf(smoothratio); looking_arc = p->angle.looking_arc(smoothratio); hard_landing *= 8.; gun_pos -= fabs(p->GetActor()->s->xrepeat < 8 ? bsinf(weapon_sway * 4., -9) : bsinf(weapon_sway * 0.5, -10)); gun_pos -= hard_landing; weapon_xoffset = (160)-90; weapon_xoffset -= bcosf(weapon_sway * 0.5) * (1. / 1536.); weapon_xoffset -= 58 + p->weapon_ang; if (shadedsector[p->cursectnum] == 1) shade = 16; else shade = p->GetActor()->s->shade; if(shade > 24) shade = 24; pal = p->GetActor()->s->pal == 1 ? 1 : pal = sector[p->cursectnum].floorpal; if(p->newOwner != nullptr || ud.cameraactor != nullptr || p->over_shoulder_on > 0 || (p->GetActor()->s->pal != 1 && p->GetActor()->s->extra <= 0)) return; if(p->last_weapon >= 0) cw = p->last_weapon; else cw = p->curr_weapon; j = 14-p->quick_kick; if(j != 14) { if(p->GetActor()->s->pal == 1) pal = 1; else pal = p->palookup; } if (p->OnMotorcycle) { int temp_kb; if (numplayers == 1) { if (*kb) { shade = 0; if (*kb == 1) { if ((krand()&1) == 1) temp_kb = MOTOHIT+1; else temp_kb = MOTOHIT+2; } else if (*kb == 4) { if ((krand()&1) == 1) temp_kb = MOTOHIT+3; else temp_kb = MOTOHIT+4; } else temp_kb = MOTOHIT; } else temp_kb = MOTOHIT; } else { if (*kb) { shade = 0; if (*kb == 1) temp_kb = MOTOHIT+1; else if (*kb == 2) temp_kb = MOTOHIT+2; else if (*kb == 3) temp_kb = MOTOHIT+3; else if (*kb == 4) temp_kb = MOTOHIT+4; else temp_kb = MOTOHIT; } else temp_kb = MOTOHIT; } ShowMotorcycle(160-look_anghalf, 174, temp_kb, shade, 0, pal, TiltStatus*5); return; } if (p->OnBoat) { int temp2, temp_kb, temp3; temp2 = 0; if (TiltStatus > 0) { if (*kb == 0) temp_kb = BOATHIT+1; else if (*kb <= 3) { temp_kb = BOATHIT+5; temp2 = 1; } else if (*kb <= 6) { temp_kb = BOATHIT+6; temp2 = 1; } else temp_kb = BOATHIT+1; } else if (TiltStatus < 0) { if (*kb == 0) temp_kb = BOATHIT+2; else if (*kb <= 3) { temp_kb = BOATHIT+7; temp2 = 1; } else if (*kb <= 6) { temp_kb = BOATHIT+8; temp2 = 1; } else temp_kb = BOATHIT+2; } else { if (*kb == 0) temp_kb = BOATHIT; else if (*kb <= 3) { temp_kb = BOATHIT+3; temp2 = 1; } else if (*kb <= 6) { temp_kb = BOATHIT+4; temp2 = 1; } else temp_kb = BOATHIT; } if (p->NotOnWater) temp3 = 170; else temp3 = 170 + (*kb>>2); if (temp2) shade = -96; ShowBoat(160-look_anghalf, temp3, temp_kb, shade, 0, pal, TiltStatus); return; } if (p->GetActor()->s->xrepeat < 8) { static int fistsign; if (p->jetpack_on == 0) { i = p->GetActor()->s->xvel; looking_arc += 32 - (i >> 1); fistsign += i >> 1; } double owo = weapon_xoffset; weapon_xoffset += bsinf(fistsign, -10); hud_draw(weapon_xoffset + 250 - look_anghalf, looking_arc + 258 - abs(bsinf(fistsign, -8)), FIST, shade, o); weapon_xoffset = owo; weapon_xoffset -= bsinf(fistsign, -10); hud_draw(weapon_xoffset + 40 - look_anghalf, looking_arc + 200 + abs(bsinf(fistsign, -8)), FIST, shade, o | 4); } else { int pin = 0; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaycrowbar = [&] { static const short kb_frames[] = { 0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7 }; static const short kb_ox[] = { 310,342,364,418,350,316,282,288,0,0 }; static const short kb_oy[] = { 300,362,320,268,248,248,277,420,0,0 }; double x; short y; x = weapon_xoffset + ((kb_ox[kb_frames[*kb]] >> 1) - 12); y = 200 - (244 - kb_oy[kb_frames[*kb]]); hud_drawpal(x - look_anghalf, looking_arc + y - gun_pos, KNEE + kb_frames[*kb], shade, 0, pal); }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displayslingblade = [&] { static const short kb_frames[] = { 0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7 }; static const short kb_ox[] = { 580,676,310,491,356,210,310,614 }; static const short kb_oy[] = { 369,363,300,323,371,400,300,440 }; double x; short y; x = weapon_xoffset + ((kb_ox[kb_frames[*kb]] >> 1) - 12); y = 210 - (244 - kb_oy[kb_frames[*kb]]); hud_drawpal(x - look_anghalf + 20, looking_arc + y - gun_pos - 80, SLINGBLADE + kb_frames[*kb], shade, 0, pal); }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaybowlingball = [&] { weapon_xoffset += 8; gun_pos -= 10; if (p->ammo_amount[BOWLING_WEAPON]) { hud_drawpal(weapon_xoffset + 162 - look_anghalf, looking_arc + 214 - gun_pos + (*kb << 3), BOWLINGBALLH, shade, o, pal); } else { rdmyospal(weapon_xoffset + 162 - look_anghalf, looking_arc + 214 - gun_pos, HANDTHROW + 5, shade, o, pal); } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaypowderkeg = [&] { weapon_xoffset += 8; gun_pos -= 10; if (p->ammo_amount[POWDERKEG_WEAPON]) { rdmyospal(weapon_xoffset + 180 - look_anghalf, looking_arc + 214 - gun_pos + (*kb << 3), POWDERH, shade, o, pal); rdmyospal(weapon_xoffset + 90 - look_anghalf, looking_arc + 214 - gun_pos + (*kb << 3), POWDERH, shade, o | 4, pal); } else { rdmyospal(weapon_xoffset + 162 - look_anghalf, looking_arc + 214 - gun_pos, HANDTHROW + 5, shade, o, pal); } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaycrossbow = [&] { if (!(gs.displayflags & DUKE3D_NO_WIDESCREEN_PINNING)) pin = RS_ALIGN_R; static const uint8_t kb_frames[] = { 0,1,1,2,2,3,2,3,2,3,2,2,2,2,2,2,2,2,2,4,4,4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7 }; if (kb_frames[*kb] == 2 || kb_frames[*kb] == 3) { rdmyospal((weapon_xoffset + 200) - look_anghalf, looking_arc + 250 - gun_pos, RPGGUN + kb_frames[*kb], shade, o | pin, pal); } else if (kb_frames[*kb] == 1) { rdmyospal((weapon_xoffset + 200) - look_anghalf, looking_arc + 250 - gun_pos, RPGGUN + kb_frames[*kb], 0, o | pin, pal); } else { rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 255 - gun_pos, RPGGUN + kb_frames[*kb], shade, o | pin, pal); } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaychicken = [&] { if (!(gs.displayflags & DUKE3D_NO_WIDESCREEN_PINNING)) pin = RS_ALIGN_R; if (*kb) { static const uint8_t kb_frames[] = { 0,1,1,2,2,3,2,3,2,3,2,2,2,2,2,2,2,2,2,4,4,4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7 }; if (kb_frames[*kb] == 2 || kb_frames[*kb] == 3) { rdmyospal((weapon_xoffset + 200) - look_anghalf, looking_arc + 250 - gun_pos, RPGGUN2 + kb_frames[*kb], shade, o | pin, pal); } else if (kb_frames[*kb] == 1) { rdmyospal((weapon_xoffset + 200) - look_anghalf, looking_arc + 250 - gun_pos, RPGGUN2 + kb_frames[*kb], 0, o | pin, pal); } else { rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 255 - gun_pos, RPGGUN2 + kb_frames[*kb], shade, o | pin, pal); } } else { if (ud.multimode < 2) { if (chickenphase) { rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 222 - gun_pos, RPGGUN2 + 7, shade, o | pin, pal); } else if ((krand() & 15) == 5) { S_PlayActorSound(327, p->GetActor()); rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 222 - gun_pos, RPGGUN2 + 7, shade, o | pin, pal); chickenphase = 6; } else { rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 225 - gun_pos, RPGGUN2, shade, o | pin, pal); } } else { rdmyospal((weapon_xoffset + 210) - look_anghalf, looking_arc + 225 - gun_pos, RPGGUN2, shade, o | pin, pal); } } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displayshotgun = [&] { weapon_xoffset -= 8; { double x; short y; static const short kb_frames3[] = { 0,0,1,1,2,2,5,5,6,6,7,7,8,8,0,0,0,0,0,0,0 }; static const short kb_frames2[] = { 0,0,3,3,4,4,5,5,6,6,7,7,8,8,0,0,20,20,21,21,21,21,20,20,20,20,0,0 }; static const short kb_frames[] = { 0,0,1,1,2,2,3,3,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,0,0,20,20,21,21,21,21,20,20,20,20,0,0 }; static const short kb_ox[] = { 300,300,300,300,300,330,320,310,305,306,302 }; static const short kb_oy[] = { 315,300,302,305,302,302,303,306,302,404,384 }; short tm; tm = 180; if (p->shotgun_state[1]) { if ((*kb) < 26) { if (kb_frames[*kb] == 3 || kb_frames[*kb] == 4) shade = 0; x = weapon_xoffset + ((kb_ox[kb_frames[*kb]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames[*kb]]); hud_drawpal(x + 64 - look_anghalf, y + looking_arc - gun_pos, SHOTGUN + kb_frames[*kb], shade, 0, pal); } else { if (kb_frames[*kb] > 0) { x = weapon_xoffset + ((kb_ox[kb_frames[(*kb) - 11]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames[(*kb) - 11]]); } else { x = weapon_xoffset + ((kb_ox[kb_frames[*kb]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames[*kb]]); } switch (*kb) { case 23: y += 60; break; case 24: y += 30; break; } hud_drawpal(x + 64 - look_anghalf, y + looking_arc - gun_pos, SHOTGUN + kb_frames[*kb], shade, 0, pal); if (kb_frames[*kb] == 21) hud_drawpal(x + 96 - look_anghalf, y + looking_arc - gun_pos, SHOTGUNSHELLS, shade, 0, pal); } } else { if ((*kb) < 16) { if (p->shotgun_state[0]) { if (kb_frames2[*kb] == 3 || kb_frames2[*kb] == 4) shade = 0; x = weapon_xoffset + ((kb_ox[kb_frames2[*kb]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames2[*kb]]); hud_drawpal(x + 64 - look_anghalf, y + looking_arc - gun_pos, SHOTGUN + kb_frames2[*kb], shade, 0, pal); } else { if (kb_frames3[*kb] == 1 || kb_frames3[*kb] == 2) shade = 0; x = weapon_xoffset + ((kb_ox[kb_frames3[*kb]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames3[*kb]]); hud_drawpal(x + 64 - look_anghalf, y + looking_arc - gun_pos, SHOTGUN + kb_frames3[*kb], shade, 0, pal); } } else if (p->shotgun_state[0]) { if (kb_frames2[*kb] > 0) { x = weapon_xoffset + ((kb_ox[kb_frames2[(*kb) - 11]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames2[(*kb) - 11]]); } else { x = weapon_xoffset + ((kb_ox[kb_frames2[*kb]] >> 1) - 12); y = tm - (244 - kb_oy[kb_frames2[*kb]]); } switch (*kb) { case 23: y += 60; break; case 24: y += 30; break; } hud_drawpal(x + 64 - look_anghalf, y + looking_arc - gun_pos, SHOTGUN + kb_frames2[*kb], shade, 0, pal); if (kb_frames2[*kb] == 21) hud_drawpal(x + 96 - look_anghalf, y + looking_arc - gun_pos, SHOTGUNSHELLS, shade, 0, pal); } } } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displayrifle = [&] { if (*kb > 0) gun_pos -= bsinf((*kb) << 7, -12); if (*kb > 0 && p->GetActor()->s->pal != 1) weapon_xoffset += 1 - (rand() & 3); switch (*kb) { case 0: hud_drawpal(weapon_xoffset + 178 - look_anghalf + 30, looking_arc + 233 - gun_pos + 5, CHAINGUN, shade, o, pal); break; default: shade = 0; if (*kb < 8) { i = rand() & 7; hud_drawpal(weapon_xoffset + 178 - look_anghalf + 30, looking_arc + 233 - gun_pos + 5, CHAINGUN + 1, shade, o, pal); } else hud_drawpal(weapon_xoffset + 178 - look_anghalf + 30, looking_arc + 233 - gun_pos + 5, CHAINGUN + 2, shade, o, pal); break; } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaypistol = [&] { if ((*kb) < 22) { static const uint8_t kb_frames[] = { 0,0,1,1,2,2,3,3,4,4,6,6,6,6,5,5,4,4,3,3,0,0 }; static const short kb_ox[] = { 194,190,185,208,215,215,216,216,201,170 }; static const short kb_oy[] = { 256,249,248,238,228,218,208,256,245,258 }; double x; short y; x = weapon_xoffset + (kb_ox[kb_frames[*kb]] - 12); y = 244 - (244 - kb_oy[kb_frames[*kb]]); if (kb_frames[*kb]) shade = 0; rdmyospal(x - look_anghalf, y + looking_arc - gun_pos, FIRSTGUN + kb_frames[*kb], shade, 0, pal); } else { static const short kb_frames[] = { 0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,1,1,0,0 }; static const short kb_ox[] = { 244,244,244 }; static const short kb_oy[] = { 256,249,248 }; double x; short dx; short y; short dy; x = weapon_xoffset + (kb_ox[kb_frames[(*kb) - 22]] - 12); y = 244 - (244 - kb_oy[kb_frames[(*kb) - 22]]); switch (*kb) { case 28: dy = 10; dx = 5; break; case 29: dy = 20; dx = 10; break; case 30: dy = 30; dx = 15; break; case 31: dy = 40; dx = 20; break; case 32: dy = 50; dx = 25; break; case 33: dy = 40; dx = 20; break; case 34: dy = 30; dx = 15; break; case 35: dy = 20; dx = 10; break; case 36: dy = 10; dx = 5; break; default: dy = 0; dx = 0; break; } rdmyospal(x - look_anghalf - dx, y + looking_arc - gun_pos + dy, FIRSTGUNRELOAD + kb_frames[(*kb) - 22], shade, 0, pal); } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaydynamite = [&] { gun_pos -= 9 * (*kb); rdmyospal(weapon_xoffset + 190 - look_anghalf, looking_arc + 260 - gun_pos, HANDTHROW, shade, o, pal); }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaythrowingdynamite = [&] { int dx; int x; int dy; dx = 25; x = 100; dy = 20; if ((*kb) < 20) { if (!(gs.displayflags & DUKE3D_NO_WIDESCREEN_PINNING)) pin = RS_ALIGN_R; static const int8_t remote_frames[] = { 1,1,1,1,1,2,2,2,2,3,3,3,4,4,4,5,5,5,5,5,6,6,6 }; if (*kb) { if ((*kb) < 5) { rdmyospal(weapon_xoffset + x + 190 - look_anghalf - dx, looking_arc + 258 - gun_pos - 64 + p->detonate_count - dy, RRTILE1752, 0, o | pin, pal); } rdmyospal(weapon_xoffset + x + 190 - look_anghalf, looking_arc + 258 - gun_pos - dy, HANDTHROW + remote_frames[*kb], shade, o | pin, pal); } else { if ((*kb) < 5) { rdmyospal(weapon_xoffset + x + 190 - look_anghalf - dx, looking_arc + 258 - gun_pos - 64 + p->detonate_count - dy, RRTILE1752, 0, o | pin, pal); } rdmyospal(weapon_xoffset + x + 190 - look_anghalf, looking_arc + 258 - gun_pos - dy, HANDTHROW + 1, shade, o | pin, pal); } } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaytits = [&] { if (*kb) { shade = 0; rd3myospal(150 + (weapon_xoffset / 2.) - look_anghalf, 266 + (looking_arc / 2.) - gun_pos, DEVISTATOR, shade, o, pal); } else rd3myospal(150 + (weapon_xoffset / 2.) - look_anghalf, 266 + (looking_arc / 2.) - gun_pos, DEVISTATOR + 1, shade, o, pal); }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displayblaster = [&] { if (!(gs.displayflags & DUKE3D_NO_WIDESCREEN_PINNING)) pin = RS_ALIGN_R; if ((*kb)) { char cat_frames[] = { 0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; rdmyospal(weapon_xoffset + 260 - look_anghalf, looking_arc + 215 - gun_pos, FREEZE + cat_frames[*kb], -32, o | pin, pal); } else rdmyospal(weapon_xoffset + 260 - look_anghalf, looking_arc + 215 - gun_pos, FREEZE, shade, o | pin, pal); }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- auto displaysaw = [&] { weapon_xoffset += 28; looking_arc += 18; if ((*kb) == 0) { rd2myospal(weapon_xoffset + 188 - look_anghalf, looking_arc + 240 - gun_pos, SHRINKER, shade, o, pal); } else { if (p->GetActor()->s->pal != 1) { weapon_xoffset += rand() & 3; gun_pos += (rand() & 3); } if (cw == BUZZSAW_WEAPON) { rd2myospal(weapon_xoffset + 184 - look_anghalf, looking_arc + 240 - gun_pos, GROWSPARK + ((*kb) & 2), shade, o, 0); } else { signed char kb_frames[] = { 1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0 }; short frm = kb_frames[*kb]; rd2myospal(weapon_xoffset + 184 - look_anghalf, looking_arc + 240 - gun_pos, SHRINKER + frm, shade, o, 0); } } }; //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- switch (cw) { case KNEE_WEAPON: displaycrowbar(); break; case SLINGBLADE_WEAPON: displayslingblade(); break; case POWDERKEG_WEAPON: displaypowderkeg(); break; case BOWLING_WEAPON: displaybowlingball(); break; case CROSSBOW_WEAPON: displaycrossbow(); break; case CHICKEN_WEAPON: displaychicken(); break; case SHOTGUN_WEAPON: displayshotgun(); break; case RIFLEGUN_WEAPON: displayrifle(); break; case PISTOL_WEAPON: displaypistol(); break; case DYNAMITE_WEAPON: displaydynamite(); break; case THROWINGDYNAMITE_WEAPON: displaythrowingdynamite(); break; case TIT_WEAPON: displaytits(); break; case MOTORCYCLE_WEAPON: case BOAT_WEAPON: break; case ALIENBLASTER_WEAPON: displayblaster(); break; case THROWSAW_WEAPON: case BUZZSAW_WEAPON: displaysaw(); break; } } } END_DUKE_NS
26.442244
164
0.497462
DosFreak
3b5d8fb02ccc621c836803679fc4f732ae9c6ca3
2,731
cpp
C++
engine/engine/core/math/tests/so2.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
engine/engine/core/math/tests/so2.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
engine/engine/core/math/tests/so2.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "engine/core/math/so2.hpp" #include <vector> #include "gtest/gtest.h" namespace isaac { TEST(SO2, composition) { SO2d rot1 = SO2d::FromAngle(1.1); SO2d rot2 = SO2d::FromAngle(1.7); SO2d rot3 = SO2d::FromAngle(2.5); SO2d rot4 = SO2d::FromAngle(0.535); EXPECT_NEAR(rot1.angle(), 1.1, 1e-7); EXPECT_NEAR(rot2.angle(), 1.7, 1e-7); EXPECT_NEAR(rot3.angle(), 2.5, 1e-7); EXPECT_NEAR(rot4.angle(), 0.535, 1e-7); EXPECT_NEAR((rot1 * rot2 * rot3 * rot4).angle(), SO2d::FromAngle(rot1.angle() + rot2.angle() + rot3.angle() + rot4.angle()).angle(), 1e-7); } TEST(SO2, angle) { SO2d rot1 = SO2d::FromAngle(1.1); SO2d rot2 = SO2d::FromAngle(1.7); SO2d rot3 = SO2d::FromAngle(2.5); SO2d rot4 = SO2d::FromAngle(0.535); EXPECT_NEAR(rot1.angle(), 1.1, 1e-7); EXPECT_NEAR(rot2.angle(), 1.7, 1e-7); EXPECT_NEAR(rot3.angle(), 2.5, 1e-7); EXPECT_NEAR(rot4.angle(), 0.535, 1e-7); } TEST(SO2, inverse) { SO2d rot1 = SO2d::FromAngle(1.1); SO2d rot2 = SO2d::FromAngle(1.7); SO2d rot3 = SO2d::FromAngle(2.5); SO2d rot4 = SO2d::FromAngle(0.535); EXPECT_NEAR(rot1.inverse().angle(), -1.1, 1e-7); EXPECT_NEAR(rot2.inverse().angle(), -1.7, 1e-7); EXPECT_NEAR(rot3.inverse().angle(), -2.5, 1e-7); EXPECT_NEAR(rot4.inverse().angle(), -0.535, 1e-7); } TEST(SO2, vector2) { SO2d rot = SO2d::FromDirection(1.0, 1.0); Vector2d vec1(2.0, 0.0); Vector2d vec2 = rot * vec1; Vector2d vec3 = rot * vec2; Vector2d vec4 = rot * vec3; Vector2d vec5 = rot * vec4; Vector2d vec6 = rot * vec5; Vector2d vec7 = rot * vec6; Vector2d vec8 = rot * vec7; Vector2d vec9 = rot * vec8; const double sqrt2 = std::sqrt(2.0); EXPECT_NEAR(vec2.x(), sqrt2, 1e-7); EXPECT_NEAR(vec2.y(), sqrt2, 1e-7); EXPECT_NEAR(vec3.x(), 0.0, 1e-7); EXPECT_NEAR(vec3.y(), 2.0, 1e-7); EXPECT_NEAR(vec4.x(), -sqrt2, 1e-7); EXPECT_NEAR(vec4.y(), sqrt2, 1e-7); EXPECT_NEAR(vec5.x(), -2.0, 1e-7); EXPECT_NEAR(vec5.y(), 0.0, 1e-7); EXPECT_NEAR(vec6.x(), -sqrt2, 1e-7); EXPECT_NEAR(vec6.y(), -sqrt2, 1e-7); EXPECT_NEAR(vec7.x(), 0.0, 1e-7); EXPECT_NEAR(vec7.y(), -2.0, 1e-7); EXPECT_NEAR(vec8.x(), sqrt2, 1e-7); EXPECT_NEAR(vec8.y(), -sqrt2, 1e-7); EXPECT_NEAR(vec9.x(), 2.0, 1e-7); EXPECT_NEAR(vec9.y(), 0.0, 1e-7); } } // namespace isaac
29.684783
97
0.650311
ddr95070
3b5e5b3f8b1e92c69cdec142e4a70fa0a041498a
17,015
hpp
C++
toonz/sources/include/tcg/hpp/triangulate.hpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
3,710
2016-03-26T00:40:48.000Z
2022-03-31T21:35:12.000Z
toonz/sources/include/tcg/hpp/triangulate.hpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
4,246
2016-03-26T01:21:45.000Z
2022-03-31T23:10:47.000Z
toonz/sources/include/tcg/hpp/triangulate.hpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
633
2016-03-26T00:42:25.000Z
2022-03-17T02:55:13.000Z
#pragma once #ifndef TCG_TRIANGULATE_HPP #define TCG_TRIANGULATE_HPP // tcg includes #include "../triangulate.h" #include "../traits.h" #include "../point_ops.h" // OS-specific includes #if defined(_WIN32) #include "windows.h" #include <GL/glu.h> #elif defined(MACOSX) #include <GLUT/glut.h> #elif defined(LINUX) || defined(FREEBSD) #include <GL/glut.h> #include <cstring> #endif #ifndef TCG_GLU_CALLBACK #ifdef WIN32 #define TCG_GLU_CALLBACK void(CALLBACK *)() #else #define TCG_GLU_CALLBACK void (*)() #endif #endif #ifndef CALLBACK #define CALLBACK #endif namespace tcg { //************************************************************************************** // GLU Tessellator Callbacks //************************************************************************************** namespace detail { template <typename mesh_type> struct CBackData { mesh_type *m_mesh; int m_triangle[3]; int m_i; }; //============================================================================ // NOTE: must be declared with CALLBACK directive template <typename mesh_type> void CALLBACK tessBegin(GLenum type, void *polygon_data) { assert(type == GL_TRIANGLES); CBackData<mesh_type> *data = (CBackData<mesh_type> *)polygon_data; data->m_i = 0; } //---------------------------------------------------------------------------- template <typename mesh_type> void CALLBACK tessEnd(void *polygon_data) { CBackData<mesh_type> *data = (CBackData<mesh_type> *)polygon_data; assert(data->m_i == 0); } //---------------------------------------------------------------------------- template <typename mesh_type, typename vertex_type> void CALLBACK tessVertex(void *vertex_data, void *polygon_data) { typedef typename mesh_type::vertex_type::point_type point_type; CBackData<mesh_type> *data = (CBackData<mesh_type> *)polygon_data; vertex_type *vData = (vertex_type *)vertex_data; GLdouble(&pos)[3] = TriMeshStuff::glu_vertex_traits<vertex_type>::vertex3d(*vData); int &idx = TriMeshStuff::glu_vertex_traits<vertex_type>::index(*vData); if (idx < 0) { data->m_mesh->addVertex( typename mesh_type::vertex_type(point_type(pos[0], pos[1]))); idx = data->m_mesh->verticesCount() - 1; } data->m_triangle[data->m_i] = idx; data->m_i = (data->m_i + 1) % 3; if (data->m_i == 0) data->m_mesh->addFace(data->m_triangle[0], data->m_triangle[1], data->m_triangle[2]); } //---------------------------------------------------------------------------- // Supplied to ensure that triangle primitives are always of type GL_TRIANGLE template <typename mesh_type> void CALLBACK edgeFlag(GLboolean flag) {} } // namespace tcg::detail //************************************************************************************** // Polygon triangulation //************************************************************************************** namespace detail { template <typename Func> void gluRegister(GLUtesselator *tess, GLenum which, Func *func) { gluTessCallback(tess, which, (TCG_GLU_CALLBACK)func); } } // namespace tcg::detail //--------------------------------------------------------------------------- template <typename ForIt, typename ContainersReader> void gluTriangulate(ForIt tribeBegin, ForIt tribeEnd, ContainersReader &meshes_reader) { using namespace detail; typedef typename tcg::traits<typename ForIt::value_type>::pointed_type family_type; typedef typename tcg::traits<typename family_type::value_type>::pointed_type polygon_type; typedef typename polygon_type::value_type vertex_type; typedef typename tcg::container_reader_traits<ContainersReader> output; typedef typename tcg::traits<typename output::value_type>::pointed_type mesh_type; GLUtesselator *tess = gluNewTess(); // create a tessellator assert(tess); // Declare callbacks // NOTE: On g++, it seems that at this point each of the callbacks still have // undefined type. // We use the above gluRegister template to force the compiler to generate // these types. gluRegister(tess, GLU_TESS_BEGIN_DATA, tessBegin<mesh_type>); gluRegister(tess, GLU_TESS_END_DATA, tessEnd<mesh_type>); gluRegister(tess, GLU_TESS_VERTEX_DATA, tessVertex<mesh_type, vertex_type>); gluRegister(tess, GLU_TESS_EDGE_FLAG, edgeFlag<mesh_type>); output::openContainer(meshes_reader); // Iterate the tribe. For every polygons family, associate one output mesh for (ForIt it = tribeBegin; it != tribeEnd; ++it) { // Build the output mesh and initialize stuff mesh_type *mesh = new mesh_type; CBackData<mesh_type> cbData; // Callback Data about the mesh cbData.m_mesh = mesh; // Tessellate the family gluTessBeginPolygon(tess, (void *)&cbData); typename family_type::iterator ft, fEnd = (*it)->end(); for (ft = (*it)->begin(); ft != fEnd; ++ft) { gluTessBeginContour(tess); typename polygon_type::iterator pt, pEnd = (*ft)->end(); for (pt = (*ft)->begin(); pt != pEnd; ++pt) gluTessVertex( tess, TriMeshStuff::glu_vertex_traits<vertex_type>::vertex3d(*pt), (void *)&*pt); gluTessEndContour(tess); } gluTessEndPolygon(tess); // Invokes the family tessellation output::addElement(meshes_reader, mesh); } gluDeleteTess(tess); // delete after tessellation output::closeContainer(meshes_reader); } //************************************************************************************** // Mesh refinement //************************************************************************************** namespace detail { template <typename mesh_type> inline void touchEdge(std::vector<UCHAR> &buildEdge, mesh_type &mesh, int e) { typename mesh_type::edge_type &ed = mesh.edge(e); int f1 = ed.face(0), f2 = ed.face(1); if (f1 >= 0) { typename mesh_type::face_type &f = mesh.face(f1); buildEdge[f.edge(0)] = 1, buildEdge[f.edge(1)] = 1, buildEdge[f.edge(2)] = 1; } if (f2 >= 0) { typename mesh_type::face_type &f = mesh.face(f2); buildEdge[f.edge(0)] = 1, buildEdge[f.edge(1)] = 1, buildEdge[f.edge(2)] = 1; } } //--------------------------------------------------------------------------- template <typename mesh_type> inline void touchVertex(std::vector<UCHAR> &buildEdge, mesh_type &mesh, int v) { // Sign all adjacent edges and adjacent faces' edges to v typename mesh_type::vertex_type &vx = mesh.vertex(v); const tcg::list<int> &incidentEdges = vx.edges(); tcg::list<int>::const_iterator it; for (it = incidentEdges.begin(); it != incidentEdges.end(); ++it) touchEdge(buildEdge, mesh, *it); } //================================================================================ template <typename mesh_type> class BoundaryEdges { std::vector<UCHAR> m_boundaryVertices; const mesh_type &m_mesh; public: BoundaryEdges(const mesh_type &mesh) : m_mesh(mesh) { const tcg::list<typename mesh_type::edge_type> &edges = mesh.edges(); const tcg::list<typename mesh_type::vertex_type> &vertices = mesh.vertices(); m_boundaryVertices.resize(vertices.nodesCount(), 0); typename tcg::list<typename mesh_type::edge_type>::const_iterator it; for (it = edges.begin(); it != edges.end(); ++it) { if (it->face(0) < 0 || it->face(1) < 0) { m_boundaryVertices[it->vertex(0)] = true; m_boundaryVertices[it->vertex(1)] = true; } } } ~BoundaryEdges() {} void setBoundaryVertex(int v) { m_boundaryVertices.resize(m_mesh.vertices().nodesCount(), 0); m_boundaryVertices[v] = 1; } bool isBoundaryVertex(int v) const { return v < int(m_boundaryVertices.size()) && m_boundaryVertices[v]; } bool isBoundaryEdge(int e) const { const typename mesh_type::edge_type &ed = m_mesh.edge(e); return ed.face(0) < 0 || ed.face(1) < 0; } }; } // namespace tcg::detail //============================================================================= template <typename mesh_type> void TriMeshStuff::DefaultEvaluator<mesh_type>::actionSort( const mesh_type &mesh, int e, typename ActionEvaluator<mesh_type>::Action *actionSequence) { typedef ActionEvaluator<mesh_type> ActionEvaluator; int count = 0; memset(actionSequence, ActionEvaluator::NONE, 3 * sizeof(typename ActionEvaluator::Action)); // Try to minimize the edge length deviation in e's neighbourhood const typename mesh_type::edge_type &ed = mesh.edge(e); int f1 = ed.face(0), f2 = ed.face(1); const TPointD *v1, *v2, *v3, *v4; double length[6]; v1 = &mesh.vertex(ed.vertex(0)).P(); v2 = &mesh.vertex(ed.vertex(1)).P(); length[0] = norm(*v2 - *v1); double lengthMax = length[0], lengthMin = length[0]; if (f1 >= 0) { v3 = &mesh.vertex(mesh.otherFaceVertex(f1, e)).P(); length[1] = norm(*v3 - *v1); length[2] = norm(*v3 - *v2); lengthMax = std::max({lengthMax, length[1], length[2]}); lengthMin = std::min({lengthMin, length[1], length[2]}); } if (f2 >= 0) { v4 = &mesh.vertex(mesh.otherFaceVertex(f2, e)).P(); length[3] = norm(*v4 - *v1); length[4] = norm(*v4 - *v2); lengthMax = std::max({lengthMax, length[3], length[4]}); lengthMin = std::min({lengthMin, length[3], length[4]}); } if (f1 >= 0 && f2 >= 0) { // Build the edge lengths length[5] = norm(*v4 - *v3); // Evaluate swap - take the triangles with least maximum mean boundary edge double m1 = (length[0] + length[1] + length[2]) / 3.0; double m2 = (length[0] + length[3] + length[4]) / 3.0; double m3 = (length[5] + length[1] + length[3]) / 3.0; double m4 = (length[5] + length[2] + length[4]) / 3.0; if (std::max(m3, m4) < std::max(m1, m2) - 1e-5) actionSequence[count++] = ActionEvaluator::SWAP; // NOTE: The original swap evaluation was about maximizing the minimal face // angle. // However, this requires quite some cross products - the above test is // sufficiently // simple and has a similar behaviour. // Evaluate collapse if (length[0] < m_collapseValue) actionSequence[count++] = ActionEvaluator::COLLAPSE; } // Evaluate split if (length[0] > m_splitValue) actionSequence[count++] = ActionEvaluator::SPLIT; } //============================================================================= namespace detail { template <typename mesh_type> inline bool testSwap(const mesh_type &mesh, int e) { // Retrieve adjacent faces const typename mesh_type::edge_type &ed = mesh.edge(e); int f1 = ed.face(0), f2 = ed.face(1); if (f1 < 0 || f2 < 0) return false; // Retrieve the 4 adjacent vertices const typename mesh_type::vertex_type &v1 = mesh.vertex(ed.vertex(0)); const typename mesh_type::vertex_type &v2 = mesh.vertex(ed.vertex(1)); const typename mesh_type::vertex_type &v3 = mesh.vertex(mesh.otherFaceVertex(f1, ed.getIndex())); const typename mesh_type::vertex_type &v4 = mesh.vertex(mesh.otherFaceVertex(f2, ed.getIndex())); // Make sure that vertex v4 lies between the semiplane generated by v3v1 and // v3v2 TPointD a(v1.P() - v3.P()), b(v2.P() - v3.P()); double normA = norm(a), normB = norm(b); if (normA < 1e-5 || normB < 1e-5) return false; a = a * (1.0 / normA); b = b * (1.0 / normB); TPointD c(v4.P() - v1.P()), d(v4.P() - v2.P()); double normC = norm(c), normD = norm(d); if (normC < 1e-5 || normD < 1e-5) return false; c = c * (1.0 / normC); d = d * (1.0 / normD); double crossAC = point_ops::cross(a, c); int signAC = crossAC < -1e-5 ? -1 : crossAC > 1e-5 ? 1 : 0; double crossBD = point_ops::cross(b, d); int signBD = crossBD < -1e-5 ? -1 : crossBD > 1e-5 ? 1 : 0; return signAC == -signBD; } //---------------------------------------------------------------------------- // Tests edge e for admissibility of ad edge collapse. Edge e must not have // adjacent // faces with boundary components. // Furthermore, we must test that faces adjacent to f1 and f2 keep e on the same // side of // the line passing through v3v1 and v3v2. template <typename mesh_type> inline bool testCollapse(const mesh_type &mesh, int e, const BoundaryEdges<mesh_type> &boundary) { // Any face adjacent to e must have no boundary edge const typename mesh_type::edge_type &ed = mesh.edge(e); int f1 = ed.face(0), f2 = ed.face(1); if (f1 < 0 || f2 < 0) return false; int v1 = mesh.edge(e).vertex(0), v2 = mesh.edge(e).vertex(1); if (boundary.isBoundaryVertex(v1) || boundary.isBoundaryVertex(v2)) return false; // Test faces adjacent to v1 or v2. Since one of their vertices will change, // we must make sure that their //'side' does not change too. int v = mesh.otherFaceVertex(f1, e); int l = mesh.edgeInciding(v1, v); int f = mesh.edge(l).face(0) == f1 ? mesh.edge(l).face(1) : mesh.edge(l).face(0); int vNext = mesh.otherFaceVertex(f, l); while (f != f2) { // Test face f if (tsign(point_ops::cross(mesh.vertex(vNext).P() - mesh.vertex(v).P(), mesh.vertex(v2).P() - mesh.vertex(v).P())) != tsign(point_ops::cross(mesh.vertex(vNext).P() - mesh.vertex(v).P(), mesh.vertex(v1).P() - mesh.vertex(v).P()))) return false; // Update vars v = vNext; l = mesh.edgeInciding(v1, v); f = mesh.edge(l).face(0) == f ? mesh.edge(l).face(1) : mesh.edge(l).face(0); vNext = mesh.otherFaceVertex(f, l); } // Same with respect to v2 v = mesh.otherFaceVertex(f1, e); l = mesh.edgeInciding(v2, v); f = mesh.edge(l).face(0) == f1 ? mesh.edge(l).face(1) : mesh.edge(l).face(0); vNext = mesh.otherFaceVertex(f, l); while (f != f2) { // Test face f if (tsign(point_ops::cross(mesh.vertex(vNext).P() - mesh.vertex(v).P(), mesh.vertex(v2).P() - mesh.vertex(v).P())) != tsign(point_ops::cross(mesh.vertex(vNext).P() - mesh.vertex(v).P(), mesh.vertex(v1).P() - mesh.vertex(v).P()))) return false; // Update vars v = vNext; l = mesh.edgeInciding(v2, v); f = mesh.edge(l).face(0) == f ? mesh.edge(l).face(1) : mesh.edge(l).face(0); vNext = mesh.otherFaceVertex(f, l); } return true; } } // namespace tcg::detail //---------------------------------------------------------------------------- template <typename mesh_type> void refineMesh(mesh_type &mesh, TriMeshStuff::ActionEvaluator<mesh_type> &eval, unsigned long maxActions) { using namespace detail; typedef TriMeshStuff::ActionEvaluator<mesh_type> Evaluator; typedef typename Evaluator::Action Action; // DIAGNOSTICS_TIMER("simplifyMesh"); // Build boundary edges. They will not be altered by the simplification // procedure. detail::BoundaryEdges<mesh_type> boundary(mesh); Action actions[3], *act, *actEnd = actions + 3; tcg::list<Edge> &edges = mesh.edges(); tcg::list<Edge>::iterator it; // DIAGNOSTICS_SET("Simplify | Vertex count (before simplify)", // mesh.vertexCount()); // DIAGNOSTICS_SET("Simplify | Edges count (before simplify)", edges.size()); // Build a vector of the edges to be analyzed std::vector<UCHAR> buildEdge(edges.nodesCount(), 1); int touchedIdx; bool boundaryEdge; cycle: if (maxActions-- == 0) return; // Analyze mesh for possible updates. Perform the first one. for (it = edges.begin(); it != edges.end(); ++it) { if (!buildEdge[it.m_idx]) continue; boundaryEdge = boundary.isBoundaryEdge(it.m_idx); eval.actionSort(mesh, it.m_idx, actions); for (act = actions; act < actEnd; ++act) { // Try to perform the i-th action if (*act == Evaluator::NONE) break; else if (!boundaryEdge && *act == Evaluator::SWAP && testSwap(mesh, it.m_idx)) { touchedIdx = mesh.swapEdge(it.m_idx); touchEdge(buildEdge, mesh, touchedIdx); goto cycle; } else if (!boundaryEdge && *act == Evaluator::COLLAPSE && testCollapse(mesh, it.m_idx, boundary)) { touchedIdx = mesh.collapseEdge(it.m_idx); touchVertex(buildEdge, mesh, touchedIdx); goto cycle; } else if (*act == Evaluator::SPLIT) { Edge &ed = mesh.edge(it.m_idx); touchVertex(buildEdge, mesh, ed.vertex(0)); touchVertex(buildEdge, mesh, ed.vertex(1)); touchedIdx = mesh.splitEdge(it.m_idx); if (buildEdge.size() < edges.size()) buildEdge.resize(edges.size()); touchVertex(buildEdge, mesh, touchedIdx); if (boundaryEdge) boundary.setBoundaryVertex(touchedIdx); goto cycle; } } buildEdge[it.m_idx] = 0; } // DIAGNOSTICS_SET("Simplify | Vertex count (after simplify)", // mesh.vertexCount()); // DIAGNOSTICS_SET("Simplify | Edges count (after simplify)", edges.size()); } } // namespace tcg #endif // TCG_TRIANGULATE_HPP
32.043315
88
0.595416
rozhuk-im
3b5fb1de34b20a87477b2c36c828330d52cf2501
5,130
cpp
C++
Malmo/test/CppTests/test_mission.cpp
geekstor/malmo-1
ce1e7972d9c1d6244a2615af0dc80f709222c6fd
[ "MIT" ]
null
null
null
Malmo/test/CppTests/test_mission.cpp
geekstor/malmo-1
ce1e7972d9c1d6244a2615af0dc80f709222c6fd
[ "MIT" ]
null
null
null
Malmo/test/CppTests/test_mission.cpp
geekstor/malmo-1
ce1e7972d9c1d6244a2615af0dc80f709222c6fd
[ "MIT" ]
null
null
null
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // 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. // -------------------------------------------------------------------------------------------------- // Malmo: #include <MissionSpec.h> using namespace malmo; // STL: #include <exception> #include <iostream> #include <string> using namespace std; int main() { MissionSpec my_mission = MissionSpec(); my_mission.timeLimitInSeconds( 10 ); my_mission.drawBlock( 19, 0, 19, "redstone_block" ); my_mission.createDefaultTerrain(); my_mission.setTimeOfDay(6000,false); my_mission.drawCuboid(50,0,50,100,10,100,"redstone_block"); my_mission.drawItem(3,0,2,"diamond_pickaxe"); my_mission.drawSphere(50,10,50,10,"ice"); my_mission.drawLine(50,20,50,100,20,100,"redstone_block"); my_mission.startAt( 2, 0, 2 ); my_mission.endAt( 19.5f, 0.0f, 19.5f, 1.0f ); my_mission.requestVideo( 320, 240 ); my_mission.setModeToCreative(); my_mission.rewardForReachingPosition(19.5f,0.0f,19.5f,100.0f,1.1f); my_mission.observeRecentCommands(); my_mission.observeHotBar(); my_mission.observeFullInventory(); my_mission.observeGrid(-2,0,-2,2,1,2, "Cells"); my_mission.observeDistance(19.5f,0.0f,19.5f,"Goal"); my_mission.removeAllCommandHandlers(); my_mission.allowContinuousMovementCommand("move"); my_mission.allowContinuousMovementCommand("strafe"); my_mission.allowDiscreteMovementCommand("movenorth"); my_mission.allowInventoryCommand("swapInventoryItems"); // check that the XML we produce validates const bool pretty_print = false; string xml = my_mission.getAsXML(pretty_print); try { const bool validate = true; MissionSpec my_mission2 = MissionSpec( xml, validate ); // check that we get the same XML if we go round again string xml2 = my_mission2.getAsXML(pretty_print); if( xml2 != xml ) { cout << "Mismatch between first generation XML and the second:\n\n" << xml << "\n\n" << xml2 << endl; return EXIT_FAILURE; } } catch( const xml_schema::exception& e ) { cout << "Error validating the XML we generated: " << e.what() << "\n" << e << endl; return EXIT_FAILURE; } // check that known-good XML validates const string xml3 = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Mission xmlns=\"http://ProjectMalmo.microsoft.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://ProjectMalmo.microsoft.com Mission.xsd\">\ <About><Summary>Run the maze!</Summary></About>\ <ServerSection><ServerInitialConditions><AllowSpawning>true</AllowSpawning><Time><StartTime>1000</StartTime><AllowPassageOfTime>true</AllowPassageOfTime></Time><Weather>clear</Weather></ServerInitialConditions>\ <ServerHandlers>\ <FlatWorldGenerator generatorString=\"3;7,220*1,5*3,2;3;,biome_1\" />\ <ServerQuitFromTimeUp timeLimitMs=\"20000\" />\ <ServerQuitWhenAnyAgentFinishes />\ </ServerHandlers></ServerSection>\ <AgentSection><Name>Jason Bourne</Name><AgentStart><Placement x=\"-204\" y=\"81\" z=\"217\"/></AgentStart><AgentHandlers>\ <VideoProducer want_depth=\"true\"><Width>320</Width><Height>240</Height></VideoProducer>\ <RewardForReachingPosition><Marker reward=\"100\" tolerance=\"1.1\" x=\"-104\" y=\"81\" z=\"217\"/></RewardForReachingPosition>\ <ContinuousMovementCommands />\ <AgentQuitFromReachingPosition><Marker x=\"-104\" y=\"81\" z=\"217\"/></AgentQuitFromReachingPosition>\ </AgentHandlers></AgentSection></Mission>"; try { const bool validate = true; MissionSpec my_mission3( xml3, validate ); } catch( const xml_schema::exception& e ) { cout << "Error validating known-good XML: " << e.what() << "\n" << e << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
47.5
247
0.6577
geekstor
3b63fb5a8114e3086e39398b3e433cb1385a70ae
3,500
cpp
C++
src/test/r3/colon-case/level-data/AssetManagerTests/AssetManagerTests-main.cpp
ryantherileyman/riley-colon-case
16c7f1239b7b70373ee9d250f028f49e5da1d4a5
[ "Apache-2.0" ]
1
2021-02-24T04:38:33.000Z
2021-02-24T04:38:33.000Z
src/test/r3/colon-case/level-data/AssetManagerTests/AssetManagerTests-main.cpp
ryantherileyman/riley-colon-case
16c7f1239b7b70373ee9d250f028f49e5da1d4a5
[ "Apache-2.0" ]
42
2020-12-29T22:16:12.000Z
2021-05-03T02:46:07.000Z
src/test/r3/colon-case/level-data/AssetManagerTests/AssetManagerTests-main.cpp
ryantherileyman/riley-colon-case
16c7f1239b7b70373ee9d250f028f49e5da1d4a5
[ "Apache-2.0" ]
null
null
null
#include <assert.h> #include <iostream> #include <r3/colon-case/level-data/r3-colonCase-AssetManager.hpp> using namespace r3::colonCase; bool testGetMapStatus_LoadingNotInitiated() { AssetManager assetManager; assetManager.setCampaignFolder("good-campaign"); AssetLoadingStatus status = assetManager.getMapStatus("levels/valid_map.json"); bool result = (status.completionStatus == AssetLoadingCompletionStatus::NON_EXISTENT); return result; } bool testGetMapStatus_LoadingInitiated() { AssetManager assetManager; assetManager.setCampaignFolder("good-campaign"); assetManager.loadMapAsync("levels/valid_map.json"); AssetLoadingStatus immediateStatus = assetManager.getMapStatus("levels/valid_map.json"); bool immediateResult = (immediateStatus.completionStatus != AssetLoadingCompletionStatus::COMPLETE); bool completeFlag = false; while (!completeFlag) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); AssetLoadingStatus waitedStatus = assetManager.getMapStatus("levels/valid_map.json"); completeFlag = (waitedStatus.completionStatus == AssetLoadingCompletionStatus::COMPLETE); if (waitedStatus.completionStatus == AssetLoadingCompletionStatus::FAILED) { return false; } } AssetLoadingStatus completedStatus = assetManager.getMapStatus("levels/valid_map.json"); bool completedResult = (completedStatus.loadedCount == 4) && (lroundf(completedStatus.getLoadedPct()) == 100); GameMap& gameMap = assetManager.getMap("levels/valid_map.json"); sf::Texture& tilesetTexture = assetManager.getTexture(gameMap.getTileImageFilename(3)); bool result = immediateResult && completedResult && (gameMap.getLayerCount() == 2) && (tilesetTexture.getSize().x == 21); return result; } bool testGetMapStatus_ErrorLoadingMap() { AssetManager assetManager; assetManager.setCampaignFolder("good-campaign"); assetManager.loadMapAsync("levels/non_existent_map.json"); bool failedFlag = false; while (!failedFlag) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); AssetLoadingStatus waitedStatus = assetManager.getMapStatus("levels/non_existent_map.json"); failedFlag = (waitedStatus.completionStatus == AssetLoadingCompletionStatus::FAILED); if (waitedStatus.completionStatus == AssetLoadingCompletionStatus::COMPLETE) { return false; } } return true; } bool testGetMapStatus_ErrorLoadingTexture() { AssetManager assetManager; assetManager.setCampaignFolder("bad-campaign"); assetManager.loadMapAsync("levels/invalid_map.json"); bool failedFlag = false; while (!failedFlag) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); AssetLoadingStatus waitedStatus = assetManager.getMapStatus("levels/invalid_map.json"); failedFlag = (waitedStatus.completionStatus == AssetLoadingCompletionStatus::FAILED); if (waitedStatus.completionStatus == AssetLoadingCompletionStatus::COMPLETE) { return false; } } return true; } bool testDestructor_WaitsIfLoadingIncomplete() { { AssetManager assetManager; assetManager.setCampaignFolder("good-campaign"); assetManager.loadMapAsync("levels/valid_map.json"); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); return true; } int main() { assert(testGetMapStatus_LoadingNotInitiated()); assert(testGetMapStatus_LoadingInitiated()); assert(testGetMapStatus_ErrorLoadingMap()); assert(testGetMapStatus_ErrorLoadingTexture()); assert(testDestructor_WaitsIfLoadingIncomplete()); std::cout << "All tests passed!\n"; return 0; }
29.91453
101
0.781714
ryantherileyman
3b644ec2aaedf297aa236db8d950b8e68b12e507
4,867
cpp
C++
GMPsgCtl/GMPsgCtl.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
GMPsgCtl/GMPsgCtl.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
GMPsgCtl/GMPsgCtl.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
// Copyright 2011 Intergraph 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 <stdio.h> #include <windows.h> #include <olectl.h> #include "../Common/Registrar.hpp" #include "GMPsgCtl.rh" #include "GMPsgCtlClsFactory.hpp" #include "../Common/LogFiles.hpp" #include "GMPsgCtlIntfc.hpp" extern wchar_t g_ModuleName[MAX_PATH]; CClsFacList *g_List; HINSTANCE g_hinstDLL; extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) { // Perform actions based on the reason for calling. switch( fdwReason ) { case DLL_PROCESS_ATTACH: // Initialize once for each new process. // Return FALSE to fail DLL load. g_ModuleName[0] = 0; g_hinstDLL = hinstDLL; g_List = NULL; break; case DLL_THREAD_ATTACH: // Do thread-specific initialization. break; case DLL_THREAD_DETACH: // Do thread-specific cleanup. break; case DLL_PROCESS_DETACH: // Perform any necessary cleanup. if(g_List) { delete g_List; #ifdef DBGLEVEL FreeLogFileName(); #endif // DBGLEVEL } break; } return TRUE; // Successful DLL_PROCESS_ATTACH. } STDAPI DllCanUnloadNow() { return(g_List->IsEmpty() ? S_OK : S_FALSE); } STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { if(!g_List) { if(!g_ModuleName[0]) GetModuleFileName(g_hinstDLL, g_ModuleName, MAX_PATH); #ifdef DBGLEVEL CreateLogFile(); #endif // DBGLEVEL g_List = new CClsFacList(g_hinstDLL); } #if DBGLEVEL > 0 WriteLogFile("DllGetClassObject\r\n", true); #if DBGLEVEL > 2 char buf[64]; FormatGuid(buf, " rclsid: ", "\r\n", rclsid); WriteLogFile(buf, false); FormatGuid(buf, " riid: ", "\r\n", riid); WriteLogFile(buf, false); #endif // DBGLEVEL #endif // DBGLEVEL *ppv = NULL; if(IsEqualIID(riid, IID_IClassFactory)) { *ppv = g_List->GetClassFactory(rclsid); } else if(IsEqualCLSID(rclsid, CLASS_GMPostGISConnectionProps) && (IsEqualIID(riid, DIID___GMPostGISConnectionProps) || IsEqualIID(riid, IID_IUnknown))) { // For some reason, GeoMedia requests class id of the control, // however, it wants the IClassFactory interface in fact *ppv = g_List->GetClassFactory(rclsid); //IClassFactory *pcf = (IClassFactory*)g_List->GetClassFactory(rclsid); //pcf->CreateInstance(NULL, riid, ppv); //*ppv = new _GMPostGISConnectionProps(NULL, NULL, NULL); } /*else if(IsEqualCLSID(rclsid, CLASS_GMPostGISNativeQueryProps) && (IsEqualIID(riid, DIID_GMPostGISNativeQueryProps) || IsEqualIID(riid, IID_IUnknown))) { *ppv = new GMPostGISNativeQueryProps(NULL, NULL); }*/ if(*ppv) { ((IUnknown*)*ppv)->AddRef(); ((IUnknown*)*ppv)->AddRef(); // ??? - seems to be necessary si that // the class factory does not get released return(S_OK); } else return(CLASS_E_CLASSNOTAVAILABLE); } STDAPI DllRegisterServer() { HRESULT hres = SELFREG_E_CLASS; IRegistrar *reg = NULL; if((CoCreateInstance(CLASS_Registrar, NULL, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, IID_IRegistrar, (void**)&reg) == S_OK) && reg) { if(!g_ModuleName[0]) GetModuleFileName(g_hinstDLL, g_ModuleName, MAX_PATH); reg->AddReplacement(L"MODULE", g_ModuleName); hres = reg->ResourceRegister(g_ModuleName, REG_MAIN, L"REGISTRY"); reg->Release(); } return(hres); } STDAPI DllUnregisterServer() { HRESULT hres = SELFREG_E_CLASS; IRegistrar *reg = NULL; if((CoCreateInstance(CLASS_Registrar, NULL, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, IID_IRegistrar, (void**)&reg) == S_OK) && reg) { if(!g_ModuleName[0]) GetModuleFileName(g_hinstDLL, g_ModuleName, MAX_PATH); reg->AddReplacement(L"MODULE", g_ModuleName); hres = reg->ResourceUnregister(g_ModuleName, REG_MAIN, L"REGISTRY"); reg->Release(); } return(hres); }
32.66443
157
0.626875
rs0h
3b66f441ac36850e03dd468893e4b5c4f6aa7153
370
hpp
C++
include/reptil_exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
include/reptil_exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
include/reptil_exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
1
2020-11-18T21:06:29.000Z
2020-11-18T21:06:29.000Z
#include "reptil.hpp" #include "exotico.hpp" class ReptilExotico: public Reptil, public Exotico{ private: ostream& print(ostream& o) const; public: ReptilExotico(string identificacao, double preco, string descricao, double peso, tipoSexo sexo, Venomous veneno, double comprimento, string origem); ~ReptilExotico(); };
33.636364
96
0.675676
fernandocunhapereira
3b6a04141721ceaac640c4aa7a8f57879d111345
397
cpp
C++
Teste e exercicios/Struct/struct.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
Teste e exercicios/Struct/struct.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
Teste e exercicios/Struct/struct.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; struct pessoa{ string nome; int idade; int cpf; }; int main() { pessoa p; cout << "digite os dados: " << endl; cout << "CPF ->"; cin >> p.cpf; cout << "Idade ->"; cin >> p.idade; cout << "Nome ->"; cin >> p.nome; cout << p.cpf << endl << p.idade << endl << p.nome; return 0; }
14.178571
55
0.465995
Lu1zReis
3b6bd84c11236d5c1867cd89f95a8ee212dfbe2e
437
cpp
C++
a132.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
a132.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
a132.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<stdint.h> using namespace std; #define IOS {cin.tie(nullptr);ios_base::sync_with_stdio(false);} #define N 1000000 int main() { IOS; int n; while(cin >> n && n){ cout << "The parity of "; int ans = 0; for(unsigned int i=1<<31;i;i>>=1){ if(n & i) cout << 1,ans++; else if(i <= n) cout << 0; } cout << " is " << ans << " (mod 2).\n"; } return 0; }
16.185185
65
0.512586
puyuliao
3b762a18ef43aed5c40d70ddf8023f4ac64cbe4c
2,596
cpp
C++
src/custom/common/misc.cpp
ntoskrnl7/crtsys
2948afde9496d4e873dc067d1d0e8a545ce894bc
[ "MIT" ]
null
null
null
src/custom/common/misc.cpp
ntoskrnl7/crtsys
2948afde9496d4e873dc067d1d0e8a545ce894bc
[ "MIT" ]
null
null
null
src/custom/common/misc.cpp
ntoskrnl7/crtsys
2948afde9496d4e873dc067d1d0e8a545ce894bc
[ "MIT" ]
null
null
null
// clang-format off // // vcruntime/guard_support.c // extern "C" unsigned char _guard_xfg_dispatch_icall_nop = 0x90; // // vcruntime/utility_app.cpp // #include <windows.h> #define _ROAPI_ #include <roapi.h> EXTERN_C ROAPI _Check_return_ HRESULT WINAPI RoInitialize ( _In_ RO_INIT_TYPE initType ) { // unreachable code KdBreakPoint(); // untested :-( UNREFERENCED_PARAMETER(initType); return S_OK; } #if CRTSYS_USE_NTL_MAIN // // // /GS 옵션을 사용하여 빌드하는 경우 // BufferOverflowK.lib(gs_support.obj) GsDriverEntry가 포함되며 // GsDriverEntry에서 DriverEntry를 호출하기 때문에 DriverEntry를 임의로 정의하였습니다. // EXTERN_C DRIVER_INITIALIZE DriverEntry; #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #endif // // BufferOverflowK.lib(gs_support.obj) // // GsDriverEntry // EXTERN_C DRIVER_INITIALIZE CrtSysDriverEntry; EXTERN_C NTSTATUS DriverEntry ( _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath ) { PAGED_CODE(); // // ntl::main을 사용하도록 빌드하였는데 DriverEntry가 빌드되는건 뭔가 잘못된것입니다. // KdBreakPoint(); return CrtSysDriverEntry( DriverObject, RegistryPath ); } #endif #if CRTSYS_USE_LIBCNTPR #include "crt/crt_internal.h" #include "crt/setlocal.h" #pragma warning(disable:4100) EXTERN_C NTSTATUS CrtSyspInitializeLocaleLock ( VOID ); EXTERN_C VOID CrtSyspUninitializeLocaleLock ( VOID ); #include <windows.h> EXTERN_C CRITICAL_SECTION CrtSyspIobEntriesLock[_IOB_ENTRIES]; NTSTATUS CrtSyspInitializeStdio ( VOID ) { for (int i = 0; i != _IOB_ENTRIES; ++i) { InitializeCriticalSection( &CrtSyspIobEntriesLock[i] ); } return STATUS_SUCCESS; } NTSTATUS CrtSyspUninitializeStdio ( VOID ) { for (int i = 0; i != _IOB_ENTRIES; ++i) { DeleteCriticalSection( &CrtSyspIobEntriesLock[i] ); } return STATUS_SUCCESS; } EXTERN_C NTSTATUS CrtSyspInitializeForLibcntpr ( VOID ) { NTSTATUS status; // // 10.0.17763.0 // libcntpr.lib!__ptlocinfo->lc_time_curr가 NULL로 초기화되어있기 때문에 __lc_time_curr를 직접 설정해야합니다. // __ptlocinfo->lc_time_curr = __lc_time_curr; // // // status = CrtSyspInitializeLocaleLock(); if (! NT_SUCCESS(status)) { return status; } status = CrtSyspInitializeStdio(); if (! NT_SUCCESS(status)) { CrtSyspUninitializeLocaleLock(); return status; } return status; } EXTERN_C VOID CrtSyspUninitializeForLibcntpr ( VOID ) { CrtSyspUninitializeStdio(); CrtSyspUninitializeLocaleLock(); } #endif // CRTSYS_USE_LIBCNTPR
15.829268
92
0.689137
ntoskrnl7
3b77575f201d6f6fda58cbcc5f311fa7de6117be
984
cxx
C++
test/t1144.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
10
2018-03-26T07:41:44.000Z
2021-11-06T08:33:24.000Z
test/t1144.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
null
null
null
test/t1144.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
1
2020-11-17T03:17:00.000Z
2020-11-17T03:17:00.000Z
/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> #include <string> namespace crap { static std::string s_unknown=std::string("unknown"); //the previous line core dumps, however the next line works: static const std::string s_unknown2("unknown2"); } std::string names[] = {"test1","test2"}; int main() { static std::string s_unknown3=std::string("unknown3"); //the previous line core dumps, however the next line works: static const std::string s_unknown4("unknown4"); printf("%s\n",crap::s_unknown.c_str()); printf("%s\n",crap::s_unknown2.c_str()); printf("%s\n",s_unknown3.c_str()); printf("%s\n",s_unknown4.c_str()); printf("%s\n",names[0].c_str()); printf("%s\n",names[1].c_str()); return 0; }
28.941176
74
0.556911
paulwratt
3b798da7a049860bc39caa1d61915556cd50e71a
17,812
hpp
C++
xfinal/mime.hpp
maxbad/xfinal
3e8ba689fc40b896bb2555aebf903672335b8b7b
[ "MIT" ]
57
2019-05-14T09:55:14.000Z
2022-03-17T07:08:55.000Z
xfinal/mime.hpp
maxbad/xfinal
3e8ba689fc40b896bb2555aebf903672335b8b7b
[ "MIT" ]
12
2019-05-18T02:34:48.000Z
2021-06-29T15:30:41.000Z
xfinal/mime.hpp
maxbad/xfinal
3e8ba689fc40b896bb2555aebf903672335b8b7b
[ "MIT" ]
22
2019-06-15T10:09:33.000Z
2022-01-18T09:24:25.000Z
#pragma once #include "string_view.hpp" #include <map> namespace xfinal { static std::map<nonstd::string_view, nonstd::string_view> mime_map = { { ".323", "text/h323" }, { ".3gp", "video/3gpp" }, { ".aab", "application/x-authoware-bin" }, { ".aam", "application/x-authoware-map" }, { ".aas", "application/x-authoware-seg" }, { ".acx", "application/internet-property-stream" }, { ".ai", "application/postscript" }, { ".aif", "audio/x-aiff" }, { ".aifc", "audio/x-aiff" }, { ".aiff", "audio/x-aiff" }, { ".als", "audio/X-Alpha5" }, { ".amc", "application/x-mpeg" }, { ".ani", "application/octet-stream" }, { ".apk", "application/vnd.android.package-archive" }, { ".asc", "text/plain" }, { ".asd", "application/astound" }, { ".asf", "video/x-ms-asf" }, { ".asn", "application/astound" }, { ".asp", "application/x-asap" }, { ".asr", "video/x-ms-asf" }, { ".asx", "video/x-ms-asf" }, { ".au", "audio/basic" }, { ".avb", "application/octet-stream" }, { ".avi", "video/x-msvideo" }, { ".awb", "audio/amr-wb" }, { ".axs", "application/olescript" }, { ".bas", "text/plain" }, { ".bcpio", "application/x-bcpio" }, { ".bin ", "application/octet-stream" }, { ".bld", "application/bld" }, { ".bld2", "application/bld2" }, { ".bmp", "image/bmp" }, { ".bpk", "application/octet-stream" }, { ".bz2", "application/x-bzip2" }, { ".c", "text/plain" }, { ".cal", "image/x-cals" }, { ".cat", "application/vnd.ms-pkiseccat" }, { ".ccn", "application/x-cnc" }, { ".cco", "application/x-cocoa" }, { ".cdf", "application/x-cdf" }, { ".cer", "application/x-x509-ca-cert" }, { ".cgi", "magnus-internal/cgi" }, { ".chat", "application/x-chat" }, { ".class", "application/octet-stream" }, { ".clp", "application/x-msclip" }, { ".cmx", "image/x-cmx" }, { ".co", "application/x-cult3d-object" }, { ".cod", "image/cis-cod" }, { ".conf", "text/plain" }, { ".cpio", "application/x-cpio" }, { ".cpp", "text/plain" }, { ".cpt", "application/mac-compactpro" }, { ".crd", "application/x-mscardfile" }, { ".crl", "application/pkix-crl" }, { ".crt", "application/x-x509-ca-cert" }, { ".csh", "application/x-csh" }, { ".csm", "chemical/x-csml" }, { ".csml", "chemical/x-csml" }, { ".css", "text/css" }, { ".cur", "application/octet-stream" }, { ".dcm", "x-lml/x-evm" }, { ".dcr", "application/x-director" }, { ".dcx", "image/x-dcx" }, { ".der", "application/x-x509-ca-cert" }, { ".dhtml", "text/html" }, { ".dir", "application/x-director" }, { ".dll", "application/x-msdownload" }, { ".dmg", "application/octet-stream" }, { ".dms", "application/octet-stream" }, { ".doc", "application/msword" }, { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { ".dot", "application/msword" }, { ".dvi", "application/x-dvi" }, { ".dwf", "drawing/x-dwf" }, { ".dwg", "application/x-autocad" }, { ".dxf", "application/x-autocad" }, { ".dxr", "application/x-director" }, { ".ebk", "application/x-expandedbook" }, { ".emb", "chemical/x-embl-dl-nucleotide" }, { ".embl", "chemical/x-embl-dl-nucleotide" }, { ".eps", "application/postscript" }, { ".epub", "application/epub+zip" }, { ".eri", "image/x-eri" }, { ".es", "audio/echospeech" }, { ".esl", "audio/echospeech" }, { ".etc", "application/x-earthtime" }, { ".etx", "text/x-setext" }, { ".evm", "x-lml/x-evm" }, { ".evy", "application/envoy" }, { ".exe", "application/octet-stream" }, { ".fh4", "image/x-freehand" }, { ".fh5", "image/x-freehand" }, { ".fhc", "image/x-freehand" }, { ".fif", "application/fractals" }, { ".flr", "x-world/x-vrml" }, { ".flv", "flv-application/octet-stream" }, { ".fm", "application/x-maker" }, { ".fpx", "image/x-fpx" }, { ".fvi", "video/isivideo" }, { ".gau", "chemical/x-gaussian-input" }, { ".gca", "application/x-gca-compressed" }, { ".gdb", "x-lml/x-gdb" }, { ".gif", "image/gif" }, { ".gps", "application/x-gps" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" }, { ".hdf", "application/x-hdf" }, { ".hdm", "text/x-hdml" }, { ".hdml", "text/x-hdml" }, { ".hlp", "application/winhlp" }, { ".hqx", "application/mac-binhex40" }, { ".hta", "application/hta" }, { ".htc", "text/x-component" }, { ".htm", "text/html" }, { ".html", "text/html" }, { ".hts", "text/html" }, { ".htt", "text/webviewhtml" }, { ".ice", "x-conference/x-cooltalk" }, { ".ico", "image/x-icon" }, { ".ief", "image/ief" }, { ".ifm", "image/gif" }, { ".ifs", "image/ifs" }, { ".iii", "application/x-iphone" }, { ".imy", "audio/melody" }, { ".ins", "application/x-internet-signup" }, { ".ips", "application/x-ipscript" }, { ".ipx", "application/x-ipix" }, { ".isp", "application/x-internet-signup" }, { ".it", "audio/x-mod" }, { ".itz", "audio/x-mod" }, { ".ivr", "i-world/i-vrml" }, { ".j2k", "image/j2k" }, { ".jad", "text/vnd.sun.j2me.app-descriptor" }, { ".jam", "application/x-jam" }, { ".jar", "application/java-archive" }, { ".java", "text/plain" }, { ".jfif", "image/pipeg" }, { ".jnlp", "application/x-java-jnlp-file" }, { ".jpe", "image/jpeg" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".jpz", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".jwc", "application/jwc" }, { ".kjx", "application/x-kjx" }, { ".lak", "x-lml/x-lak" }, { ".latex", "application/x-latex" }, { ".lcc", "application/fastman" }, { ".lcl", "application/x-digitalloca" }, { ".lcr", "application/x-digitalloca" }, { ".lgh", "application/lgh" }, { ".lha", "application/octet-stream" }, { ".lml", "x-lml/x-lml" }, { ".lmlpack", "x-lml/x-lmlpack" }, { ".log", "text/plain" }, { ".lsf", "video/x-la-asf" }, { ".lsx", "video/x-la-asf" }, { ".lzh", "application/octet-stream" }, { ".m13", "application/x-msmediaview" }, { ".m14", "application/x-msmediaview" }, { ".m15", "audio/x-mod" }, { ".m3u", "audio/x-mpegurl" }, { ".m3url", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" }, { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".ma1", "audio/ma1" }, { ".ma2", "audio/ma2" }, { ".ma3", "audio/ma3" }, { ".ma5", "audio/ma5" }, { ".man", "application/x-troff-man" }, { ".map", "magnus-internal/imagemap" }, { ".mbd", "application/mbedlet" }, { ".mct", "application/x-mascot" }, { ".mdb", "application/x-msaccess" }, { ".mdz", "audio/x-mod" }, { ".me", "application/x-troff-me" }, { ".mel", "text/x-vmel" }, { ".mht", "message/rfc822" }, { ".mhtml", "message/rfc822" }, { ".mi", "application/x-mif" }, { ".mid", "audio/mid" }, { ".midi", "audio/midi" }, { ".mif", "application/x-mif" }, { ".mil", "image/x-cals" }, { ".mio", "audio/x-mio" }, { ".mmf", "application/x-skt-lbs" }, { ".mng", "video/x-mng" }, { ".mny", "application/x-msmoney" }, { ".moc", "application/x-mocha" }, { ".mocha", "application/x-mocha" }, { ".mod", "audio/x-mod" }, { ".mof", "application/x-yumekara" }, { ".mol", "chemical/x-mdl-molfile" }, { ".mop", "chemical/x-mopac-input" }, { ".mov", "video/quicktime" }, { ".movie", "video/x-sgi-movie" }, { ".mp2", "video/mpeg" }, { ".mp3", "audio/mpeg" }, { ".mp4", "video/mp4" }, { ".mpa", "video/mpeg" }, { ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".mpn", "application/vnd.mophun.application" }, { ".mpp", "application/vnd.ms-project" }, { ".mps", "application/x-mapserver" }, { ".mpv2", "video/mpeg" }, { ".mrl", "text/x-mrml" }, { ".mrm", "application/x-mrm" }, { ".ms", "application/x-troff-ms" }, { ".msg", "application/vnd.ms-outlook" }, { ".mts", "application/metastream" }, { ".mtx", "application/metastream" }, { ".mtz", "application/metastream" }, { ".mvb", "application/x-msmediaview" }, { ".mzv", "application/metastream" }, { ".nbmp", "image/nbmp" }, { ".nc", "application/x-netcdf" }, { ".ndb", "x-lml/x-ndb" }, { ".ndwn", "application/ndwn" }, { ".nif", "application/x-nif" }, { ".nmz", "application/x-scream" }, { ".nokia-op-logo", "image/vnd.nok-oplogo-color" }, { ".npx", "application/x-netfpx" }, { ".nsnd", "audio/nsnd" }, { ".nva", "application/x-neva1" }, { ".nws", "message/rfc822" }, { ".oda", "application/oda" }, { ".ogg", "audio/ogg" }, { ".oom", "application/x-AtlasMate-Plugin" }, { ".p10", "application/pkcs10" }, { ".p12", "application/x-pkcs12" }, { ".p7b", "application/x-pkcs7-certificates" }, { ".p7c", "application/x-pkcs7-mime" }, { ".p7m", "application/x-pkcs7-mime" }, { ".p7r", "application/x-pkcs7-certreqresp" }, { ".p7s", "application/x-pkcs7-signature" }, { ".pac", "audio/x-pac" }, { ".pae", "audio/x-epac" }, { ".pan", "application/x-pan" }, { ".pbm", "image/x-portable-bitmap" }, { ".pcx", "image/x-pcx" }, { ".pda", "image/x-pda" }, { ".pdb", "chemical/x-pdb" }, { ".pdf", "application/pdf" }, { ".pfr", "application/font-tdpfr" }, { ".pfx", "application/x-pkcs12" }, { ".pgm", "image/x-portable-graymap" }, { ".pict", "image/x-pict" }, { ".pko", "application/ynd.ms-pkipko" }, { ".pm", "application/x-perl" }, { ".pma", "application/x-perfmon" }, { ".pmc", "application/x-perfmon" }, { ".pmd", "application/x-pmd" }, { ".pml", "application/x-perfmon" }, { ".pmr", "application/x-perfmon" }, { ".pmw", "application/x-perfmon" }, { ".png", "image/png" }, { ".pnm", "image/x-portable-anymap" }, { ".pnz", "image/png" }, { ".pot,", "application/vnd.ms-powerpoint" }, { ".ppm", "image/x-portable-pixmap" }, { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" }, { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".pqf", "application/x-cprplayer" }, { ".pqi", "application/cprplayer" }, { ".prc", "application/x-prc" }, { ".prf", "application/pics-rules" }, { ".prop", "text/plain" }, { ".proxy", "application/x-ns-proxy-autoconfig" }, { ".ps", "application/postscript" }, { ".ptlk", "application/listenup" }, { ".pub", "application/x-mspublisher" }, { ".pvx", "video/x-pv-pvx" }, { ".qcp", "audio/vnd.qcelp" }, { ".qt", "video/quicktime" }, { ".qti", "image/x-quicktime" }, { ".qtif", "image/x-quicktime" }, { ".r3t", "text/vnd.rn-realtext3d" }, { ".ra", "audio/x-pn-realaudio" }, { ".ram", "audio/x-pn-realaudio" }, { ".rar", "application/octet-stream" }, { ".ras", "image/x-cmu-raster" }, { ".rc", "text/plain" }, { ".rdf", "application/rdf+xml" }, { ".rf", "image/vnd.rn-realflash" }, { ".rgb", "image/x-rgb" }, { ".rlf", "application/x-richlink" }, { ".rm", "audio/x-pn-realaudio" }, { ".rmf", "audio/x-rmf" }, { ".rmi", "audio/mid" }, { ".rmm", "audio/x-pn-realaudio" }, { ".rmvb", "audio/x-pn-realaudio" }, { ".rnx", "application/vnd.rn-realplayer" }, { ".roff", "application/x-troff" }, { ".rp", "image/vnd.rn-realpix" }, { ".rpm", "audio/x-pn-realaudio-plugin" }, { ".rt", "text/vnd.rn-realtext" }, { ".rte", "x-lml/x-gps" }, { ".rtf", "application/rtf" }, { ".rtg", "application/metastream" }, { ".rtx", "text/richtext" }, { ".rv", "video/vnd.rn-realvideo" }, { ".rwc", "application/x-rogerwilco" }, { ".s3m", "audio/x-mod" }, { ".s3z", "audio/x-mod" }, { ".sca", "application/x-supercard" }, { ".scd", "application/x-msschedule" }, { ".sct", "text/scriptlet" }, { ".sdf", "application/e-score" }, { ".sea", "application/x-stuffit" }, { ".setpay", "application/set-payment-initiation" }, { ".setreg", "application/set-registration-initiation" }, { ".sgm", "text/x-sgml" }, { ".sgml", "text/x-sgml" }, { ".sh", "application/x-sh" }, { ".shar", "application/x-shar" }, { ".shtml", "magnus-internal/parsed-html" }, { ".shw", "application/presentations" }, { ".si6", "image/si6" }, { ".si7", "image/vnd.stiwap.sis" }, { ".si9", "image/vnd.lgtwap.sis" }, { ".sis", "application/vnd.symbian.install" }, { ".sit", "application/x-stuffit" }, { ".skd", "application/x-Koan" }, { ".skm", "application/x-Koan" }, { ".skp", "application/x-Koan" }, { ".skt", "application/x-Koan" }, { ".slc", "application/x-salsa" }, { ".smd", "audio/x-smd" }, { ".smi", "application/smil" }, { ".smil", "application/smil" }, { ".smp", "application/studiom" }, { ".smz", "audio/x-smd" }, { ".snd", "audio/basic" }, { ".spc", "application/x-pkcs7-certificates" }, { ".spl", "application/futuresplash" }, { ".spr", "application/x-sprite" }, { ".sprite", "application/x-sprite" }, { ".sdp", "application/sdp" }, { ".spt", "application/x-spt" }, { ".src", "application/x-wais-source" }, { ".sst", "application/vnd.ms-pkicertstore" }, { ".stk", "application/hyperstudio" }, { ".stl", "application/vnd.ms-pkistl" }, { ".stm", "text/html" }, { ".svg", "image/svg+xml" }, { ".sv4cpio", "application/x-sv4cpio" }, { ".sv4crc", "application/x-sv4crc" }, { ".svf", "image/vnd" }, { ".eot", "application/vnd.ms-fontobject" }, { ".woff", "application/font-woff" }, { ".svh", "image/svh" }, { ".svr", "x-world/x-svr" }, { ".swf", "application/x-shockwave-flash" }, { ".swfl", "application/x-shockwave-flash" }, { ".t", "application/x-troff" }, { ".tad", "application/octet-stream" }, { ".talk", "text/x-speech" }, { ".tar", "application/x-tar" }, { ".taz", "application/x-tar" }, { ".tbp", "application/x-timbuktu" }, { ".tbt", "application/x-timbuktu" }, { ".tcl", "application/x-tcl" }, { ".tex", "application/x-tex" }, { ".texi", "application/x-texinfo" }, { ".texinfo", "application/x-texinfo" }, { ".tgz", "application/x-compressed" }, { ".thm", "application/vnd.eri.thm" }, { ".tif", "image/tiff" }, { ".tiff", "image/tiff" }, { ".tki", "application/x-tkined" }, { ".tkined", "application/x-tkined" }, { ".toc", "application/toc" }, { ".toy", "image/toy" }, { ".tr", "application/x-troff" }, { ".trk", "x-lml/x-gps" }, { ".trm", "application/x-msterminal" }, { ".tsi", "audio/tsplayer" }, { ".tsp", "application/dsptype" }, { ".tsv", "text/tab-separated-values" }, { ".ttf", "application/octet-stream" }, { ".ttz", "application/t-time" }, { ".txt", "text/plain" }, { ".uls", "text/iuls" }, { ".ult", "audio/x-mod" }, { ".ustar", "application/x-ustar" }, { ".uu", "application/x-uuencode" }, { ".uue", "application/x-uuencode" }, { ".vcd", "application/x-cdlink" }, { ".vcf", "text/x-vcard" }, { ".vdo", "video/vdo" }, { ".vib", "audio/vib" }, { ".viv", "video/vivo" }, { ".vivo", "video/vivo" }, { ".vmd", "application/vocaltec-media-desc" }, { ".vmf", "application/vocaltec-media-file" }, { ".vmi", "application/x-dreamcast-vms-info" }, { ".vms", "application/x-dreamcast-vms" }, { ".vox", "audio/voxware" }, { ".vqe", "audio/x-twinvq-plugin" }, { ".vqf", "audio/x-twinvq" }, { ".vql", "audio/x-twinvq" }, { ".vre", "x-world/x-vream" }, { ".vrml", "x-world/x-vrml" }, { ".vrt", "x-world/x-vrt" }, { ".vrw", "x-world/x-vream" }, { ".vts", "workbook/formulaone" }, { ".wav", "audio/x-wav" }, { ".wax", "audio/x-ms-wax" }, { ".wbmp", "image/vnd.wap.wbmp" }, { ".wcm", "application/vnd.ms-works" }, { ".wdb", "application/vnd.ms-works" }, { ".web", "application/vnd.xara" }, { ".wi", "image/wavelet" }, { ".wis", "application/x-InstallShield" }, { ".wks", "application/vnd.ms-works" }, { ".wm", "video/x-ms-wm" }, { ".wma", "audio/x-ms-wma" }, { ".wmd", "application/x-ms-wmd" }, { ".wmf", "application/x-msmetafile" }, { ".wml", "text/vnd.wap.wml" }, { ".wmlc", "application/vnd.wap.wmlc" }, { ".wmls", "text/vnd.wap.wmlscript" }, { ".wmlsc", "application/vnd.wap.wmlscriptc" }, { ".wmlscript", "text/vnd.wap.wmlscript" }, { ".wmv", "audio/x-ms-wmv" }, { ".wmx", "video/x-ms-wmx" }, { ".wmz", "application/x-ms-wmz" }, { ".wpng", "image/x-up-wpng" }, { ".wps", "application/vnd.ms-works" }, { ".wpt", "x-lml/x-gps" }, { ".wri", "application/x-mswrite" }, { ".wrl", "x-world/x-vrml" }, { ".wrz", "x-world/x-vrml" }, { ".ws", "text/vnd.wap.wmlscript" }, { ".wsc", "application/vnd.wap.wmlscriptc" }, { ".wv", "video/wavelet" }, { ".wvx", "video/x-ms-wvx" }, { ".wxl", "application/x-wxl" }, { ".x-gzip", "application/x-gzip" }, { ".xaf", "x-world/x-vrml" }, { ".xar", "application/vnd.xara" }, { ".xbm", "image/x-xbitmap" }, { ".xdm", "application/x-xdma" }, { ".xdma", "application/x-xdma" }, { ".xdw", "application/vnd.fujixerox.docuworks" }, { ".xht", "application/xhtml+xml" }, { ".xhtm", "application/xhtml+xml" }, { ".xhtml", "application/xhtml+xml" }, { ".xla", "application/vnd.ms-excel" }, { ".xlc", "application/vnd.ms-excel" }, { ".xll", "application/x-excel" }, { ".xlm", "application/vnd.ms-excel" }, { ".xls", "application/vnd.ms-excel" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { ".xlt", "application/vnd.ms-excel" }, { ".xlw", "application/vnd.ms-excel" }, { ".xm", "audio/x-mod" }, { ".xml","text/plain" }, { ".xml","application/xml" }, { ".xmz", "audio/x-mod" }, { ".xof", "x-world/x-vrml" }, { ".xpi", "application/x-xpinstall" }, { ".xpm", "image/x-xpixmap" }, { ".xsit", "text/xml" }, { ".xsl", "text/xml" }, { ".xul", "text/xul" }, { ".xwd", "image/x-xwindowdump" }, { ".xyz", "chemical/x-pdb" }, { ".yz1", "application/x-yz1" }, { ".z", "application/x-compress" }, { ".zac", "application/x-zaurus-zac" }, { ".zip", "application/zip" }, { ".json", "application/json" }, }; static nonstd::string_view unknow_file = "application/octet-stream"; static nonstd::string_view get_extension(std::string const& key) { for (auto& iter : mime_map) { if (iter.second == key) { return iter.first; } } return ""; } static nonstd::string_view get_content_type(std::string const& key) { auto it = mime_map.find(nonstd::string_view(key.data(),key.size())); if (it != mime_map.end()) { return it->second; } else { return unknow_file; } } }
34.789063
90
0.552493
maxbad
3b79f31a046bb2ceaabb630cb05fa4e25ca4b6e0
6,539
cxx
C++
src/matrix_4x4.cxx
cervenkam/muscle-deformation-PBD
66cce66944a8e81cb9bbc82f845bd45beccf0d9b
[ "Apache-2.0" ]
1
2020-11-15T23:21:31.000Z
2020-11-15T23:21:31.000Z
src/matrix_4x4.cxx
cervenkam/muscle-deformation-PBD
66cce66944a8e81cb9bbc82f845bd45beccf0d9b
[ "Apache-2.0" ]
null
null
null
src/matrix_4x4.cxx
cervenkam/muscle-deformation-PBD
66cce66944a8e81cb9bbc82f845bd45beccf0d9b
[ "Apache-2.0" ]
null
null
null
/* ########################################################### # PBD algorithm implementation # # Thesis: Muscle Fibres Deformation using Particle System # # Author: Martin Cervenka # # Version: 5/2019 # ########################################################### This class provides basic operations with 4x4 matrices Matrix is stored in row-major order: / 0 1 2 \ | 3 4 5 | \ 6 7 8 / */ #include "matrix_4x4.h" #include <cstring> /* C'tor of the 4x4 matrix => x00 First element of the matrix => x02 Second element (first row, second column) => x33 Last element => x03-x32 Rest of the elements */ matrix_4x4::matrix_4x4( double x00,double x01,double x02,double x03, double x10,double x11,double x12,double x13, double x20,double x21,double x22,double x23, double x30,double x31,double x32,double x33 ){ /* Simple assign to the internal matrix */ m_data[0][0]=x00;m_data[0][1]=x01;m_data[0][2]=x02;m_data[0][3]=x03; m_data[1][0]=x10;m_data[1][1]=x11;m_data[1][2]=x12;m_data[1][3]=x13; m_data[2][0]=x20;m_data[2][1]=x21;m_data[2][2]=x22;m_data[2][3]=x23; m_data[3][0]=x30;m_data[3][1]=x31;m_data[3][2]=x32;m_data[3][3]=x33; } /* C'tor of identity matrix */ matrix_4x4::matrix_4x4(){} /* Makes translate matrix => x X value of the translation => y Y value of the translation => z Z value of the translation */ void matrix_4x4::translate(double x,double y,double z){ /* Set X component of last column (weight) to the translation value */ m_data[0][3] += x; /* same with both y */ m_data[1][3] += y; /* and z */ m_data[2][3] += z; } /* Transforms input vector (3 element) by this 4x4 matrix Result just equals to "(M*[v;0])(1:3)" in octave/matlab <=> input/output 3 element vector */ void matrix_4x4::transform_vector(double* v){ /* Rename data - make code shorter and easier to read */ auto& d=m_data; /* Calculate X component of the transformed vector */ double x=v[0]*d[0][0]+v[1]*d[0][1]+v[2]*d[0][2]+d[0][3]; /* Y the same way, this is just dot product of 2. matrix row and input vector */ double y=v[0]*d[1][0]+v[1]*d[1][1]+v[2]*d[1][2]+d[1][3]; /* and Z is dot product with 3. row */ double z=v[0]*d[2][0]+v[1]*d[2][1]+v[2]*d[2][2]+d[2][3]; /* and we save the new X value to the I/O vector */ v[0]=x; /* same with y */ v[1]=y; /* and z */ v[2]=z; } /* Converts this matrix to its inverse (WARNING! does not care if singular) */ void matrix_4x4::inverse(){ /* This inversion is done by adjungate matrix and subdeterminant method - it seems to be fast, even when we know its dimension apriori. Hopefully no one will have to debug the following... */ /* At first, we rename the data to make code shorer and clearer */ auto& d=m_data; /* The following line is subdeterminant of following elements: / . . . . \ | . . . . | A2323 = det | . . # # | \ . . # # / */ double A2323=d[2][2]*d[3][3]-d[2][3]*d[3][2]; /* And the following line is subdeterminant of following elements: / . . . . \ | . . . . | A1323 = det | . # . # | \ . # . # / */ double A1323=d[2][1]*d[3][3]-d[2][3]*d[3][1]; /* This way we get all 2x2 subdeterminants we need ... */ double A1223=d[2][1]*d[3][2]-d[2][2]*d[3][1]; double A0323=d[2][0]*d[3][3]-d[2][3]*d[3][0]; double A0223=d[2][0]*d[3][2]-d[2][2]*d[3][0]; double A0123=d[2][0]*d[3][1]-d[2][1]*d[3][0]; double A2313=d[1][2]*d[3][3]-d[1][3]*d[3][2]; double A1313=d[1][1]*d[3][3]-d[1][3]*d[3][1]; double A1213=d[1][1]*d[3][2]-d[1][2]*d[3][1]; double A2312=d[1][2]*d[2][3]-d[1][3]*d[2][2]; double A1312=d[1][1]*d[2][3]-d[1][3]*d[2][1]; double A1212=d[1][1]*d[2][2]-d[1][2]*d[2][1]; double A0313=d[1][0]*d[3][3]-d[1][3]*d[3][0]; double A0213=d[1][0]*d[3][2]-d[1][2]*d[3][0]; double A0312=d[1][0]*d[2][3]-d[1][3]*d[2][0]; double A0212=d[1][0]*d[2][2]-d[1][2]*d[2][0]; double A0113=d[1][0]*d[3][1]-d[1][1]*d[3][0]; double A0112=d[1][0]*d[2][1]-d[1][1]*d[2][0]; /* Then we compute the determinant (or its inverse), we use subdeterminants and Laplace expansion to make it "faster" */ double inv_det=1/( +d[0][0]*(d[1][1]*A2323-d[1][2]*A1323+d[1][3]*A1223) -d[0][1]*(d[1][0]*A2323-d[1][2]*A0323+d[1][3]*A0223) +d[0][2]*(d[1][0]*A1323-d[1][1]*A0323+d[1][3]*A0123) -d[0][3]*(d[1][0]*A1223-d[1][1]*A0223+d[1][2]*A0123) ); double nd[4][4]; /* And then we calculate each element of the inverted matrix, we use here rule of block matrices */ nd[0][0]=inv_det*+(d[1][1]*A2323-d[1][2]*A1323+d[1][3]*A1223); nd[0][1]=inv_det*-(d[0][1]*A2323-d[0][2]*A1323+d[0][3]*A1223); nd[0][2]=inv_det*+(d[0][1]*A2313-d[0][2]*A1313+d[0][3]*A1213); nd[0][3]=inv_det*-(d[0][1]*A2312-d[0][2]*A1312+d[0][3]*A1212); nd[1][0]=inv_det*-(d[1][0]*A2323-d[1][2]*A0323+d[1][3]*A0223); nd[1][1]=inv_det*+(d[0][0]*A2323-d[0][2]*A0323+d[0][3]*A0223); nd[1][2]=inv_det*-(d[0][0]*A2313-d[0][2]*A0313+d[0][3]*A0213); nd[1][3]=inv_det*+(d[0][0]*A2312-d[0][2]*A0312+d[0][3]*A0212); nd[2][0]=inv_det*+(d[1][0]*A1323-d[1][1]*A0323+d[1][3]*A0123); nd[2][1]=inv_det*-(d[0][0]*A1323-d[0][1]*A0323+d[0][3]*A0123); nd[2][2]=inv_det*+(d[0][0]*A1313-d[0][1]*A0313+d[0][3]*A0113); nd[2][3]=inv_det*-(d[0][0]*A1312-d[0][1]*A0312+d[0][3]*A0112); nd[3][0]=inv_det*-(d[1][0]*A1223-d[1][1]*A0223+d[1][2]*A0123); nd[3][1]=inv_det*+(d[0][0]*A1223-d[0][1]*A0223+d[0][2]*A0123); nd[3][2]=inv_det*-(d[0][0]*A1213-d[0][1]*A0213+d[0][2]*A0113); nd[3][3]=inv_det*+(d[0][0]*A1212-d[0][1]*A0212+d[0][2]*A0112); /* The last step is to save the matrix */ memcpy(m_data,nd,sizeof(double)*16); } /* Method which multiplies this matrix with another one (from right) => mat Multiplicator <= Result of "M*mat" */ matrix_4x4 matrix_4x4::operator*(const matrix_4x4& mat){ /* Creating new matrix (on stack - don't worry, this is overloaded operator) */ matrix_4x4 res; /* For each row in this matrix */ for(size_t a=0; a<4; a++){ /* For each column in second matrix */ for(size_t b=0; b<4; b++){ /* we will calculate sum of the corresponding elements (we do dot product of this matrix row and second matrix column) */ double sum = 0; /* For each one of the corresponding elements */ for(size_t c=0; c<4; c++){ /* We add the result of the multiplication */ sum+=m_data[a][c]*mat.m_data[c][b]; } /* Then we can set the value of the current element */ res.m_data[a][b]=sum; } } /* Finally, we return the result */ return res; }
37.365714
71
0.577
cervenkam
3b7a78749f9f6caa6e06878f7645abb189daede8
11,615
cpp
C++
sources/unvrtool.cpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/unvrtool.cpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/unvrtool.cpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2020, Jan Ove Haaland, all rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include "_headers_std.hpp" #include "util.hpp" #include "config.hpp" #include "vrrecorder.hpp" using namespace std; const char* usage = R"QQ( Quick Usage: unvrtool <video> - Show video unvrtool -save <video> - Save video without showing unvrtool -save -view <video> - Save video while showing unvrtool -s -a <video> - Save video and then create new video with source-audio unvrtool -s -t out.mp4 <video> - Save video to out.mp4 unvrtool -tf out\ path\*.mp4 - Save all mp4 videos in path to out folder unvrtool -config <name> -s <video> - Save video using <name> configuration unvrtool -save <video1> <video2> - Opens <video1> and saves, the opens <video2> and saves unvrtool -c my -c 640x480 -v -sa -tf out\ path\*.mp4 - Show & save all path\*.mp4 to out\ with audio using "my.config" and "640x480.config" General Usage: unvrtool [options] <path to VR video file1> [<path to VR video file2> [...]] Options: <file> or -i <file> Video to open -if | -inputformat <format> Specify video format, ex tb:360:equirectangular, lr:180:fisheye, lr::flat -v | -view View video -s | -save Save video(s), without showing anything unless -g specified -sc | -script Allow user to setup camera shots first, esc to stop. -sl | -scriptload <path> Loads script from path. If not specified will look for <file>.uvrtscript -ss | -scriptsave <path> Saves script to path. If not specified will use <file>.uvrtscript -sa | -saveaudio After save, use ffmpeg to create a video with audio from source-video. -sak| -saveaudiokeep Don't delete no-audio video after audio save -t | -to <path> Save video to path, implies -s -tf | -tofolder <path> Save video(s) to folder, implies -s -ts | -timestart <time> Start video at <time>, given as H:MM:SS -ts% | -timestart% <percent> Start video at <percent> point of video, 0.0 - 100.0 -te | -timeend <time> End video at <time>, given as H:MM:SS -te% | -timeend% <percent> End video at <percent> point of video, 0.0 - 100.0 -td | -timeduration <time> End video at <time> after start-time -c | -config <config> Load config-file. If no extension is given .config will be added -cr | -configreset Reset all config values -cs | -configset <key>=<val>[;...] Set config values on commandline, as an alternative to -c -p | -print Print current (in commandline) settings -pl | -printline Print current (in commandline) settings, one per line -pv | -printverbose Print current (in commandline) settings, with comments -w1 | -waitone Waits for user to press enter before continueing -wa | -waitall Waits for user to press enter before continueing after each vide -we | -waiterror Waits for user to press enter before continueing after each vide if it failed By default <config> can be either just a name, which will be searched for first in current directory, then in app-folder, or path to config-file. Configs does not need to set all values, in which case unset values will remain unchanged. Use -cr to reset all values Ex: -cr -c mydefaults.config -c fisheye.config -c 640x480.config A config-file with current settings can be created with -writeconfig. The user will be asked to confirm overwrite if it exists. unvrtool -writeconfig <config-file> - write current config to <config-file> Ex: unvrtool -c mydefaults -c 1920x1080 -c usesnapshots -writeconfig configs\myspecial.config If there is a file named unvrtool.config in the same folder as the unvrtool app it will be loaded on startup and used as deafult. Keys: In script camera-setup mode: Press Enter to keep fov,bo,yaw and pitch at current location. Press Space or A to keep fov and bo, and set yaw and pitch to auto at current location. Press Delete/Backspace to not set script command at current location, or delete if any set. Press L / S to Load / Save uvrtscript file. If -sc n != 0: Will skip forward automatically on enter or space. n < 0: Will skip -n seconds, n > 0: will skip video-length/n seconds. n = 0: Manual, user must skip back/forward manually. Press Esc to exit mode. General: Left/Right keys: Skip back/forward 10 seconds. Shift: 1 frame, Ctrl: 1 sec, Alt: 1 min, Ctrl+Alt: 10 min, Ctrl+Shift: Next/Previous script-point. Up/Down keys: Increase/Slowdown playback speed Space: pause Esc: exit Enter: Disable auto mode A: Enable auto mode C: Toggle input channel M: Toggle mouse mode T: Toggle showing target markers (not a good idea while saving) Left-mouse click: Set yaw/pitch to aim at point Right-mouse click: Set yaw/pitch to auto Mouse scroll-wheel: zoom fov/bo. Ctrl: fov only. Shift/Alt: bo only. Both: zoom fov/bo inverted. )QQ"; int main(int argc, char** argv) { std::cout << "Unvrtool ver 1.0.1" << std::endl; util::CheckOpenCvDlls(); std::filesystem::path appPath(argv[0]); string appName = appPath.filename().replace_extension().string(); string appFolderPath = util::GetAppFolderPath(); if (appFolderPath == "") appFolderPath = appPath.parent_path().string(); // Won't work if app is in $PATH std::filesystem::path appFolder(appFolderPath); string appConfigPath = (appFolder / appName).string() + ".config"; Config cr; if (std::filesystem::exists(appConfigPath)) cr.ReadFile(appConfigPath.c_str()); Config c(cr); if (argc == 1) { std::cout << usage; cin.get(); return -1; } #define H(x) { x; continue; } int laststatus = 0; int waitif = 0; const char* pendingVideo = nullptr; VrImageFormat vr; for (int i = 1; i < argc+1; i++) { std::string opt; if (i < argc) opt = argv[i]; else if (pendingVideo != nullptr) opt = "--process"; // trigger processing of pending video else break; if (opt == "--getargsfrom") H(if (util::GetArgsFrom(argv[++i], &argc, &argv)) i = 0;); if (opt == "--dbgfmtimg") H(c.saveDebugFormatImage = true); //-cr | -configreset Reset all config values if (opt == "-cr" || opt == "-configreset") H(c = Config(cr)); //-c | -config <config> Load config-file. If no extension is given .config will be added if (opt == "-c" || opt == "-config") H(bool ok = c.ReadFile(argv[++i], appFolderPath.c_str()); std::cout << (ok ? "" : "Unable to ") << " Read " << argv[i]); //-cs | -configset <key>=<val>[;...] Set config values on commandline, as an alternative to -c if (opt == "-cs" || opt == "-configset") H(c.ReadString(argv[++i])); //-p | -print Print current (in commandline) settings if (opt == "-p" || opt == "-print") H(std::cout << c.Print(0) << std::endl); //-pl | -printline Print current (in commandline) settings, one per line if (opt == "-pl" || opt == "-printline") H(std::cout << c.Print(1) << std::endl); //-pv | -printverbose Print current (in commandline) settings, with comments if (opt == "-pv" || opt == "-printverbose") H(std::cout << c.Print(2) << std::endl); // -w1 | -waitone Waits for user to press enter before continueing if (opt == "-w1" || opt == "-waitone") H(cout << "Press enter to continue"; cin.get()); //-w | -wait Waits for user to press enter before continueing if (opt == "-w" || opt == "-wait") H(waitif = 2); // -we | -waiterror Waits for user to press enter before continueing if last video failed if (laststatus != 0 && (opt == "-we" || opt == "-waiterror")) H(waitif = 1); //-v | -view View video if (opt == "-v" || opt == "-view") H(c.view = true); //-s | -save Save video(s), without showing anything unless -g specified if (opt == "-s" || opt == "-save") H(c.save = true); //-sa | -saveaudio After save, use ffmpeg to create a video with audio from source-video. if (opt == "-sa" || opt == "-saveaudio") H(c.saveaudio = true); //-sak | -saveaudiokeep Don't delete no-audio video after audio save if (opt == "-sak" || opt == "-saveaudiokeep") H(c.audiokeep = true); //-t | -to <path> Save video to path, implies -s if (opt == "-t" || opt == "-to") H(c.save = true; c.outPath = argv[++i]); //-tf | -tofolder <path> Save video(s) to folder, implies -s if (opt == "-tf" || opt == "-tofolder") H(c.save = true; c.outFolder = argv[++i]); //-sc | -script Allow user to setup camera shots first, esc to stop. if (opt == "-sc" || opt == "-script") H(c.scriptcam = true;); //-sl | -scriptload <path> Loads script from path. Either path to .uvrtscript file, or path to folder with <file>.uvrtscript if (opt == "-sl" || opt == "-scriptload") H(c.loadscriptPath = std::string(argv[++i])); //-ss | -scriptsave <path> Saves script to path if (opt == "-ss" || opt == "-scriptsave") H(c.savescriptPath = std::string(argv[++i])); //-ts | -timestart <time> Start video at <time>, given as H:MM:SS if (opt == "-ts" || opt == "-timestart") H(c.timeStartSec = TimeCodeHMS(argv[++i]).ToSecs()); // -ts% | -timestart% <percent> Start video at <percent> point of video, 0.0 - 100.0 if (opt == "-ts%" || opt == "-timestart%") H(c.timeStartPrc = stof(argv[++i])); //-te | -timeend <time> End video at <time>, given as H:MM:SS if (opt == "-te" || opt == "-timeend") H(c.timeEndSec = TimeCodeHMS(argv[++i]).ToSecs()); if (opt == "-te%" || opt == "-timeend%") H(c.timeEndPrc = stof(argv[++i])); // -td | -timeduration <time> End video at <time> after start - time if (opt == "-td" || opt == "-timeduration") H(c.timeDurationSec = TimeCodeHMS(argv[++i]).ToSecs()); //-if | -inputformat <format> Specify video format or auto (default). Ex: lr:180:fisheye or tb:360:equirectangular if (opt == "-if" || opt == "-inputformat") H(vr = VrImageFormat::Parse(argv[++i])); // unvrtool -writeconfig <config-file> - write current config to <config-file> if (opt == "-writeconfig") { if (argc == ++i) { auto confPath = appName + ".config"; if (std::filesystem::exists(appConfigPath)) { std::cout << "Press enter to overwrite " << confPath << " or Ctrl+C to abort" << std::endl; cin.get(); } std::cout << "Writing " << confPath << std::endl; H(c.Write(confPath.c_str())); } else H(c.Write(argv[i])); } //<file> or -i <file> Video to open if (opt == "--process" || opt == "-i" || opt[0] != '-') { if (pendingVideo != nullptr) { int s = 0; if (std::filesystem::exists(pendingVideo)) { VrRecorder v(c); v.videopath = std::string(pendingVideo); s = v.Run(vr); cout << std::endl; } else { s = 1; cout << "Not Found: " << pendingVideo << std::endl; } pendingVideo = nullptr; c.outPath = ""; // Reset, if set if (s != 0 && waitif > 0) { cout << "Error, press enter to continue"; cin.get(); } else if (waitif > 1) { cout << "Press enter to continue"; cin.get(); } cout << std::endl; } if (opt != "--process") if (opt == "-i") pendingVideo = argv[++i]; else { std::string filepath(argv[i]); bool unvrFile = filepath.find(".unvr.") != std::string::npos; if (!unvrFile) pendingVideo = argv[i]; else cout << "Ignoring unvr file " << argv[i] << std::endl; } } } }
38.716667
145
0.620146
unvrtool
3b8053fec43e49d20300eef56be3664934adb7e3
5,574
cpp
C++
Oxcart/src/data/Model.cpp
JackiBackiBoy/Oxcart
75cb9efbbf4122d06015f6700bcf3b22b1241a2c
[ "Apache-2.0" ]
1
2020-10-06T13:52:15.000Z
2020-10-06T13:52:15.000Z
Oxcart/src/data/Model.cpp
JackiBackiBoy/Oxcart
75cb9efbbf4122d06015f6700bcf3b22b1241a2c
[ "Apache-2.0" ]
null
null
null
Oxcart/src/data/Model.cpp
JackiBackiBoy/Oxcart
75cb9efbbf4122d06015f6700bcf3b22b1241a2c
[ "Apache-2.0" ]
null
null
null
#include "Model.h" #include <iostream> #include "GL/glew.h" #include "vendor/stb_image/stb_image.h" Model::Model(const std::string& aPath, const bool& anIsFlippedUVs) : myIsFlippedUVs(anIsFlippedUVs) { LoadModel(aPath); } void Model::Render(Shader& aShader) { for (unsigned int i = 0; i < myMeshes.size(); i++) { myMeshes[i].Render(aShader); } } unsigned int Model::TextureFromFile(const char* aPath, const std::string& aDirectory) { std::string tempFileName = std::string(aPath); tempFileName = aDirectory + '/' + tempFileName; unsigned int tempTextureID; glGenTextures(1, &tempTextureID); int tempWidth; int tempHeight; int tempChannelCount; stbi_set_flip_vertically_on_load(true); unsigned char* tempData = stbi_load(tempFileName.c_str(), &tempWidth, &tempHeight, &tempChannelCount, 0); if (tempData) { GLenum tempFormat; if (tempChannelCount == 1) { tempFormat = GL_RED; } else if (tempChannelCount == 3) { tempFormat = GL_RGB; } else if (tempChannelCount == 4) { tempFormat = GL_RGBA; } glBindTexture(GL_TEXTURE_2D, tempTextureID); glTexImage2D(GL_TEXTURE_2D, 0, tempFormat, tempWidth, tempHeight, 0, tempFormat, GL_UNSIGNED_BYTE, tempData); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(tempData); } else { std::cout << "Error (Assimp): " << aPath << std::endl; stbi_image_free(tempData); } return tempTextureID; } void Model::LoadModel(const std::string& aPath) { Assimp::Importer tempImporter; unsigned int tempModelFlags = aiProcess_Triangulate | aiProcess_GenSmoothNormals; // If the model has flipped UVs then flip them if (myIsFlippedUVs) { tempModelFlags |= aiProcess_FlipUVs; } const aiScene* tempScene = tempImporter.ReadFile(aPath, tempModelFlags); if (!tempScene || tempScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !tempScene->mRootNode) { std::cout << "Error (Assimp): " << tempImporter.GetErrorString() << std::endl; return; } myDirectory = aPath.substr(0, aPath.find_last_of('/')); ProcessNode(tempScene->mRootNode, tempScene); } void Model::ProcessNode(aiNode* aNode, const aiScene* aScene) { // Process the node's meshes for (unsigned int i = 0; i < aNode->mNumMeshes; i++) { aiMesh* tempMesh = aScene->mMeshes[aNode->mMeshes[i]]; myMeshes.push_back(ProcessMesh(tempMesh, aScene)); } // Process the meshes of the children of the node for (unsigned int i = 0; i < aNode->mNumChildren; i++) { ProcessNode(aNode->mChildren[i], aScene); } } Mesh Model::ProcessMesh(aiMesh* aMesh, const aiScene* aScene) { std::vector<Vertex> tempVertices; std::vector<unsigned int> tempIndices; std::vector<Texture2D> tempTextures; for (unsigned int i = 0; i < aMesh->mNumVertices; i++) { Vertex tempVertex; Vector3D tempVector3D; // Process vertex positions tempVector3D.x = aMesh->mVertices[i].x; tempVector3D.y = aMesh->mVertices[i].y; tempVector3D.z = aMesh->mVertices[i].z; tempVertex.position = tempVector3D; // Process vertex normals if (aMesh->HasNormals()) { tempVector3D.x = aMesh->mNormals[i].x; tempVector3D.y = aMesh->mNormals[i].y; tempVector3D.z = aMesh->mNormals[i].z; tempVertex.normal = tempVector3D; } // Process texture coordinates if (aMesh->mTextureCoords[0]) { Vector2D tempVector2D; tempVector2D.x = aMesh->mTextureCoords[0][i].x; tempVector2D.y = aMesh->mTextureCoords[0][i].y; tempVertex.textureCoords = tempVector2D; } else { tempVertex.textureCoords = { 0, 0 }; } tempVertices.push_back(tempVertex); } // Process indices for (unsigned int i = 0; i < aMesh->mNumFaces; i++) { aiFace tempFace = aMesh->mFaces[i]; for (unsigned int j = 0; j < tempFace.mNumIndices; j++) { tempIndices.push_back(tempFace.mIndices[j]); } } // Process the material if (aMesh->mMaterialIndex >= 0) { aiMaterial* tempMaterial = aScene->mMaterials[aMesh->mMaterialIndex]; // Diffuse maps std::vector<Texture2D> tempDiffuseMaps = LoadMaterialTextures(tempMaterial, aiTextureType_DIFFUSE, "diffuse"); tempTextures.insert(tempTextures.end(), tempDiffuseMaps.begin(), tempDiffuseMaps.end()); // Specular maps std::vector<Texture2D> tempSpecularMaps = LoadMaterialTextures(tempMaterial, aiTextureType_SPECULAR, "specular"); tempTextures.insert(tempTextures.end(), tempSpecularMaps.begin(), tempSpecularMaps.end()); } return Mesh(tempVertices, tempIndices, tempTextures); } std::vector<Texture2D> Model::LoadMaterialTextures(aiMaterial* aMaterial, aiTextureType aType, std::string aTypeName) { std::vector<Texture2D> tempTextures; for (unsigned int i = 0; i < aMaterial->GetTextureCount(aType); i++) { aiString tempString; aMaterial->GetTexture(aType, i, &tempString); bool tempShouldSkip = false; for (unsigned int j = 0; j < myLoadedTextures.size(); j++) { if (std::strcmp(myLoadedTextures[j].path.data(), tempString.C_Str()) == 0) { tempTextures.push_back(myLoadedTextures[j]); tempShouldSkip = true; break; } } if (!tempShouldSkip) { Texture2D tempTexture; tempTexture.ID = TextureFromFile(tempString.C_Str(), myDirectory); tempTexture.type = aTypeName; tempTexture.path = tempString.C_Str(); tempTextures.push_back(tempTexture); myLoadedTextures.push_back(tempTexture); } } return tempTextures; }
26.542857
117
0.719232
JackiBackiBoy
3b80beb3bb688b516d918bffbb1cb93a8e9c502a
484
cpp
C++
Implementations/06 - DP (3)/6.2 - Examples/Traveling Salesman (4).cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
Implementations/06 - DP (3)/6.2 - Examples/Traveling Salesman (4).cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
Implementations/06 - DP (3)/6.2 - Examples/Traveling Salesman (4).cpp
Senpat/USACO
7f65e083e70c10b43224c6e1acbab79af249b942
[ "MIT" ]
null
null
null
/** * Description: Bitset DP example * Solves TSP for small N */ const int MX = 15; int N, dp[MX][1<<MX], dist[MX][MX]; int solve() { F0R(i,N) F0R(j,1<<N) dp[i][j] = MOD; dp[0][1] = 0; F0R(j,1<<N) F0R(i,N) if (j&(1<<i)) F0R(k,N) if (!(j&(1<<k))) dp[k][j^(1<<k)] = min(dp[k][j^(1<<k)], dp[i][j]+dist[i][k]); int ans = MOD; FOR(j,1,N) ans = min(ans,dp[j][(1<<N)-1]+dist[j][0]); return ans; }
22
57
0.417355
Senpat
3b8416520722faa27530f6ed5064873df412ef17
1,414
cpp
C++
GL_GraphicLab/src/Scene/TriangleScene.cpp
acros/GL_GraphicLab
a2b892d87d0f022c15f092ab45950495dbdb4bd4
[ "MIT" ]
3
2016-11-16T18:04:50.000Z
2018-05-10T11:31:52.000Z
GL_GraphicLab/src/Scene/TriangleScene.cpp
acros/GL_GraphicLab
a2b892d87d0f022c15f092ab45950495dbdb4bd4
[ "MIT" ]
null
null
null
GL_GraphicLab/src/Scene/TriangleScene.cpp
acros/GL_GraphicLab
a2b892d87d0f022c15f092ab45950495dbdb4bd4
[ "MIT" ]
null
null
null
#include "TriangleScene.h" TriangleScene::TriangleScene(Renderer& renderer) : Scene(renderer) { mVertStr = "#version 300 es \n" "layout(location = 0) in vec4 vPosition; \n" "void main() \n" "{ \n" " gl_Position = vPosition; \n" "} \n"; mFragStr = "#version 300 es \n" "precision mediump float; \n" "out vec4 fragColor; \n" "void main() \n" "{ \n" " fragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 ); \n" "} \n"; } TriangleScene::~TriangleScene() { } void TriangleScene::render() { mRendererRef.beginDraw(); GLfloat vVertices[] = { 0.0f, 1.f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; GLfloat vColors[] = { 0.5f,0.f,0.0f, 0.0f, 1.f,0.0f, 0.0f,0.0f,1.0f }; // Use the program object glUseProgram(mShaderProgram); // Load the vertex data glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices); glEnableVertexAttribArray(0); //the next triangle // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, vColors); // glEnableVertexAttribArray(1); glDrawArrays(GL_TRIANGLES, 0, 3); mRendererRef.endDraw(); }
23.966102
65
0.476662
acros
3b86ba6e6e90bb73e2ed0e2ca9a13a513ba19ef8
12,048
cpp
C++
prototype/TAT-C/cpp/test/SystemTest_Analysis.cpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
prototype/TAT-C/cpp/test/SystemTest_Analysis.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
prototype/TAT-C/cpp/test/SystemTest_Analysis.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//------------------------------------------------------------------------------ // SystemTest_Analysis //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Author: Wendy Shoan // Created: 2016.05.31 // /** * System tester for analysis */ //------------------------------------------------------------------------------ #include <iostream> #include <string> #include <ctime> #include <cmath> #include "gmatdefs.hpp" #include "GmatConstants.hpp" #include "Rvector6.hpp" #include "Rvector3.hpp" #include "Rmatrix.hpp" #include "RealUtilities.hpp" #include "MessageInterface.hpp" #include "ConsoleMessageReceiver.hpp" #include "AbsoluteDate.hpp" #include "Spacecraft.hpp" #include "Earth.hpp" #include "KeyValueStatistics.hpp" #include "VisiblePOIReport.hpp" #include "OrbitState.hpp" #include "PointGroup.hpp" #include "Propagator.hpp" #include "ConicalSensor.hpp" #include "CoverageChecker.hpp" #include "TimeTypes.hpp" using namespace std; using namespace GmatMathUtil; using namespace GmatMathConstants; //------------------------------------------------------------------------------ // int main(int argc, char *argv[]) //------------------------------------------------------------------------------ int main(int argc, char *argv[]) { std::string outFormat = "%16.9f "; Real tolerance = 1e-15; ConsoleMessageReceiver *consoleMsg = ConsoleMessageReceiver::Instance(); MessageInterface::SetMessageReceiver(consoleMsg); std::string outPath = "./"; MessageInterface::SetLogFile(outPath + "GmatLog.txt"); MessageInterface::ShowMessage("%s\n", GmatTimeUtil::FormatCurrentTime().c_str()); // Set global format setting GmatGlobal *global = GmatGlobal::Instance(); global->SetActualFormat(false, false, 16, 1, false); char *buffer = NULL; buffer = getenv("OS"); if (buffer != NULL) { MessageInterface::ShowMessage("Current OS is %s\n", buffer); } else { MessageInterface::ShowMessage("Buffer is NULL\n"); } MessageInterface::ShowMessage("*** START TEST ***\n"); try { // Test the PointGroup MessageInterface::ShowMessage("*** TEST*** Analysis!!!!\n"); // This is a usage example that drives O-C code and computes standard // statistical products typical of O-C analysis. This script is an example // of how R-M might use the O-C data. AbsoluteDate *date; OrbitState *state; ConicalSensor *sensor; Spacecraft *sat1; Propagator *prop; PointGroup *pGroup; std::vector<VisiblePOIReport> coverageEvents; clock_t t0 = clock(); Integer numIter = 1; for (Integer ii = 0; ii < numIter; ii++) // ********** { bool showPlots = false; // Create the epoch object and set the initial epoch date = new AbsoluteDate(); date->SetGregorianDate(2017,1,15,22,30,20.111); // MessageInterface::ShowMessage(" --- date created\n"); // Create the spacecraft state object and set Keplerian elements state = new OrbitState(); state->SetKeplerianState(6700.0,0.002,90.0*RAD_PER_DEG, PI/4.0 + PI/6.0,0.2345,PI/6.0); // MessageInterface::ShowMessage(" --- state created\n"); // Create a conical sensor sensor = new ConicalSensor(PI); // MessageInterface::ShowMessage(" --- conical sensor created\n"); // Create a spacecraft giving it a state and epoch sat1 = new Spacecraft(date,state); sat1->AddSensor(sensor); // MessageInterface::ShowMessage(" --- spacecraft created\n"); // Create the propagator prop = new Propagator(sat1); // MessageInterface::ShowMessage(" --- propagator created\n"); // Create the point group and initialize the coverage checker pGroup = new PointGroup(); pGroup->AddHelicalPointsByNumPoints(200); CoverageChecker *covChecker = new CoverageChecker(pGroup,sat1); // MessageInterface::ShowMessage(" --- point group created\n"); if (showPlots) ; // don't have this in C++ // figHandle = pGroup.PlotAllTestPoints(); // Propagate for a duration and collect data Real startDate = date->GetJulianDate(); Integer count = 0; // Over 1 day while (date->GetJulianDate() < ((Real)startDate + 1.0)) { // MessageInterface::ShowMessage(" --- about to advance the time and propagate\n"); // Propagate date->Advance(120.0); prop->Propagate(*date); // MessageInterface::ShowMessage(" --- done advancing the time and propagating\n"); // Compute points in view IntegerArray accessPoints = covChecker->AccumulateCoverageData(); // Plotting stuff used for testing and visualization if (showPlots) { ; // // Save orbit for plotting. Kludge cause output classes not done yet. // count++; // Rvector6 intertialState = sat1->GetCartesianState(); // Real jDate = sat1.GetJulianDate(); // Earth *cb = new Earth(); // orbitState(count,:) = cb.GetBodyFixedState(intertialState(1:3,1),jDate)'; // pGroup.PlotSelectedTestPoints(accessPoints); drawnow; // if count >= 2 // figure(figHandle); hold on; // plot3(orbitState(count-1:count,1)/6378,orbitState(count-1:count,2)/6378,... // orbitState(count-1:count,3)/6378,'k-','MarkerSize',3) } } // MessageInterface::ShowMessage(" --- propagation completed\n"); // Compute coverage data coverageEvents = covChecker->ProcessCoverageData(); // MessageInterface::ShowMessage(" --- ProcessCoverageData completed (%d reports)\n", // (Integer) coverageEvents.size()); } // ***** Real timeSpent = ((Real) (clock() - t0)) / CLOCKS_PER_SEC; MessageInterface::ShowMessage("TIME SPENT in %d iterations is %12.10f seconds\n", numIter,timeSpent); RealArray lonVec; RealArray latVec; // Compute coverate stats. Shows how R-M might use data for coverage analysis // Create Lat\Lon Grid for (Integer pointIdx = 0; pointIdx < pGroup->GetNumPoints(); pointIdx++) { Rvector3 *vec = pGroup->GetPointPositionVector(pointIdx); lonVec.push_back(ATan(vec->GetElement(1),vec->GetElement(0))*DEG_PER_RAD); latVec.push_back(ASin(vec->GetElement(2)/vec->GetMagnitude())*DEG_PER_RAD); } MessageInterface::ShowMessage(" --- lat/long set-up completed\n"); // Compute total coverage statistics from all coverage events Rvector totalCoverageDuration(pGroup->GetNumPoints()); IntegerArray numPassVec; // (pGroup->GetNumPoints()); for (Integer ii = 0; ii < pGroup->GetNumPoints(); ii++) numPassVec.push_back(0); Rvector minPassVec(pGroup->GetNumPoints()); Rvector maxPassVec(pGroup->GetNumPoints()); for (Integer eventIdx = 0; eventIdx < coverageEvents.size(); eventIdx++) { VisiblePOIReport currEvent = coverageEvents.at(eventIdx); Integer poiIndex = currEvent.GetPOIIndex(); Real eventDuration = (currEvent.GetEndDate().GetJulianDate() - currEvent.GetStartDate().GetJulianDate()) * 24.0; totalCoverageDuration(poiIndex) = totalCoverageDuration(poiIndex) + eventDuration; // Rvector3 vec = pGroup->GetPointPositionVector(pointIdx); // ? // % lat = atan2(vec(2),vec(1))*180/pi; // % lon = asin(vec(3)/norm(vec)); // % Z(lat,lon) = totalCoverageDuration; // Save the maximum duration if necessary if (eventDuration > maxPassVec(poiIndex)) maxPassVec(poiIndex) = eventDuration; if (minPassVec(poiIndex) == 0 || (eventDuration< maxPassVec(poiIndex))) minPassVec(poiIndex) = eventDuration; numPassVec.at(poiIndex) = numPassVec.at(poiIndex) + 1; } // *********** display stuff *********** // Write the simple coverage report to the MATLAB command window MessageInterface::ShowMessage(" =======================================================================\n"); MessageInterface::ShowMessage(" ==================== Brief Coverage Analysis Report ===================\n"); MessageInterface::ShowMessage(" lat (deg): Latitude of point in degrees \n"); MessageInterface::ShowMessage(" lon (deg): Longitude of point in degrees \n"); MessageInterface::ShowMessage(" numPasses: Number of total passes seen by a point \n"); MessageInterface::ShowMessage(" totalDur : Total duration point was observed in hours \n"); MessageInterface::ShowMessage(" minDur : Duration of the shortest pass in minutes \n"); MessageInterface::ShowMessage(" maxDur : Duration of the longest pass in hours \n"); MessageInterface::ShowMessage(" =======================================================================\n"); MessageInterface::ShowMessage(" =======================================================================\n"); MessageInterface::ShowMessage(" "); // data = [latVec,lonVec, numPassVec, totalCoverageDuration, minPassVec, maxPassVec]; <<<<<<<<< Integer headerCount = 1; Integer dataEnd = 0; for (Integer passIdx = 0; passIdx < pGroup->GetNumPoints(); passIdx+= 10) { MessageInterface::ShowMessage(" lat (deg) lon (deg) numPasses totalDur minDur maxDur\n"); dataEnd = passIdx + 10; // 9; for (Integer ii = 0; ii < 10; ii++) // 9 MessageInterface::ShowMessage(" %le %le %d %le %le %le \n", // MessageInterface::ShowMessage(" %12.10f %12.10f %d %12.10f %12.10f %12.10f \n", latVec.at(passIdx+ii), lonVec.at(passIdx+ii), numPassVec.at(passIdx+ii), totalCoverageDuration(passIdx+ii), minPassVec(passIdx+ii), maxPassVec(passIdx+ii)); } if (dataEnd + 1 < pGroup->GetNumPoints()) { MessageInterface::ShowMessage(" lat (deg) lon (deg) numPasses totalDur minDur maxDur\n"); for (Integer ii = dataEnd; ii < pGroup->GetNumPoints(); ii++) MessageInterface::ShowMessage(" %le %le %d %le %le %le \n", // MessageInterface::ShowMessage(" %12.10f %12.10f %d %12.10f %12.10f %12.10f \n", latVec.at(ii), lonVec.at(ii), numPassVec.at(ii), totalCoverageDuration(ii), minPassVec(ii), maxPassVec(ii)); } cout << endl; cout << "Hit enter to end" << endl; cin.get(); // delete pointers here MessageInterface::ShowMessage("*** END TEST ***\n"); } catch (BaseException &be) { MessageInterface::ShowMessage("Exception caught: %s\n", be.GetFullMessage().c_str()); } }
40.840678
127
0.534363
Randl
3b898bfcedf9131a37a2ad56305439fe557e7b94
4,765
cpp
C++
src/Field.cpp
renatocf/rugby-game-cpp
4a00f1b582304d728f47e39d6a97d02bdce40e16
[ "MIT" ]
null
null
null
src/Field.cpp
renatocf/rugby-game-cpp
4a00f1b582304d728f47e39d6a97d02bdce40e16
[ "MIT" ]
null
null
null
src/Field.cpp
renatocf/rugby-game-cpp
4a00f1b582304d728f47e39d6a97d02bdce40e16
[ "MIT" ]
null
null
null
// C Headers #include <cassert> // Standard exceptions #include <sstream> #include <stdexcept> // Internal headers #include "Dimension.hpp" #include "Position.hpp" // Main header #include "Field.hpp" namespace rugby { /* ////////////////////////////////////////////////////////////////////////// */ /* -------------------------------------------------------------------------- */ /* PUBLIC */ /* -------------------------------------------------------------------------- */ /* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ /*----------------------------------------------------------------------------*/ /* CONSTRUCTORS */ /*----------------------------------------------------------------------------*/ Field::Field(const dimension_t& dimension) : _dimension(dimension), _grid(dimension.height, std::vector<ItemPtr>(dimension.width)) { if (_dimension < Field::MIN_DIMENSION) { std::stringstream message_template; message_template << "Dimension must be at least (" << Field::MIN_DIMENSION << ") because of the Field's borders"; throw std::invalid_argument(message_template.str()); } } /*----------------------------------------------------------------------------*/ /* CONCRETE METHODS */ /*----------------------------------------------------------------------------*/ const dimension_t& Field::dimension() const { return _dimension; } /*----------------------------------------------------------------------------*/ std::ostream& Field::print_info(std::ostream& out) const { out << "Dimensions (H x W)" << _dimension.height << " x " << _dimension.width << std::endl; return out; } /*----------------------------------------------------------------------------*/ std::ostream& Field::print_grid(std::ostream& out) const { for (size_t i = 0; i < _dimension.height; i++) { for (size_t j = 0; j < _dimension.width; j++) { out << '|'; out << _grid[i][j]; } out << '|'; out << std::endl; } out << std::endl; return out; } /*----------------------------------------------------------------------------*/ void Field::add_item(const ItemPtr& item, const position_t& position) { if (item == nullptr) return; if (position_is_beyond_limits(position)) { std::stringstream message_template; message_template << "Item " << item << "must be within the limits of the field!"; throw std::out_of_range(message_template.str()); } _grid[position.i][position.j] = item; item->position(position); } /*----------------------------------------------------------------------------*/ void Field::move_item(const ItemPtr& item, const direction_t& direction) { if (item == nullptr) return; position_t item_position = item->position(); // Given how items are added to the field, their position // should never be in the border of the field assert(!position_is_beyond_limits(item->position())); if (!item->is_movable()) { throw std::logic_error( "Should not try to move an item that is not movable"); } position_t new_position = item->position().calculate_move(direction); // Change current position in the grid _grid[new_position.i][new_position.j] = item; _grid[item_position.i][item_position.j] = nullptr; item->position(new_position); } /*----------------------------------------------------------------------------*/ /* NON-MEMBER OPERATORS */ /*----------------------------------------------------------------------------*/ std::ostream& operator<<(std::ostream& out, const Field& field) { field.print_grid(out); return out; } /* ////////////////////////////////////////////////////////////////////////// */ /* -------------------------------------------------------------------------- */ /* PRIVATE */ /* -------------------------------------------------------------------------- */ /* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ /*----------------------------------------------------------------------------*/ /* CONCRETE METHODS */ /*----------------------------------------------------------------------------*/ bool Field::position_is_beyond_limits(const position_t& p) const { return p.i > _dimension.height-1 || p.j > _dimension.width-1; } /*----------------------------------------------------------------------------*/ } // namespace rugby
33.090278
80
0.375236
renatocf
3b8d0919b8a8894ea4ae3b9f0431ca57787d895e
3,426
hpp
C++
missions/po4.tanoa/Tasks/op_2_targetWeaponsCache.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/po4.tanoa/Tasks/op_2_targetWeaponsCache.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/po4.tanoa/Tasks/op_2_targetWeaponsCache.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
class op_2_TargetWeaponsCache: TaskDefaults { scope = 1; typeID = 2; positionSearchTypes[] = {"Town","Shack","Village","House","Clearing","Hill"}; positionSearchRadius = 1000; positionNearLast = 1; class TaskDetails { title = "%1"; description[] = { "<t>Ref: %2</t> | <t>Date: %3<br/>AO: %4 %5 near %6</t>" ,"<t size='1.1' color='#FFC600'>Brief:</t> <t>Redacted.</t>" ,"<t size='1.1' color='#FFC600'>Action:</t> <t>Redacted.</t>" ,"<t size='1.1' color='#FFC600'>Enemy:</t> <t>Redacted.</t>" ,"<t size='1.1' color='#FFC600'>Note:</t> <t>Redacted.</t>" ,"op_2_TargetWeaponsCache" }; iconType = "Destroy"; iconPosition = "position"; textArguments[] = {"operationName","randomCode","datetime","worldRegion","worldName","nearestTown","factionBLUshort","factionOPFshort"}; }; class Markers { class marker_A { shape = "RECTANGLE"; brush = "SolidBorder"; colour = "ColorOpfor"; size[] = {0.99,0.99}; alpha = 0.2; }; class marker_B: marker_A { brush = "Border"; size[] = {1.2,1.2}; alpha = 1; }; class marker_C: marker_A { brush = "Border"; size[] = {1.0,1.0}; alpha = 1; }; class marker_D: marker_A { brush = "FDiagonal"; size[] = {1.2,0.1}; alpha = 0.9; direction = 0; distance = 1.1; }; class marker_E: marker_D { direction = 180; }; class marker_F: marker_D { size[] = {1.0,0.1}; direction = 90; angle = 90; }; class marker_G: marker_F { direction = 270; }; class marker_target { position = "positionOffset"; shape = "ICON"; type = "mil_objective"; colour = "ColorOpfor"; size[] = {0.8,0.8}; alpha = 0.6; text = "Target"; }; }; class Groups { class weaponsCache_1 { probability = 1; isTarget = 1; objectTypes[] = {"Box_FIA_Ammo_F","Box_FIA_Support_F","Box_FIA_Wps_F"}; position = "positionOffset"; occupyBuildings = 1; radius[] = {150,150}; }; class weaponsCache_2: weaponsCache_1 { probability = 0.8; minPlayers = 4; }; class weaponsCache_3: weaponsCache_1 { probability = 0.8; minPlayers = 8; }; class EN_Group_1 { probability = 0.9; position = "positionOffset"; distance[] = {20,50}; direction[] = {0,360}; faction = "FactionTypeOPF"; groupTypes[] = {"Squad8","Squad8_AA","Squad8_AR","Squad8_AT","Squad8_M","Squad4","Squad4_AA","Squad4_AR","Squad4_AT","Squad4_M"}; isPatrolling = 0.9; radius[] = {50,150}; isDefending = 1; occupyBuildings = 1; }; class EN_Group_2: EN_Group_1 { minPlayers = 2; distance[] = {100,150}; radius[] = {150,200}; }; class EN_Group_3: EN_Group_1 { minPlayers = 6; distance[] = {150,200}; radius[] = {200,250}; }; class EN_Vehicle_Group_1 { probability = 0.85; position = "positionOffset"; distance[] = {50,100}; direction[] = {0,360}; faction = "FactionTypeOPF"; vehicleTypes[] = {"CarTurret","Car"}; createCrew = 1; isPatrolling = 0.6; radius[] = {150,250}; }; class EN_Vehicle_Group_2: EN_Vehicle_Group_1 { probability = 0.7; minPlayers = 8; vehicleTypes[] = {"CarTurret","Armour_AA","Armour_APC"}; }; class EN_Vehicle_Group_3: EN_Vehicle_Group_1 { probability = 0.7; minPlayers = 16; vehicleTypes[] = {"Armour_AA","Armour_APC"}; }; }; class Objective { class Succeeded { state = 1; // 0:Created, 1:Succeeded, 2: Failed, 3: Canceled condition = "_cacheDestroyed"; }; }; };
25.567164
138
0.603619
ademirt
3b942e189ccfcc2de67a8dca1bfd1bc5c1c50938
2,006
cpp
C++
src/RE/T/TESForm.cpp
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
118
2019-02-07T22:34:11.000Z
2022-03-29T10:40:40.000Z
src/RE/T/TESForm.cpp
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
63
2019-07-30T13:50:11.000Z
2022-02-19T02:14:33.000Z
src/RE/T/TESForm.cpp
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
71
2019-05-21T00:15:51.000Z
2022-03-03T15:14:19.000Z
#include "RE/T/TESForm.h" #include "RE/B/BGSDefaultObjectManager.h" #include "RE/F/FormTraits.h" #include "RE/I/IObjectHandlePolicy.h" #include "RE/I/InventoryEntryData.h" #include "RE/T/TESFullName.h" #include "RE/T/TESGlobal.h" #include "RE/T/TESModel.h" #include "RE/T/TESObjectREFR.h" #include "RE/V/VirtualMachine.h" namespace RE { std::int32_t TESForm::GetGoldValue() const { const auto obj = As<TESBoundObject>(); if (obj) { const InventoryEntryData entry{ const_cast<TESBoundObject*>(obj), 1 }; return entry.GetValue(); } else { return -1; } } const char* TESForm::GetName() const { const auto fullName = As<TESFullName>(); if (fullName) { const auto str = fullName->GetFullName(); return str ? str : ""; } else { return ""; } } float TESForm::GetWeight() const { const auto survival = []() { const auto dobj = BGSDefaultObjectManager::GetSingleton(); const auto survival = dobj ? dobj->GetObject<TESGlobal>(DEFAULT_OBJECT::kSurvivalModeEnabled) : nullptr; return survival ? survival->value == 1.0F : false; }; const auto ref = As<TESObjectREFR>(); const auto baseObj = ref ? ref->GetBaseObject() : nullptr; const auto form = baseObj ? baseObj : this; if (!survival() && (form->IsAmmo() || form->IsLockpick())) { return 0.0F; } else if (const auto weightForm = form->As<TESWeightForm>(); weightForm) { return weightForm->weight; } else if (form->Is(FormType::NPC)) { const auto npc = static_cast<const TESNPC*>(form); return npc->weight; } else { return -1.0F; } } bool TESForm::HasVMAD() const { const auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); if (!vm) { return false; } const auto policy = vm->GetObjectHandlePolicy(); if (!policy) { return false; } const auto handle = policy->GetHandleForObject(GetFormType(), this); return handle != policy->EmptyHandle(); } bool TESForm::HasWorldModel() const noexcept { return As<TESModel>() != nullptr; } }
24.765432
107
0.666999
colinswrath
3b956fe7da7e80058d9a6d2171a462d5186a13fc
2,502
cc
C++
src/IndexEntryParser.cc
Black-Library/black-library-parsers
e5fa87d1066c0247e3636a51ff0b973c894c4aec
[ "MIT" ]
null
null
null
src/IndexEntryParser.cc
Black-Library/black-library-parsers
e5fa87d1066c0247e3636a51ff0b973c894c4aec
[ "MIT" ]
null
null
null
src/IndexEntryParser.cc
Black-Library/black-library-parsers
e5fa87d1066c0247e3636a51ff0b973c894c4aec
[ "MIT" ]
null
null
null
/** * IndexEntryParser.cc */ #include <functional> #include <iostream> #include <LogOperations.h> #include <IndexEntryParser.h> #include <ShortTimeGenerator.h> namespace black_library { namespace core { namespace parsers { namespace BlackLibraryCommon = black_library::core::common; IndexEntryParser::IndexEntryParser(parser_t parser_type) : Parser(parser_type), index_entries_() { parser_behavior_ = parser_behavior_t::INDEX_ENTRY; } int IndexEntryParser::CalculateIndexBounds(const ParserJob &parser_job) { if (parser_job.start_number > index_entries_.size()) { index_ = 0; } else { index_ = parser_job.start_number - 1; } if (parser_job.start_number <= parser_job.end_number && index_entries_.size() >= parser_job.end_number) { end_index_ = parser_job.end_number - 1; } else { end_index_ = index_entries_.size() - 1; } if (index_ > index_entries_.size() || index_entries_.empty()) { BlackLibraryCommon::LogError(parser_name_, "Requested start index {} greater than detected entries size: {}", index_, index_entries_.size()); return -1; } return 0; } void IndexEntryParser::ExpendedAttempts() { ++index_; } int IndexEntryParser::PreParseLoop(xmlNodePtr root_node, const ParserJob &parser_job) { BlackLibraryCommon::LogDebug(parser_name_, "Find index entry nodes"); FindIndexEntries(root_node); BlackLibraryCommon::LogDebug(parser_name_, "Found {} nodes", index_entries_.size()); if (index_entries_.size() <= 0 && index_entries_.size() < parser_job.start_number) { BlackLibraryCommon::LogError(parser_name_, "Index entries size error"); return -1; } return 0; } bool IndexEntryParser::ReachedEnd() { return index_ > end_index_; } void IndexEntryParser::SaveLastUrl(ParserResult &parser_result) { parser_result.metadata.last_url = index_entries_[index_entries_.size() - 1].data_url; } void IndexEntryParser::SaveUpdateDate(ParserResult &parser_result) { for (const auto & index_entry : index_entries_) { if (index_entry.time_published > parser_result.metadata.update_date) parser_result.metadata.update_date = index_entry.time_published; } if (parser_result.metadata.update_date <= 0) BlackLibraryCommon::LogError(parser_name_, "Failed to get update date for UUID: {}", uuid_); } } // namespace parsers } // namespace core } // namespace black_library
24.057692
149
0.701039
Black-Library
3b9704f9fdda59e24eca8c843b63597101f3bc0e
460
cpp
C++
page23/page23.cpp
valeriivoronkov/cplusplus_schildt3
8690889543f595e00bef99fc6981260fffae67d3
[ "MIT" ]
null
null
null
page23/page23.cpp
valeriivoronkov/cplusplus_schildt3
8690889543f595e00bef99fc6981260fffae67d3
[ "MIT" ]
null
null
null
page23/page23.cpp
valeriivoronkov/cplusplus_schildt3
8690889543f595e00bef99fc6981260fffae67d3
[ "MIT" ]
null
null
null
/* * Эта программа преобразует галлоны в литры. */ /* * File: page23.cpp * Author: xcoder * * Created on November 5, 2018, 7:56 PM */ #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int gallons, liters; cout << "Введите количество галлонов: "; cin >> gallons; // Ввод данных от пользователя. liters = gallons * 4; // Преобразование в литры. cout << "Литров: " << liters; return 0; }
16.428571
52
0.604348
valeriivoronkov
3b9776ec72bc734ab0906517a86a44e35cceedc9
231
cpp
C++
parser.cpp
wistron-corporation/openpower-vpd-parser
73b589b85ec6194853f1474b76e62623468debdb
[ "Apache-2.0" ]
null
null
null
parser.cpp
wistron-corporation/openpower-vpd-parser
73b589b85ec6194853f1474b76e62623468debdb
[ "Apache-2.0" ]
null
null
null
parser.cpp
wistron-corporation/openpower-vpd-parser
73b589b85ec6194853f1474b76e62623468debdb
[ "Apache-2.0" ]
null
null
null
#include "parser.hpp" #include "impl.hpp" namespace openpower { namespace vpd { Store parse(Binary&& vpd) { parser::Impl p(std::move(vpd)); Store s = p.run(); return s; } } // namespace vpd } // namespace openpower
12.157895
35
0.636364
wistron-corporation
3b984a4f11986b24fd1a3619b9199a63e44a4c1c
4,273
cpp
C++
dpctl-capi/tests/test_sycl_kernel_interface.cpp
reazulhoque/dpctl
27634efff7bcaf2096d3e236d9739e1a25e0d99e
[ "Apache-2.0" ]
1
2020-08-09T13:55:34.000Z
2020-08-09T13:55:34.000Z
dpctl-capi/tests/test_sycl_kernel_interface.cpp
PokhodenkoSA/pydppl
9b8644b167a2bc9d1067e5c0d13d3abef0bff82b
[ "Apache-2.0" ]
6
2021-07-08T08:08:25.000Z
2021-09-10T13:55:55.000Z
dpctl-capi/tests/test_sycl_kernel_interface.cpp
PokhodenkoSA/dpctl
9b8644b167a2bc9d1067e5c0d13d3abef0bff82b
[ "Apache-2.0" ]
null
null
null
//===-- test_sycl_program_interface.cpp - Test cases for kernel interface ===// // // Data Parallel Control (dpctl) // // Copyright 2020-2021 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. // //===----------------------------------------------------------------------===// /// /// \file /// This file has unit test cases for functions defined in /// dpctl_sycl_kernel_interface.h. /// //===----------------------------------------------------------------------===// #include "dpctl_sycl_context_interface.h" #include "dpctl_sycl_device_interface.h" #include "dpctl_sycl_device_selector_interface.h" #include "dpctl_sycl_kernel_interface.h" #include "dpctl_sycl_program_interface.h" #include "dpctl_sycl_queue_interface.h" #include "dpctl_sycl_queue_manager.h" #include "dpctl_utils.h" #include <CL/sycl.hpp> #include <array> #include <gtest/gtest.h> using namespace cl::sycl; namespace { struct TestDPCTLSyclKernelInterface : public ::testing::TestWithParam<const char *> { const char *CLProgramStr = R"CLC( kernel void add(global int* a, global int* b, global int* c) { size_t index = get_global_id(0); c[index] = a[index] + b[index]; } kernel void axpy(global int* a, global int* b, global int* c, int d) { size_t index = get_global_id(0); c[index] = a[index] + d*b[index]; } )CLC"; const char *CompileOpts = "-cl-fast-relaxed-math"; DPCTLSyclDeviceSelectorRef DSRef = nullptr; DPCTLSyclDeviceRef DRef = nullptr; TestDPCTLSyclKernelInterface() { DSRef = DPCTLFilterSelector_Create(GetParam()); DRef = DPCTLDevice_CreateFromSelector(DSRef); } ~TestDPCTLSyclKernelInterface() { DPCTLDeviceSelector_Delete(DSRef); DPCTLDevice_Delete(DRef); } void SetUp() { if (!DRef) { auto message = "Skipping as no device of type " + std::string(GetParam()) + "."; GTEST_SKIP_(message.c_str()); } } }; } // namespace TEST_P(TestDPCTLSyclKernelInterface, CheckGetFunctionName) { auto QueueRef = DPCTLQueue_CreateForDevice(DRef, nullptr, 0); auto CtxRef = DPCTLQueue_GetContext(QueueRef); auto PRef = DPCTLProgram_CreateFromOCLSource(CtxRef, CLProgramStr, CompileOpts); auto AddKernel = DPCTLProgram_GetKernel(PRef, "add"); auto AxpyKernel = DPCTLProgram_GetKernel(PRef, "axpy"); auto fnName1 = DPCTLKernel_GetFunctionName(AddKernel); auto fnName2 = DPCTLKernel_GetFunctionName(AxpyKernel); ASSERT_STREQ("add", fnName1); ASSERT_STREQ("axpy", fnName2); DPCTLCString_Delete(fnName1); DPCTLCString_Delete(fnName2); DPCTLQueue_Delete(QueueRef); DPCTLContext_Delete(CtxRef); DPCTLProgram_Delete(PRef); DPCTLKernel_Delete(AddKernel); DPCTLKernel_Delete(AxpyKernel); } TEST_P(TestDPCTLSyclKernelInterface, CheckGetNumArgs) { auto QueueRef = DPCTLQueue_CreateForDevice(DRef, nullptr, 0); auto CtxRef = DPCTLQueue_GetContext(QueueRef); auto PRef = DPCTLProgram_CreateFromOCLSource(CtxRef, CLProgramStr, CompileOpts); auto AddKernel = DPCTLProgram_GetKernel(PRef, "add"); auto AxpyKernel = DPCTLProgram_GetKernel(PRef, "axpy"); ASSERT_EQ(DPCTLKernel_GetNumArgs(AddKernel), 3ul); ASSERT_EQ(DPCTLKernel_GetNumArgs(AxpyKernel), 4ul); DPCTLQueue_Delete(QueueRef); DPCTLContext_Delete(CtxRef); DPCTLProgram_Delete(PRef); DPCTLKernel_Delete(AddKernel); DPCTLKernel_Delete(AxpyKernel); } INSTANTIATE_TEST_SUITE_P(TestKernelInterfaceFunctions, TestDPCTLSyclKernelInterface, ::testing::Values("opencl:gpu:0", "opencl:cpu:0"));
32.618321
80
0.668617
reazulhoque
3b9927fc8098750630ef4b9ab94e0988cfe835bc
3,350
cpp
C++
igl/grad_intrinsic.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/grad_intrinsic.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/grad_intrinsic.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2018 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "grad_intrinsic.h" #include "grad.h" template <typename Derivedl, typename DerivedF, typename Gtype> IGL_INLINE void igl::grad_intrinsic( const Eigen::MatrixBase<Derivedl>&l, const Eigen::MatrixBase<DerivedF>&F, Eigen::SparseMatrix<Gtype> &G) { assert(F.cols() ==3 && "Only triangles supported"); // number of vertices const int n = F.maxCoeff()+1; // number of faces const int m = F.rows(); // JD: There is a pretty subtle bug when using a fixed column size for this matrix. // When calling igl::grad(V, ...), the two code paths `grad_tet` and `grad_tri` // will be compiled. It turns out that `igl::grad_tet` calls `igl::volume`, which // reads the coordinates of the `V` matrix into `RowVector3d`. If the matrix `V` // has a known compile-time size of 2, this produces a compilation error when // libigl is compiled in header-only mode. In static mode this doesn't happen // because the matrix `V` is probably implicitly copied into a `Eigen::MatrixXd`. // This is a situation that could be solved using `if constexpr` in C++17. // In C++11, the alternative is to use SFINAE and `std::enable_if` (ugh). typedef Eigen::Matrix<Gtype,Eigen::Dynamic,Eigen::Dynamic> MatrixX2S; MatrixX2S V2 = MatrixX2S::Zero(3*m,2); // 1=[x,y] // /\ // l3 / \ l2 // / \ // / \ // 2-----------3 // l1 // // x = (l2²-l1²-l3²)/(-2*l1) // y = sqrt(l3² - x²) // // // Place 3rd vertex at [l(:,1) 0] V2.block(2*m,0,m,1) = l.col(0); // Place second vertex at [0 0] // Place third vertex at [x y] V2.block(0,0,m,1) = (l.col(1).cwiseAbs2()-l.col(0).cwiseAbs2()-l.col(2).cwiseAbs2()).array()/ (-2.*l.col(0)).array(); V2.block(0,1,m,1) = (l.col(2).cwiseAbs2() - V2.block(0,0,m,1).cwiseAbs2()).array().sqrt(); DerivedF F2(F.rows(),F.cols()); std::vector<Eigen::Triplet<Gtype> > Pijv; Pijv.reserve(F.size()); for(int f = 0;f<m;f++) { for(int c = 0;c<F.cols();c++) { F2(f,c) = f+c*m; Pijv.emplace_back(F2(f,c),F(f,c),1); } } Eigen::SparseMatrix<Gtype> P(m*3,n); P.setFromTriplets(Pijv.begin(),Pijv.end()); Eigen::SparseMatrix<Gtype> G2; grad(V2,F2,G2); G = G2*P; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::grad_intrinsic<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<double, 0, int>&); // generated by autoexplicit.sh template void igl::grad_intrinsic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<double, 0, int>&); #endif
42.405063
297
0.617612
sabinaRachev
3b99a4e4b231502a984dd8f0f4f67f5e803b42ec
18,365
hpp
C++
include/public/coherence/lang/MemberHolder.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/public/coherence/lang/MemberHolder.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/public/coherence/lang/MemberHolder.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_MEMBER_HOLDER_HPP #define COH_MEMBER_HOLDER_HPP #include "coherence/lang/compatibility.hpp" #include "coherence/lang/Object.hpp" #include "coherence/lang/SmartMember.hpp" #include "coherence/lang/SynchronizedMemberReadBlock.hpp" #include "coherence/lang/SynchronizedMemberWriteBlock.hpp" #include "coherence/lang/TypedHandle.hpp" #include "coherence/lang/TypedHolder.hpp" #include <ostream> COH_OPEN_NAMESPACE2(coherence,lang) /** * MemberHolder is a thread-safe handle implementation which supports * referencing Objects as either Handles or Views. MemberHolder can safely be * used in place of View but adds the ability to attempt a safe down cast to a * Handle. This differs from the C++ const_cast in that the down cast will only * succeed if the MemberHolder had been assigned from a Handle, an assignment * from a View results in a MemberHolder whose down cast operation will throw * a ClassCastException. * * MemberHolder is not for general use, instead it is a convenience handle type * which can be used for container like classes, which need to be able to * contain both Handles and Views. * * Note: In the rare case that a MemberHolder is declared via the mutable * keyword, the MemberHolder must be informed of this fact by setting * fMutable to true during construction. * * @author mf 2008.01.09 */ template<class T> class MemberHolder : public SmartMember, public ChainedHandleElement { // ----- typedefs ------------------------------------------------------- public: /** * The type of the values the holder can reference. */ typedef const T ValueType; /** * The Handle type for the referenced Object. */ typedef typename T::Handle ValueHandle; /** * The View type for the referenced Object. */ typedef typename T::View ValueView; /** * The Holder type for the referenced Object. */ typedef typename T::Holder ValueHolder; /** * Result type for a non-const get operation. */ typedef TypedHolder<T> GetType; // -------- constructors ------------------------------------------------ public: /** * Construct a new MemberHolder referencing NULL via a handle. * * @param oGuardian the object that protects this member */ MemberHolder(const Object& oGuardian) : SmartMember(oGuardian), ChainedHandleElement(/*fView*/ false), m_po(NULL) { if (oGuardian._isEscaped()) { m_prev = m_next = NULL; } } /** * Construct a new MemberHolder referencing the specified Object. * * @param oGuardian the object that protects this member * @param that the Object to reference */ MemberHolder(const Object& oGuardian, const TypedHolder<T>& that) : SmartMember(oGuardian), ChainedHandleElement(/*fView*/ false), m_po(NULL) { if (oGuardian._isEscaped()) { m_prev = m_next = NULL; } set(that); } /** * Construct a new MemberHolder referencing the specified Object. * * @param oGuardian the object that protects this member * @param that the Object to reference * @param fMutable true if the member is declared as mutable, false * if declared as const */ MemberHolder(const Object& oGuardian, const TypedHolder<T>& that, bool fMutable) : SmartMember(oGuardian), ChainedHandleElement(/*fView*/ false), m_po(NULL) { if (oGuardian._isEscaped()) { m_prev = m_next = NULL; } set(that); m_nMutability = fMutable ? forever_mutable : safe_immutable; } /** * Destroy the MemberHolder. */ ~MemberHolder() { try { m_nMutability = inherited; set(NULL); } catch (const std::exception& e) { // Exception::View is not a known type within this file std::cerr << "Error during ~MemberHolder: " << e.what() << std::endl; return; // can't re-throw from within destructor } } protected: /** * Construct a MemberHolder without any associated guardian. * * The new MemberHolder is not usable until the guardian is specified. */ MemberHolder() : SmartMember(), ChainedHandleElement(/*fView*/ false), m_po(NULL) { } private: /** * Blocked copy constructor. */ MemberHolder(const MemberHolder&); // ----- operators ------------------------------------------------------ public: /** * Assign this MemberHolder to reference the same Object (and in the * same manner) as the specified MemberHolder. * * @param that the object to reference * * @return a reference to this MemberHolder */ MemberHolder& operator=(const MemberHolder& that) { set(that); // assign from snapshot return *this; } /** * Assign this MemberHolder to reference the same Object (and in the * same manner) as the specified MemberHolder. * * @param that the object to reference * * @return a reference to this MemberHolder */ MemberHolder& operator=(const TypedHolder<T>& that) { set(that); return *this; } /** * Return a View to the referenced Object. * * @return a View to the referenced Object */ operator ValueView() const { if (m_prev == NULL) { if (m_nMutability == safe_immutable) { // safe_immutable, synchronization not required return ValueView(m_po); } else { SynchronizedMemberReadBlock::Guard guard(getGuardian()); return ValueView(m_po); // must occur in syncRead scope } } else { return TypedHandle<const T>(m_po, *this); } } /** * Return a View to the referenced Object. * * @return a View to the referenced Object */ template<class PT> operator TypedHandle<const PT>() const { return (ValueView) *this; } /** * Return a TypedHolder to the referenced Object. * * @return a TypedHolder to the referenced Object */ template<class PT> operator TypedHolder<PT>() const { return get(); } /** * Dereference the MemberHolder. * * @return a const pointer to the referenced Object */ ValueView operator->() const { return (ValueView) *this; } /** * Dereference this handle, returning <tt>T&</tt>. * * @return a raw <tt>T&</tt> reference to the referenced Object * * @throws NullPointerException if the this handle is @c NULL */ const T& operator*() const { return *get(); } // ----- SmartMember interface ------------------------------------------ protected: /** * {@inheritDoc} */ virtual void onEscape(bool fEscaped) const { T* po = m_po; if (po) { if (m_fView) { ((const T*) po)->_attach(fEscaped); } else { po->_attach(fEscaped); } } if (fEscaped) { performAction(unlink()); m_prev = m_next = NULL; } else { if (po) { if (m_fView) { ((const T*) po)->_detach(/*fEscaped*/ true); } else { po->_detach(/*fEscaped*/ true); } } m_prev = m_next = this; } SmartMember::onEscape(fEscaped); } /** * {@inheritDoc} */ virtual size64_t retained() const { TypedHolder<T> oh = get(); return oh == NULL ? 0 : oh->sizeOf(/*fDeep*/ true); } // ----- helper methods ------------------------------------------------- protected: /** * Set the Holder to reference an Object via a View. * * @param that the Object to reference * @param pSync the synch block to delegate to or NULL to create one */ void set(const TypedHolder<T>& that, SynchronizedMemberWriteBlock *pSync = NULL) { if (m_prev == NULL) { setEscaped(that, pSync); } else if (m_nMutability >= forever_immutable) { coh_throw_illegal_state("attempt to set const MemberHolder"); } else { performAction(link(that)); m_po = const_cast<T*>(that.m_cpo); m_fView = that.m_fView; } } /** * Set the escaped Holder to reference an Object via a View. * * @param that the Object to reference * @param pSync the synch block to delegate to or NULL to create one */ void setEscaped(const TypedHolder<T>& that, SynchronizedMemberWriteBlock *pSync = NULL) { const Object& oGuardian = getGuardian(); T* pNew = const_cast<T*>(that.m_cpo); bool fNewView = that.m_fView; T* pOld; bool fOldView; if (pNew != NULL) { if (fNewView) { ((const T*) pNew)->_attach(/*fEscaped*/ true); } else { pNew->_attach(/*fEscaped*/ true); } } if (pSync == NULL) { // sync block SynchronizedMemberWriteBlock::Guard guard(oGuardian); if (m_nMutability >= forever_immutable) { coh_throw_illegal_state("attempt to set const MemberHolder"); } pOld = m_po; fOldView = m_fView; m_po = pNew; m_fView = fNewView; } else { // sync block SynchronizedMemberWriteBlock syncWrite(oGuardian, pSync); if (m_nMutability >= forever_immutable) { coh_throw_illegal_state("attempt to set const MemberHolder"); } pOld = m_po; fOldView = m_fView; m_po = pNew; m_fView = fNewView; } if (pOld != NULL) { if (fOldView) { ((const T*) pOld)->_detach(/*fEscaped*/ true); } else { pOld->_detach(/*fEscaped*/ true); } } } /** * Return a TypedHolder referencing the same Object as this * MemberHolder * * @param pSync the sync block to delegate to or NULL to create one * * @return a TypedHolder referencing the same Object as this * MemberHolder */ TypedHolder<T> get(SynchronizedMemberReadBlock* pSync = NULL) const { if (m_prev == NULL) { return getEscaped(pSync); } else if (m_fView) { return TypedHandle<const T>(m_po, *this); } else { return TypedHandle<T>(m_po, *this); } } /** * Return a TypedHolder referencing the same Object as this * MemberHolder * * @param pSync the sync block to delegate to or NULL to create one * * @return a TypedHolder referencing the same Object as this * MemberHolder */ TypedHolder<T> getEscaped(SynchronizedMemberReadBlock* pSync = NULL) const { const Object& oGuardian = getGuardian(); if (pSync != NULL) { SynchronizedMemberReadBlock syncRead(oGuardian, pSync); if (m_fView) { return ValueView(m_po); // must occur in syncRead scope } return ValueHandle(m_po); // must occur in syncRead scope } else if (m_nMutability == safe_immutable) { // safe_immutable, synchronization not required if (m_fView) { return ValueView(m_po); } return ValueHandle(m_po); } else { SynchronizedMemberReadBlock::Guard guard(oGuardian); if (m_fView) { return ValueView(m_po); // must occur in syncRead scope } return ValueHandle(m_po); // must occur in syncRead scope } } /** * Perform the specified action. * * @param nAction the action to perform */ void performAction(Action nAction) const { T* po = m_po; switch (nAction) { case action_error: coh_throw_illegal_state("corrupted ChainedHandleElement"); case action_flip: if (NULL != po) ((const T*) po)->_attach(/*fEscaped*/ false); // fall through case action_detach: if (NULL != po) { if (m_fView) { ((const T*) po)->_detach(/*fEscaped*/ false); } else { po->_detach(/*fEscaped*/ false); } } // fall through case action_none: default: break; } } // ----- data members --------------------------------------------------- protected: /** * The referenced Object. */ T* m_po; // ----- friends -------------------------------------------------------- /** * @internal */ template<class> friend class Array; /** * @internal */ friend class SynchronizedMemberReadBlock; /** * @internal */ friend class SynchronizedMemberWriteBlock; }; // ----- non-member operators and functions --------------------------------- /** * Output a human-readable description of the given MemberHolder to the * specified stream. * * @param out the stream used to output the description * @param th the MemberHolder to describe * * @return the supplied stream */ template <typename Char, typename Traits, class T> COH_INLINE std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& out, const MemberHolder<T>& th) { out << (typename T::View) th; return out; } /** * Assign the specified holder to NULL. * * @param mh the holder to clear */ template<class T> void clear_handle(MemberHolder<T>& mh) { mh = NULL; } /** * Return true if the supplied holder equals NULL. * * @param mh the holder to test * * @return true iff the supplied holder equals NULL */ template<class T> bool is_null(const MemberHolder<T>& mh) { return mh == NULL; } /** * Perform a dynamic cast the pointer associated with the MemberHolder * to a the specified handle/view type. * * @param mh the MemberHolder from which to perform the cast * @param fThrow true if an exception is to be thrown on a failed cast * * @return the casted pointer, or NULL if the cast fails and fThrow is false * * @throws ClassCastException if the cast fails and fThrow is true */ template<class D, class T> D cast(const MemberHolder<T>& mh, bool fThrow = true) { return cast<D>((TypedHolder<T>) mh, fThrow); } /** * Perform an instanceof check on a handle or view. * * @param mh the MemberHolder from which to perform the test * * @return true if the supplied handle is an instance of the specified type */ template<class D, class T> bool instanceof(const MemberHolder<T>& mh) { return instanceof<D>((TypedHolder<T>) mh); } COH_CLOSE_NAMESPACE2 #endif // COH_MEMBER_HOLDER_HPP
29.290271
121
0.475306
chpatel3
3b9b986737b81383ae0ff870aae62b36e1df9a3c
1,970
cpp
C++
logdevice/server/admincommands/Setting.cpp
SimonKinds/LogDevice
fc9ac2fccb6faa3292b2b0a610a9eb77fd445824
[ "BSD-3-Clause" ]
1
2018-10-17T06:49:04.000Z
2018-10-17T06:49:04.000Z
logdevice/server/admincommands/Setting.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
logdevice/server/admincommands/Setting.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/commandline_util_chrono.h" #include "logdevice/common/debug.h" #include "logdevice/common/settings/SettingsUpdater.h" #include "logdevice/server/admincommands/Setting.h" #include "logdevice/server/ServerProcessor.h" namespace facebook { namespace logdevice { void commands::SettingSet::run() { try { server_->getSettings().setFromAdminCmd(name_, value_); out_.printf("Setting \"%s\" now set to \"%s\". " "This setting will be unset after %s.\r\n", name_.c_str(), value_.c_str(), chrono_string(ttl_).c_str()); if (name_ == "loglevel" && dbg::currentLevel >= dbg::Level::DEBUG) { out_.printf( "\r\nNOTE: debug and spew levels produce lots of output. " "If this server is under nontrivial amount of load, the log file " "will grow rapidly. Remember to switch back to a less verbose " "level when you don't need the debug level anymore:\r\n\r\n" " echo unset loglevel | nc ...\r\n\r\n"); } // Post a request to unset the setting after ttl expires. // If the request fails, do nothing std::unique_ptr<Request> req = std::make_unique<SettingOverrideTTLRequest>(ttl_, name_, server_); if (server_->getServerProcessor()->postImportant(req) != 0) { out_.printf("Failed to post SettingOverrideTTLRequest, error: %s.\r\n", error_name(err)); // also log it ld_error("Failed to post SettingOverrideTTLRequest, error: %s.", error_name(err)); return; } } catch (const boost::program_options::error& ex) { out_.printf("Error: %s.\r\n", ex.what()); } } }} // namespace facebook::logdevice
37.169811
77
0.641624
SimonKinds
3b9fe445254bf70394f25bf86cf613ca2970ddbd
17,545
cpp
C++
rose_sketch/arduino/lib/ICS/IcsServo.cpp
h7ga40/GR-ROSE-TensorFlowLite
259033510f2509a2d790c175967f235cc25c1742
[ "BSD-2-Clause" ]
null
null
null
rose_sketch/arduino/lib/ICS/IcsServo.cpp
h7ga40/GR-ROSE-TensorFlowLite
259033510f2509a2d790c175967f235cc25c1742
[ "BSD-2-Clause" ]
null
null
null
rose_sketch/arduino/lib/ICS/IcsServo.cpp
h7ga40/GR-ROSE-TensorFlowLite
259033510f2509a2d790c175967f235cc25c1742
[ "BSD-2-Clause" ]
null
null
null
// KONDO ICS Serial Servo // Based on ICS3.5 #include <stdio.h> #include <string.h> #include "IcsController.h" #include "IcsServo.h" /**************************************** Constants of ICS Protocol ****************************************/ // CMD(command) #define CMD_POSITION 0x80 // POSITION command #define CMD_READ 0xA0 // READ command #define CMD_WRITE 0xC0 // WRITE command #define CMD_ID 0xE0 // ID command #define CMD_MASK 0xE0 // bit mask of command #define ID_MASK 0x1F // bit mask of ID #define MSB_MASK 0x7F // bit mask of MSB // SC(sub command) of READ/WRITE command #define SC_EEPROM 0x00 // EEPROM #define SC_STRETCH 0x01 // stretch #define SC_SPEED 0x02 // speed #define SC_CURRENT 0x03 // current #define SC_TEMPERATURE 0x04 // temperature #define SC_POSITION 0x05 // position (read only) // SC(sub command) of ID command #define SC_READ_ID 0x00 // read ID #define SC_WRITE_ID 0x01 // write ID // verify CMD #define ICS_CMD_CHECK(rx, tx, tx_size) \ ((rx[0] == tx[0]) && ((rx[tx_size+0] & MSB_MASK) == (tx[0] & MSB_MASK))) // verify CMD (read ID command) #define ICS_CMD_GET_ID_CHECK(rx, tx, tx_size) \ ((rx[0] == tx[0]) && ((rx[tx_size+0] & CMD_MASK & MSB_MASK) == (CMD_ID & MSB_MASK))) // verify SC #define ICS_SC_CHECK(rx, tx, tx_size) \ ((rx[1] == tx[1]) && (rx[tx_size+1] == tx[1])) // verify DATA #define ICS_DATA_CHECK(rx, tx, tx_size) \ ((rx[2] == tx[2]) && (rx[tx_size+2] == tx[2])) /**************************************** Local Constants ****************************************/ // request flag bit #define REQ_POSITION 0x01 // set & get position #define REQ_CURRENT 0x02 // get current #define REQ_TEMPERATURE 0x04 // get temperature /**************************************** Common API ****************************************/ // set ICS controller and servo ID void IcsServo::attach(IcsController& controller, uint8_t id, uint8_t icsver) { this->controller = &controller; this->ID = id; this->icsver = icsver; // add this servo to servo chain if(controller.servoFirst == NULL) { controller.servoFirst = this; controller.servoLast = this; controller.servoNow = this; } else { controller.servoLast->next = this; controller.servoLast = this; } this->next = NULL; } /**************************************** Synchronous API ****************************************/ // set & get position // pos : target position // return : current position uint16_t IcsServo::setPosition(uint16_t pos) { // command data uint8_t tx_data[3]; tx_data[0] = CMD_POSITION | (ID & ID_MASK);// CMD tx_data[1] = (uint8_t)(pos >> 7) & 0x7F; // POS_H tx_data[2] = (uint8_t)(pos & 0x7F); // POS_L // send command and receive response uint8_t rx_data[3+3]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return 0xFFFF; // Error } // verify response data uint16_t retval; if(ICS_CMD_CHECK(rx_data, tx_data, 3)) // verify CMD { // current position retval = ((uint16_t)rx_data[3+1] << 7) | (uint16_t)rx_data[3+2]; }else{ retval = 0xFFFF; // Error } return retval; } // read parameter (common routine) // sc : sub command (type of parameter) // return : value of parameter uint8_t IcsServo::getParameter(uint8_t sc) { // command data uint8_t tx_data[2]; tx_data[0] = CMD_READ | (ID & ID_MASK); // CMD tx_data[1] = sc; // SC // send command and receive response uint8_t rx_data[2+3]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return 0xFF; // Error } // verify response data uint8_t retval; if( ICS_CMD_CHECK(rx_data, tx_data, 2) // verify CMD && ICS_SC_CHECK (rx_data, tx_data, 2)) // verify SC { // value of parameter retval = rx_data[2+2]; }else{ retval = 0xFF; // Error } return retval; } // get stretch // return : stretch uint8_t IcsServo::getStretch() { return this->getParameter(SC_STRETCH); } // get speed uint8_t IcsServo::getSpeed() { return this->getParameter(SC_SPEED); } // get current uint8_t IcsServo::getCurrent() { return this->getParameter(SC_CURRENT); } // get temperature uint8_t IcsServo::getTemperature() { return this->getParameter(SC_TEMPERATURE); } // get position uint16_t IcsServo::getPosition() { if(icsver >= 36) { // command data uint8_t tx_data[2]; tx_data[0] = CMD_READ | (ID & ID_MASK); // CMD tx_data[1] = SC_POSITION; // SC // send command and receive response uint8_t rx_data[2+4]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return 0xFF; // Error } // verify response data uint16_t retval; if( ICS_CMD_CHECK(rx_data, tx_data, 2) // verify CMD && ICS_SC_CHECK (rx_data, tx_data, 2)) // verify SC { // value of parameter retval = ((uint16_t)rx_data[3+1] << 7) | (uint16_t)rx_data[3+2]; }else{ retval = 0xFFFF; // Error } return retval; } else { uint16_t retval = setPosition(0); setPosition(retval); return retval; } } // write parameter (common routine) // sc : sub command (type of parameter) // value : value of parameter // return : success or failure bool IcsServo::setParameter(uint8_t sc, uint8_t value) { // command data uint8_t tx_data[3]; tx_data[0] = CMD_WRITE | (ID & ID_MASK); // CMD tx_data[1] = sc; // SC tx_data[2] = value; // value of parameter // send command and receive response uint8_t rx_data[3+3]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return false; // Error } // verify response data bool retval; if( ICS_CMD_CHECK (rx_data, tx_data, 3) // verify CMD && ICS_SC_CHECK (rx_data, tx_data, 3) // verify SC && ICS_DATA_CHECK(rx_data, tx_data, 3)) // verify DATA { retval = true; }else{ retval = false; } return retval; } // set stretch // stretch : stretch // return : success or failure bool IcsServo::setStretch(uint8_t stretch) { return this->setParameter(SC_STRETCH, stretch); } // set speed // speed : speed // return : success or failure bool IcsServo::setSpeed(uint8_t speed) { return this->setParameter(SC_SPEED, speed); } // set current limit // current : current limit // return : success or failure bool IcsServo::setCurrent(uint8_t current) { return this->setParameter(SC_CURRENT, current); } // set temperature limit // temp : temprature limit // return : success or failure bool IcsServo::setTemperature(uint8_t temp) { return this->setParameter(SC_TEMPERATURE, temp); } // read data from EEPROM // data : EEPROM data (out) // return : success or failure bool IcsServo::readEEPROM(uint8_t *data) { // command data uint8_t tx_data[2]; tx_data[0] = CMD_READ | (ID & ID_MASK); // CMD tx_data[1] = SC_EEPROM; // SC // send command and receive response uint8_t rx_data[2+66]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 10)){ return false; // Error } // verify response data bool retval; if( ICS_CMD_CHECK(rx_data, tx_data, 2) // verify CMD && ICS_SC_CHECK (rx_data, tx_data, 2)) // verify SC { // EEPROM data memcpy(data, &rx_data[2+2], 64); retval = true; }else{ retval = false; } return retval; } // write data to EEPROM // data : EEPROM data // return : success or failure bool IcsServo::writeEEPROM(uint8_t *data) { // command data uint8_t tx_data[66]; tx_data[0] = CMD_WRITE | (ID & ID_MASK); // CMD tx_data[1] = SC_EEPROM; // SC memcpy(&tx_data[2], data, 64); // send command and receive response uint8_t rx_data[66+2]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 10)){ return false; // Error } // verify response data bool retval; if( ICS_CMD_CHECK(rx_data, tx_data, 66) // verify CMD && ICS_SC_CHECK (rx_data, tx_data, 66)) // verify SC { retval = true; }else{ retval = false; } return retval; } // read servo ID // only for ONE-ON-ONE connection! // return : servo ID uint8_t IcsServo::readID() { // command data uint8_t tx_data[4]; tx_data[0] = CMD_ID; // CMD tx_data[1] = SC_READ_ID; // SC tx_data[2] = SC_READ_ID; // SC tx_data[3] = SC_READ_ID; // SC // send command and receive response uint8_t rx_data[4+1]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return 0xFF; // Error } // verify response data uint8_t retval; if(ICS_CMD_GET_ID_CHECK(rx_data, tx_data, 4)) // verify CMD { // ID retval = rx_data[4+0] & ID_MASK; }else{ retval = 0xFF; // Error } return retval; } // write servo ID // only for ONE-ON-ONE connection! // id : servo ID // return : success or failure bool IcsServo::writeID(uint8_t id) { // command data uint8_t tx_data[4]; tx_data[0] = CMD_ID | (id & ID_MASK); // CMD tx_data[1] = SC_WRITE_ID;// SC tx_data[2] = SC_WRITE_ID;// SC tx_data[3] = SC_WRITE_ID;// SC // send command and receive response uint8_t rx_data[4+1]={0}; if(!this->transfer(tx_data, sizeof(tx_data), rx_data, sizeof(rx_data), 1)){ return false; // Error } // verify response data bool retval; if(ICS_CMD_CHECK(rx_data, tx_data, 4)) // verify CMD { retval = true; }else{ retval = false; } return retval; } /**************************************** Asynchronous API ****************************************/ // request to set & get position // pos : target position void IcsServo::requestPosition(uint16_t pos) { this->error = 0; this->posTarget = pos; this->request |= REQ_POSITION; } // request to get current void IcsServo::requestCurrent() { this->error = 0; this->request |= REQ_CURRENT; } // request to get temperature void IcsServo::requestTemperature() { this->error = 0; this->request |= REQ_TEMPERATURE; } // requested communication completed? bool IcsServo::isReady() { // no more requests and not receiving? return ((this->request == 0) && !this->isReceiving); } /**************************************** Private Functions ****************************************/ // UART send / receive // tx_data: send data // tx_size: send data size // rx_data: receive data // rx_size: receive data size // timeout: time limit [ms] // return: success or failure bool IcsServo::transfer(uint8_t* tx_data, int tx_size, uint8_t* rx_data, int rx_size, int timeout) { if(controller == NULL){ setError(ERROR_UNATTACHED); return false; } // set time limit controller->setTimeout(timeout); // send command controller->write(tx_data, tx_size); // receive response bool retval = false; int rx_index = 0; while(rx_index < rx_size){ int len = controller->getRxSize(); int i; for(i=0;i<len;i++){ rx_data[rx_index] = controller->read(); rx_index++; if(rx_index >= rx_size){ retval = true; break; } } // check time limit if(controller->isTimeout()){ setError(ERROR_TIMEOUT); retval = false; break; } delayMicroseconds(1); } return retval; } #if 0 extern IcsController ics1; extern IcsController ics2; #endif // asynchronous send void IcsServo::sendAsync() { if(controller == NULL){ setError(ERROR_UNATTACHED); } int tx_size = 0; // Position if(request & REQ_POSITION){ request &= ~REQ_POSITION; commandNow = CMD_POSITION; uint16_t pos = posTarget; txData[0] = CMD_POSITION | (ID & ID_MASK);// CMD txData[1] = (uint8_t)(pos >> 7) & 0x7F; // POS_H txData[2] = (uint8_t)(pos & 0x7F); // POS_L tx_size = 3; } // Current else if(request & REQ_CURRENT){ request &= ~REQ_CURRENT; commandNow = CMD_READ; txData[0] = CMD_READ | (ID & ID_MASK); // CMD txData[1] = SC_STRETCH; // SC tx_size = 2; } // Temperature else if(request & REQ_TEMPERATURE){ request &= ~REQ_TEMPERATURE; commandNow = CMD_READ; txData[0] = CMD_READ | (ID & ID_MASK); // CMD txData[1] = SC_TEMPERATURE; // SC tx_size = 2; } // send command if(tx_size != 0) { controller->write(txData, tx_size); #if 0 if(controller == &ics1){ Serial.print("s"); }else{ Serial.print("S"); } #endif this->isReceiving = true; rxCnt = 0; // set time limit controller->setTimeout(1); } } // set error code // error : error code void IcsServo::setError(uint8_t error) { this->error = error; this->isReceiving = false; if((controller != NULL) && (controller->onError != NULL)) { controller->onError(error, ID); } } // asynchronous receive (POSITION command) void IcsServo::receivePositionAsync() { // proccess each byte of received data int len = controller->getRxSize(); int i; for(i=0;i<len;i++){ uint8_t bData = controller->read(); // receive data format switch(rxCnt) { // [0-2] loopback case 0: case 1: case 2: // verify loopback if(bData == txData[rxCnt]){ rxCnt++; }else{ setError(ERROR_VERIFY); // Error return; } break; // [3] CMD case 3: // verify CMD and ID if((bData & MSB_MASK) == (txData[0] & MSB_MASK)){ rxCnt++; }else{ setError(ERROR_VERIFY); // Error return; } break; // [4] position upper 7bit case 4: rxData[0] = bData; rxCnt++; break; // [5] position lower 7bit case 5: rxData[1] = bData; // current position position = ((uint16_t)rxData[0] << 7) | (uint16_t)rxData[1]; isReceiving = false; #if 0 if(controller == &ics1){ Serial.print("r"); }else{ Serial.print("R"); } #endif return; // success // abnormal state default: setError(ERROR_ABNORMAL); // Error return; } } } // asynchronous receive (READ command) void IcsServo::receiveReadAsync() { // proccess each byte of received data int len = controller->getRxSize(); int i; for(i=0;i<len;i++){ uint8_t bData = controller->read(); // receive data format switch(rxCnt) { // [0-1] loopback case 0: case 1: // verify loopback if(bData == txData[rxCnt]){ rxCnt++; }else{ setError(ERROR_VERIFY); // Error return; } break; // [2] CMD case 2: // verify CMD and ID if((bData & MSB_MASK) == (txData[0] & MSB_MASK)){ rxCnt++; }else{ setError(ERROR_VERIFY); // Error return; } break; // [3] SC case 3: // verify SC if(bData == txData[1]){ rxCnt++; }else{ setError(ERROR_VERIFY); // Error return; } break; // [4] DATA case 4: switch(txData[1]){ // Current case SC_CURRENT: current = bData; break; // Temperature case SC_TEMPERATURE: temperature = bData; break; } isReceiving = false; return; // success // abnormal state default: setError(ERROR_ABNORMAL); // Error return; } } } // asynchronous receive void IcsServo::receiveAsync() { if(controller == NULL){ setError(ERROR_UNATTACHED); return; } switch(commandNow) { // POSITION command case CMD_POSITION: this->receivePositionAsync(); break; // READ command case CMD_READ: this->receiveReadAsync(); break; } // check time limit if(controller->isTimeout()){ #if 0 if(controller == &ics1){ Serial.print("e"); }else{ Serial.print("E"); } #endif setError(ERROR_TIMEOUT); // Error } delayMicroseconds(1); } // ICS protocol version (used for getting position) void IcsServo::setProtcolVersion(uint8_t version){ icsver = version; }
24.607293
98
0.545683
h7ga40
3ba0f92f37beeafe101daf9808789de976cbfc28
812
cpp
C++
leetcode.com/0005 Longest Palindromic Substring/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0005 Longest Palindromic Substring/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0005 Longest Palindromic Substring/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
// O(N*N) #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string longestPalindrome(string s) { int sLen = s.length(), maxLen = 0, maxStart = 0; int i = 0, l = 0, r = 0, len = 0; while(i<sLen-maxLen/2) { l = r = i; while(r<sLen-1 && s[r+1]==s[r]) r++; i = r+1; // 牛逼 while(l>0 && r<sLen-1 && s[r+1]==s[l-1]) l--, r++; len = r-l+1; if(maxLen < len) maxLen = len, maxStart = l; } return s.substr(maxStart, maxLen); } }; int main(int argc, char const *argv[]) { Solution s; string str("abca"); // cout<<string(str.begin()+1, str.begin()+ 1 + 3)<<endl; cout<<s.longestPalindrome("abbd")<<endl; return 0; }
22.555556
62
0.488916
sky-bro
3ba2f1a1e49122cfb4e52fe42e414242e3b28b37
2,668
cpp
C++
oldlib/BBST/AVL_set.cpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
oldlib/BBST/AVL_set.cpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
oldlib/BBST/AVL_set.cpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
template<typename T> class AVL_set{ struct node; using np=node*; struct node{ T val; int cnt=1; int dep=0; np ch[2]={nullptr,nullptr}; node(T val):val(val){} }; np root=nullptr; inline int count(np t){return t?t->cnt:0;} inline int depth(np t){return t?t->dep:0;} inline np update(np& t,bool f=1){ if(!t)return t; t->cnt=count(t->ch[0])+1+count(t->ch[1]); t->dep=max(depth(t->ch[0]),depth(t->ch[1]))+1; if(f&&abs(depth(t->ch[0])-depth(t->ch[1]))==2){ rebuild(t,depth(t->ch[0])<depth(t->ch[1])); } return t; } public: AVL_set(){} inline void insert(T val){insert(val,root);} inline void erase(T val){erase(val,root);} inline int lower_bound(T val){return lower_bound(val,root);} inline int upper_bound(T val){return upper_bound(val,root);} inline int count(T val){return upper_bound(val,root)-lower_bound(val,root);} inline int size(){return count(root);} inline T find_by_order(int idx){assert(0<=idx&&idx<size());return find_by_order(idx,root);} inline T operator[](int idx){return find_by_order(idx);} private: void insert(T val,np& t){ if(!t)t=new node(val); else if(val<=t->val)insert(val,t->ch[0]); else if(val>t->val)insert(val,t->ch[1]); update(t); } void erase(T val,np& t){ if(!t)return; else if(val==t->val){ if(!t->ch[0]||!t->ch[1])t=t->ch[0]?t->ch[0]:t->ch[1]; else move_down(t->ch[0],t); } else if(val<t->val)erase(val,t->ch[0]); else if(val>t->val)erase(val,t->ch[1]); update(t); } void move_down(np& t,np& p){ if(t->ch[1])move_down(t->ch[1],p); else p->val=t->val,t=t->ch[0]; update(t); } int lower_bound(T val,np t){ if(!t)return 0; if(val<=t->val)return lower_bound(val,t->ch[0]); else return count(t->ch[0])+1+lower_bound(val,t->ch[1]); } int upper_bound(T val,np t){ if(!t)return 0; if(val<t->val)return upper_bound(val,t->ch[0]); else return count(t->ch[0])+1+upper_bound(val,t->ch[1]); } T find_by_order(int idx,np t){ if(idx==count(t->ch[0]))return t->val; else if(idx<count(t->ch[0]))return find_by_order(idx,t->ch[0]); else return find_by_order(idx-count(t->ch[0])-1,t->ch[1]); } np rot(np t){ int b=depth(t->ch[0])<depth(t->ch[1]); if(depth(t->ch[0])==depth(t->ch[1]))return t; np s=t->ch[b]; t->ch[b]=s->ch[1-b]; s->ch[1-b]=t; update(t,0);update(s,0); return s; } void rebuild(np& t,int b){ if(t->ch[b]&&depth(t->ch[b]->ch[b])<depth(t->ch[b]->ch[1-b])){ t->ch[b]=rot(t->ch[b]); } t=rot(update(t,0)); } };
31.023256
92
0.562219
hotman78
3ba580d7b5e16ca2ea04c2843780b2e5bc52ec95
17,353
cpp
C++
src/slave/containerizer/isolators/cgroups/mem.cpp
tillt/mesos
3031114c7bb93853b526fa62e4735a96bc8a9150
[ "Apache-2.0" ]
1
2015-07-18T09:47:35.000Z
2015-07-18T09:47:35.000Z
src/slave/containerizer/isolators/cgroups/mem.cpp
yuzhu/mesos-akaros
6a905943542cd93e1f71069ea6c228b7085533b7
[ "Apache-2.0" ]
1
2015-12-21T23:47:34.000Z
2015-12-21T23:47:47.000Z
src/slave/containerizer/isolators/cgroups/mem.cpp
tillt/mesos
3031114c7bb93853b526fa62e4735a96bc8a9150
[ "Apache-2.0" ]
null
null
null
/** * 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. */ #include <stdint.h> #include <vector> #include <mesos/resources.hpp> #include <mesos/values.hpp> #include <process/collect.hpp> #include <process/defer.hpp> #include <process/pid.hpp> #include <stout/bytes.hpp> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/foreach.hpp> #include <stout/hashmap.hpp> #include <stout/hashset.hpp> #include <stout/lambda.hpp> #include <stout/nothing.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "common/type_utils.hpp" #include "linux/cgroups.hpp" #include "slave/containerizer/isolators/cgroups/mem.hpp" using namespace process; using std::list; using std::ostringstream; using std::string; using std::vector; namespace mesos { namespace internal { namespace slave { template<class T> static Future<Option<T> > none() { return None(); } CgroupsMemIsolatorProcess::CgroupsMemIsolatorProcess( const Flags& _flags, const string& _hierarchy, const bool _limitSwap) : flags(_flags), hierarchy(_hierarchy), limitSwap(_limitSwap) {} CgroupsMemIsolatorProcess::~CgroupsMemIsolatorProcess() {} Try<Isolator*> CgroupsMemIsolatorProcess::create(const Flags& flags) { Try<string> hierarchy = cgroups::prepare( flags.cgroups_hierarchy, "memory", flags.cgroups_root); if (hierarchy.isError()) { return Error("Failed to create memory cgroup: " + hierarchy.error()); } // Make sure the kernel OOM-killer is enabled. // The Mesos OOM handler, as implemented, is not capable of handling // the oom condition by itself safely given the limitations Linux // imposes on this code path. Try<Nothing> enable = cgroups::memory::oom::killer::enable( hierarchy.get(), flags.cgroups_root); if (enable.isError()) { return Error(enable.error()); } // Determine whether to limit swap or not. bool limitSwap = false; if (flags.cgroups_limit_swap) { Result<Bytes> check = cgroups::memory::memsw_limit_in_bytes( hierarchy.get(), flags.cgroups_root); if (check.isError()) { return Error( "Failed to read 'memory.memsw.limit_in_bytes': " + check.error()); } else if (check.isNone()) { return Error("'memory.memsw.limit_in_bytes' is not available"); } limitSwap = true; } process::Owned<IsolatorProcess> process( new CgroupsMemIsolatorProcess(flags, hierarchy.get(), limitSwap)); return new Isolator(process); } Future<Nothing> CgroupsMemIsolatorProcess::recover( const list<state::RunState>& states) { hashset<string> cgroups; foreach (const state::RunState& state, states) { if (state.id.isNone()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure("ContainerID is required to recover"); } const ContainerID& containerId = state.id.get(); const string cgroup = path::join(flags.cgroups_root, containerId.value()); Try<bool> exists = cgroups::exists(hierarchy, cgroup); if (exists.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure("Failed to check cgroup for container '" + stringify(containerId) + "'"); } if (!exists.get()) { VLOG(1) << "Couldn't find cgroup for container " << containerId; // This may occur if the executor has exited and the isolator // has destroyed the cgroup but the slave dies before noticing // this. This will be detected when the containerizer tries to // monitor the executor's pid. continue; } infos[containerId] = new Info(containerId, cgroup); cgroups.insert(cgroup); oomListen(containerId); } Try<vector<string> > orphans = cgroups::get( hierarchy, flags.cgroups_root); if (orphans.isError()) { foreachvalue (Info* info, infos) { delete info; } infos.clear(); return Failure(orphans.error()); } foreach (const string& orphan, orphans.get()) { // Ignore the slave cgroup (see the --slave_subsystems flag). // TODO(idownes): Remove this when the cgroups layout is updated, // see MESOS-1185. if (orphan == path::join(flags.cgroups_root, "slave")) { continue; } if (!cgroups.contains(orphan)) { LOG(INFO) << "Removing orphaned cgroup '" << orphan << "'"; // We don't wait on the destroy as we don't want to block recovery. cgroups::destroy(hierarchy, orphan, cgroups::DESTROY_TIMEOUT); } } return Nothing(); } Future<Option<CommandInfo> > CgroupsMemIsolatorProcess::prepare( const ContainerID& containerId, const ExecutorInfo& executorInfo) { if (infos.contains(containerId)) { return Failure("Container has already been prepared"); } // TODO(bmahler): Don't insert into 'infos' unless we create the // cgroup successfully. It's safe for now because 'cleanup' gets // called if we return a Failure, but cleanup will fail because the // cgroup does not exist when cgroups::destroy is called. Info* info = new Info( containerId, path::join(flags.cgroups_root, containerId.value())); infos[containerId] = info; // Create a cgroup for this container. Try<bool> exists = cgroups::exists(hierarchy, info->cgroup); if (exists.isError()) { return Failure("Failed to prepare isolator: " + exists.error()); } else if (exists.get()) { return Failure("Failed to prepare isolator: cgroup already exists"); } Try<Nothing> create = cgroups::create(hierarchy, info->cgroup); if (create.isError()) { return Failure("Failed to prepare isolator: " + create.error()); } oomListen(containerId); return update(containerId, executorInfo.resources()) .then(lambda::bind(none<CommandInfo>)); } Future<Nothing> CgroupsMemIsolatorProcess::isolate( const ContainerID& containerId, pid_t pid) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); CHECK(info->pid.isNone()); info->pid = pid; Try<Nothing> assign = cgroups::assign(hierarchy, info->cgroup, pid); if (assign.isError()) { return Failure("Failed to assign container '" + stringify(info->containerId) + "' to its own cgroup '" + path::join(hierarchy, info->cgroup) + "' : " + assign.error()); } return Nothing(); } Future<Limitation> CgroupsMemIsolatorProcess::watch( const ContainerID& containerId) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } CHECK_NOTNULL(infos[containerId]); return infos[containerId]->limitation.future(); } Future<Nothing> CgroupsMemIsolatorProcess::update( const ContainerID& containerId, const Resources& resources) { if (resources.mem().isNone()) { return Failure("No memory resource given"); } if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); // New limit. Bytes mem = resources.mem().get(); Bytes limit = std::max(mem, MIN_MEMORY); // Always set the soft limit. Try<Nothing> write = cgroups::memory::soft_limit_in_bytes(hierarchy, info->cgroup, limit); if (write.isError()) { return Failure( "Failed to set 'memory.soft_limit_in_bytes': " + write.error()); } LOG(INFO) << "Updated 'memory.soft_limit_in_bytes' to " << limit << " for container " << containerId; // Read the existing limit. Bytes currentLimit; if (limitSwap) { Result<Bytes> _currentLimit = cgroups::memory::memsw_limit_in_bytes(hierarchy, info->cgroup); if (_currentLimit.isError()) { return Failure( "Failed to read 'memory.memsw.limit_in_bytes': " + _currentLimit.error()); } else if (_currentLimit.isNone()) { return Failure("'memory.memsw.limit_in_bytes' is not available"); } currentLimit = _currentLimit.get(); } else { Try<Bytes> _currentLimit = cgroups::memory::limit_in_bytes(hierarchy, info->cgroup); if (_currentLimit.isError()) { return Failure( "Failed to read 'memory.limit_in_bytes': " + _currentLimit.error()); } currentLimit = _currentLimit.get(); } // Determine whether to set the hard limit. If this is the first // time (info->pid.isNone()), or we're raising the existing limit, // then we can update the hard limit safely. Otherwise, if we need // to decrease 'memory.limit_in_bytes' we may induce an OOM if too // much memory is in use. As a result, we only update the soft limit // when the memory reservation is being reduced. This is probably // okay if the machine has available resources. // TODO(benh): Introduce a MemoryWatcherProcess which monitors the // discrepancy between usage and soft limit and introduces a "manual // oom" if necessary. if (info->pid.isNone() || limit > currentLimit) { if (limitSwap) { Try<bool> write = cgroups::memory::memsw_limit_in_bytes( hierarchy, info->cgroup, limit); if (write.isError()) { return Failure( "Failed to set 'memory.memsw.limit_in_bytes': " + write.error()); } else if (!write.get()) { return Failure("'memory.memsw.limit_in_bytes' is not available"); } LOG(INFO) << "Updated 'memory.memsw.limit_in_bytes' to " << limit << " for container " << containerId; } else { Try<Nothing> write = cgroups::memory::limit_in_bytes( hierarchy, info->cgroup, limit); if (write.isError()) { return Failure( "Failed to set 'memory.limit_in_bytes': " + write.error()); } LOG(INFO) << "Updated 'memory.limit_in_bytes' to " << limit << " for container " << containerId; } } return Nothing(); } Future<ResourceStatistics> CgroupsMemIsolatorProcess::usage( const ContainerID& containerId) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } Info* info = CHECK_NOTNULL(infos[containerId]); ResourceStatistics result; // The rss from memory.stat is wrong in two dimensions: // 1. It does not include child cgroups. // 2. It does not include any file backed pages. Try<Bytes> usage = cgroups::memory::usage_in_bytes(hierarchy, info->cgroup); if (usage.isError()) { return Failure("Failed to parse memory.usage_in_bytes: " + usage.error()); } // TODO(bmahler): Add namespacing to cgroups to enforce the expected // structure, e.g, cgroups::memory::stat. result.set_mem_rss_bytes(usage.get().bytes()); Try<hashmap<string, uint64_t> > stat = cgroups::stat(hierarchy, info->cgroup, "memory.stat"); if (stat.isError()) { return Failure("Failed to read memory.stat: " + stat.error()); } Option<uint64_t> total_cache = stat.get().get("total_cache"); if (total_cache.isSome()) { result.set_mem_file_bytes(total_cache.get()); } Option<uint64_t> total_rss = stat.get().get("total_rss"); if (total_rss.isSome()) { result.set_mem_anon_bytes(total_rss.get()); } Option<uint64_t> total_mapped_file = stat.get().get("total_mapped_file"); if (total_mapped_file.isSome()) { result.set_mem_mapped_file_bytes(total_mapped_file.get()); } return result; } Future<Nothing> CgroupsMemIsolatorProcess::cleanup( const ContainerID& containerId) { // Multiple calls may occur during test clean up. if (!infos.contains(containerId)) { VLOG(1) << "Ignoring cleanup request for unknown container: " << containerId; return Nothing(); } Info* info = CHECK_NOTNULL(infos[containerId]); if (info->oomNotifier.isPending()) { info->oomNotifier.discard(); } return cgroups::destroy(hierarchy, info->cgroup, cgroups::DESTROY_TIMEOUT) .onAny(defer(PID<CgroupsMemIsolatorProcess>(this), &CgroupsMemIsolatorProcess::_cleanup, containerId, lambda::_1)); } Future<Nothing> CgroupsMemIsolatorProcess::_cleanup( const ContainerID& containerId, const Future<Nothing>& future) { if (!infos.contains(containerId)) { return Failure("Unknown container"); } CHECK_NOTNULL(infos[containerId]); if (!future.isReady()) { return Failure("Failed to clean up container " + stringify(containerId) + " : " + (future.isFailed() ? future.failure() : "discarded")); } delete infos[containerId]; infos.erase(containerId); return Nothing(); } void CgroupsMemIsolatorProcess::oomListen( const ContainerID& containerId) { CHECK(infos.contains(containerId)); Info* info = CHECK_NOTNULL(infos[containerId]); info->oomNotifier = cgroups::memory::oom::listen(hierarchy, info->cgroup); // If the listening fails immediately, something very wrong // happened. Therefore, we report a fatal error here. if (info->oomNotifier.isFailed()) { LOG(FATAL) << "Failed to listen for OOM events for container " << containerId << ": " << info->oomNotifier.failure(); } LOG(INFO) << "Started listening for OOM events for container " << containerId; info->oomNotifier.onReady(defer( PID<CgroupsMemIsolatorProcess>(this), &CgroupsMemIsolatorProcess::oomWaited, containerId, lambda::_1)); } void CgroupsMemIsolatorProcess::oomWaited( const ContainerID& containerId, const Future<Nothing>& future) { if (future.isDiscarded()) { LOG(INFO) << "Discarded OOM notifier for container " << containerId; } else if (future.isFailed()) { LOG(ERROR) << "Listening on OOM events failed for container " << containerId << ": " << future.failure(); } else { // Out-of-memory event happened, call the handler. LOG(INFO) << "OOM notifier is triggered for container " << containerId; oom(containerId); } } void CgroupsMemIsolatorProcess::oom(const ContainerID& containerId) { if (!infos.contains(containerId)) { // It is likely that process exited is executed before this // function (e.g. The kill and OOM events happen at the same // time, and the process exit event arrives first.) Therefore, we // should not report a fatal error here. LOG(INFO) << "OOM detected for an already terminated executor"; return; } Info* info = CHECK_NOTNULL(infos[containerId]); LOG(INFO) << "OOM detected for container " << containerId; // Construct a "message" string to describe why the isolator // destroyed the executor's cgroup (in order to assist in // debugging). ostringstream message; message << "Memory limit exceeded: "; // Output the requested memory limit. if (limitSwap) { Result<Bytes> limit = cgroups::memory::memsw_limit_in_bytes(hierarchy, info->cgroup); if (limit.isError()) { LOG(ERROR) << "Failed to read 'memory.memsw.limit_in_bytes': " << limit.error(); } else if (limit.isNone()) { LOG(ERROR) << "'memory.memsw.limit_in_bytes' is not available"; } else { message << "Requested: " << limit.get() << " "; } } else { Try<Bytes> limit = cgroups::memory::limit_in_bytes(hierarchy, info->cgroup); if (limit.isError()) { LOG(ERROR) << "Failed to read 'memory.limit_in_bytes': " << limit.error(); } else { message << "Requested: " << limit.get() << " "; } } // Output the maximum memory usage. Try<Bytes> usage = cgroups::memory::max_usage_in_bytes( hierarchy, info->cgroup); if (usage.isError()) { LOG(ERROR) << "Failed to read 'memory.max_usage_in_bytes': " << usage.error(); } else { message << "Maximum Used: " << usage.get() << "\n"; } // Output 'memory.stat' of the cgroup to help with debugging. // NOTE: With Kernel OOM-killer enabled these stats may not reflect // memory state at time of OOM. Try<string> read = cgroups::read(hierarchy, info->cgroup, "memory.stat"); if (read.isError()) { LOG(ERROR) << "Failed to read 'memory.stat': " << read.error(); } else { message << "\nMEMORY STATISTICS: \n" << read.get() << "\n"; } LOG(INFO) << strings::trim(message.str()); // Trim the extra '\n' at the end. Resource mem = Resources::parse( "mem", stringify(usage.isSome() ? usage.get().bytes() : 0), "*").get(); info->limitation.set(Limitation(mem, message.str())); } } // namespace slave { } // namespace internal { } // namespace mesos {
29.511905
79
0.659079
tillt
3ba93888c98593010f148d1e15cc0a859dde5a9d
6,416
cpp
C++
videosource.cpp
bulletsk/pientertain
96f29b8d13467c89b22c862505953e2e0644451f
[ "BSD-3-Clause" ]
null
null
null
videosource.cpp
bulletsk/pientertain
96f29b8d13467c89b22c862505953e2e0644451f
[ "BSD-3-Clause" ]
null
null
null
videosource.cpp
bulletsk/pientertain
96f29b8d13467c89b22c862505953e2e0644451f
[ "BSD-3-Clause" ]
null
null
null
#include "videosource.hh" #include "videosourceimage.hh" #include "videosourceraspberrycam.hh" #include <QDebug> #include <QSettings> #include <QCoreApplication> #include <QElapsedTimer> static const int s_minArea = 5; static const int s_maxArea = 200; static const int s_minSmooth = 0; static const int s_maxSmooth = 100; static const int s_defaultAreaSize = 20; static const int s_defaultSmooth = 0; VideoSource *VideoSource::createVideoSource(const QString &identifier, VideoSourceType type) { switch (type) { case Image: return new VideoSourceImage(identifier, nullptr); case Camera: return new VideoSourceRaspberryCam(identifier, nullptr); default: break; } qDebug() << "not yet implemented"; return nullptr; } VideoSource::VideoSource(const QString &sourceIdentifier, QObject *parent) : QThread(parent), m_identifier(sourceIdentifier), m_requestExit(false), m_areaSize(s_defaultAreaSize), m_smoothCount(s_defaultSmooth) { readSettings(); } int VideoSource::area() const { return m_areaSize; } int VideoSource::smooth() const { return m_smoothCount; } VideoSource::~VideoSource() { writeSettings(); if (isRunning()) { stop(); } } void VideoSource::readSettings() { QSettings settings(QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName()); settings.beginGroup("processing"); m_areaSize = settings.value("area", s_defaultAreaSize).toInt(); m_smoothCount = settings.value("smooth", s_defaultSmooth).toInt(); m_settings["area"] = m_areaSize; m_settings["smooth"] = m_smoothCount; settings.endGroup(); QVector<QPoint> corners; settings.beginGroup("corners"); for (int i=1;i<=4;i++) { QPoint p = settings.value("point"+QString::number(i), QPoint(-1,-1)).toPoint(); if ( p.x() < 0) { corners.clear(); break; } corners.append(p); } settings.endGroup(); if (corners.size() == 4) { setCorners(corners); } } void VideoSource::writeSettings() { QSettings settings(QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName()); settings.beginGroup("processing"); settings.setValue("area", m_areaSize); settings.setValue("smooth", m_smoothCount); settings.endGroup(); if (m_corners.size() != 4) { return; } settings.beginGroup("corners"); for (int i=1;i<=4;i++) { settings.setValue("point"+QString::number(i), m_corners[i-1]); } settings.endGroup(); } void VideoSource::stop() { m_requestExit = true; wait(); } QVector<QPoint> VideoSource::corners() const { return m_corners; } void VideoSource::setCorners( const QVector<QPoint> &corners) { if (corners.size()!=4) { return; } m_corners = corners; m_measurePoints.clear(); m_measurePoints << m_corners[CCTopLeft] << m_corners[CCTopLeft] + ((m_corners[CCTopRight] - m_corners[CCTopLeft])/2) << m_corners[CCTopRight] << m_corners[CCTopLeft] + ((m_corners[CCBottomLeft] - m_corners[CCTopLeft])/2) << m_corners[CCTopLeft] + ((m_corners[CCBottomRight] - m_corners[CCTopLeft])/2) << m_corners[CCTopRight] + ((m_corners[CCBottomRight] - m_corners[CCTopRight])/2) << m_corners[CCBottomLeft] << m_corners[CCBottomLeft] + ((m_corners[CCBottomRight] - m_corners[CCBottomLeft])/2) << m_corners[CCBottomRight]; } void VideoSource::setCameraSettings (const QJsonObject &json ) { if (json.contains("area")) { int value = qBound(s_minArea, json.value("area").toInt(), s_maxArea); m_settings["area"] = value; m_areaSize = value; } if (json.contains("smooth")) { int value = qBound(s_minSmooth, json.value("smooth").toInt(), s_maxSmooth); m_settings["smooth"] = value; m_smoothCount = value; } } void VideoSource::onRequestImage() { m_imageLock.lock(); m_latestImage = m_currentImage; m_imageLock.unlock(); emit latestImage(m_latestImage); } void VideoSource::run() { emit cornersChanged(m_corners); emit cameraSettingsChanged(m_settings); m_colors.resize(static_cast<int>(CornerLast)); QElapsedTimer frameRateTimer; int frameRateCounter = 0; frameRateTimer.start(); bool ok = initialize(); if (ok) { emit statusChanged("initialized", false); } if (!ok) { emit statusChanged("initialization failed", true); } while (!m_requestExit) { m_imageLock.lock(); nextImage(); m_imageLock.unlock(); calculateColors(); emit newColors(m_colors); frameRateCounter++; if (frameRateCounter==100) { quint64 msecs = frameRateTimer.restart(); QString fpsMessage = QString::number( (1000.0f / (msecs/100.0f)), 'g', 4) + " fps"; frameRateCounter = 0; emit statusChanged( fpsMessage, false ); } } m_requestExit = false; ok = shutdown(); if (ok) { emit statusChanged("stopped", false); } else { emit statusChanged("shutdown failed", true); } } void VideoSource::calculateColors() { if (m_currentImage.isNull()) { return; } if (m_corners.size() != 4) { QVector<QPoint> defaultCorners; defaultCorners.append( QPoint(0,0) ); defaultCorners.append( QPoint( m_currentImage.width()-1, 0) ); defaultCorners.append( QPoint( 0, m_currentImage.height()-1) ); defaultCorners.append( QPoint( m_currentImage.width()-1, m_currentImage.height()-1) ); setCorners(defaultCorners); } if (m_currentImage.format() != QImage::Format_RGB888) { qDebug() << "format not rgb888"; return; } int corner = 0; const int areaSize = area(); const int width = m_currentImage.width(); const int height = m_currentImage.height(); const unsigned char *data = m_currentImage.constBits(); for (QPoint point : qAsConst(m_measurePoints)) { const int xl = qMax(0, point.x()-areaSize); const int yl = qMax(0, point.y()-areaSize); const int xr = qMin(width, point.x()+areaSize); const int yr = qMin(height, point.y()+areaSize); int num = 0; int r = 0; int g = 0; int b = 0; int idx; for (int y=yl;y<yr;y++) { for (int x=xl;x<xr;x++) { idx = (y*width+x)*3; r += static_cast<int>(data[idx+0]); g += static_cast<int>(data[idx+1]); b += static_cast<int>(data[idx+2]); ++num; } } if (num > 0) { r /= num; g /= num; b /= num; } m_colors[corner] = QColor(r,g,b); ++corner; } }
24.676923
209
0.662251
bulletsk
3baa9a73ca36b841fca71531d2526543986bc046
1,311
cpp
C++
I2C/I2CDev.cpp
jwolf02/libdriver
e83992ab3e83e2d58f59b021926f6e947ac20897
[ "MIT" ]
null
null
null
I2C/I2CDev.cpp
jwolf02/libdriver
e83992ab3e83e2d58f59b021926f6e947ac20897
[ "MIT" ]
null
null
null
I2C/I2CDev.cpp
jwolf02/libdriver
e83992ab3e83e2d58f59b021926f6e947ac20897
[ "MIT" ]
null
null
null
#include <I2CDev.hpp> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <linux/i2c-dev.h> #include <common.hpp> const std::string I2CDev::DEFAULT_NAME = "/dev/i2c-1"; I2CDev::I2CDev(const std::string &devname, int address) { open(devname, address); } I2CDev::~I2CDev() { close(); } void I2CDev::open(const std::string &devname, int address) { _fd = ::open(devname.c_str(), O_RDWR); if (_fd >= 0) { _addr = address; if (ioctl(_fd, I2C_SLAVE, address) < 0) { ERROR; } } } bool I2CDev::isOpen() const { return _fd > 0; } bool I2CDev::operator!() const { return isOpen(); } void I2CDev::close() { if (isOpen()) { ::close(_fd); _fd = 0; } } void I2CDev::read(void *buf, size_t n) { if (::read(_fd, buf, n) < (ssize_t) n) { ERROR; } } void I2CDev::read(std::string &str, size_t n) { if (str.size() < n) { str.resize(n); } read(const_cast<char*>(str.data()), n); } void I2CDev::write(const void *buf, size_t n) { if (::write(_fd, buf, n) < (ssize_t) n) { ERROR; } } void I2CDev::write(const std::string &str, size_t n) { write(str.c_str(), n != 0 ? n : str.size()); } int I2CDev::address() const { return _addr; }
18.728571
60
0.561404
jwolf02
3bab3143caf3d6293adb586e53216c7a80453d9e
31,173
hpp
C++
include/integratorxx/deprecated/lebedev/lebedev_266.hpp
evaleev/IntegratorXX
70339ca2d8f753e477dffb64788913c1bc12b519
[ "BSD-3-Clause" ]
null
null
null
include/integratorxx/deprecated/lebedev/lebedev_266.hpp
evaleev/IntegratorXX
70339ca2d8f753e477dffb64788913c1bc12b519
[ "BSD-3-Clause" ]
null
null
null
include/integratorxx/deprecated/lebedev/lebedev_266.hpp
evaleev/IntegratorXX
70339ca2d8f753e477dffb64788913c1bc12b519
[ "BSD-3-Clause" ]
3
2019-05-09T21:02:21.000Z
2021-03-04T21:34:35.000Z
namespace IntegratorXX::deprecated { namespace LebedevGrids { /** * \brief Lebedev-Laikov Quadrature specification for Order = 266 * */ template <typename T> struct lebedev_266 { static constexpr std::array<cartesian_pt_t<T>,266> points = { 1.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, -1.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, 1.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, -1.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, 1.000000000000000e+00, 0.000000000000000e+00, 0.000000000000000e+00, -1.000000000000000e+00, 0.000000000000000e+00, 7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, 7.071067811865476e-01, -7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, -7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, 7.071067811865476e-01, -7.071067811865476e-01, 0.000000000000000e+00, 7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, -7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, 7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, 7.071067811865476e-01, 0.000000000000000e+00, 7.071067811865476e-01, -7.071067811865476e-01, 0.000000000000000e+00, -7.071067811865476e-01, -7.071067811865476e-01, 0.000000000000000e+00, 5.773502691896257e-01, 5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, 5.773502691896257e-01, 5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, 5.773502691896257e-01, 5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, 5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, -5.773502691896257e-01, 7.039373391585475e-01, 7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, 7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, 7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, 7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, 7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, 7.039373391585475e-01, 9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, 7.039373391585475e-01, -7.039373391585475e-01, 9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, -9.457507640371310e-02, -7.039373391585475e-01, -7.039373391585475e-01, 1.012526248572414e-01, 1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, 1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, 1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, 1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, 1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, 1.012526248572414e-01, 9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, 1.012526248572414e-01, -1.012526248572414e-01, 9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, -9.896948074629054e-01, -1.012526248572414e-01, -1.012526248572414e-01, 4.647448726420539e-01, 4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, 4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, 4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, 4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, 4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, 4.647448726420539e-01, 7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, 4.647448726420539e-01, -4.647448726420539e-01, 7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, -7.536739392508157e-01, -4.647448726420539e-01, -4.647448726420539e-01, 3.277420654971629e-01, 3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, 3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, 3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, 3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, 3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, 3.277420654971629e-01, 8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, 3.277420654971629e-01, -3.277420654971629e-01, 8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, -8.860983449974991e-01, -3.277420654971629e-01, -3.277420654971629e-01, 6.620338663699974e-01, 6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, 6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, 6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, 6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, 6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, 6.620338663699974e-01, 3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, 6.620338663699974e-01, -6.620338663699974e-01, 3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, -3.513151285646334e-01, -6.620338663699974e-01, -6.620338663699974e-01, 8.506508083520399e-01, 5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, 5.257311121191337e-01, 0.000000000000000e+00, 8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, 5.257311121191337e-01, 8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, 8.506508083520399e-01, 0.000000000000000e+00, 5.257311121191337e-01, -8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, -8.506508083520399e-01, 0.000000000000000e+00, 8.506508083520399e-01, 0.000000000000000e+00, 5.257311121191337e-01, -8.506508083520399e-01, 0.000000000000000e+00, 5.257311121191337e-01, 8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, -8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, 5.257311121191337e-01, 0.000000000000000e+00, 8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, 8.506508083520399e-01, 5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, 0.000000000000000e+00, 8.506508083520399e-01, 5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, 5.257311121191337e-01, 0.000000000000000e+00, 8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, -8.506508083520399e-01, -5.257311121191337e-01, 0.000000000000000e+00, 5.257311121191337e-01, 8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, 8.506508083520399e-01, 0.000000000000000e+00, 5.257311121191337e-01, -8.506508083520399e-01, 0.000000000000000e+00, -5.257311121191337e-01, -8.506508083520399e-01, 3.233484542692899e-01, 1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, 1.153112011009701e-01, 9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, 3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, 9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, 9.392279297499158e-01, 1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, 3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, 1.153112011009701e-01, 3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, 3.233484542692899e-01, 9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, 9.392279297499158e-01, 1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, 9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, 3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, 1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, 9.392279297499158e-01, 3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, 1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, 1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, 1.153112011009701e-01, 9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, 3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, -9.392279297499158e-01, -3.233484542692899e-01, -1.153112011009701e-01, 9.392279297499158e-01, 1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, 3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, 3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, 3.233484542692899e-01, 9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, 1.153112011009701e-01, -3.233484542692899e-01, 9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, -9.392279297499158e-01, -1.153112011009701e-01, -3.233484542692899e-01, 2.314790158712601e-01, 5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, 5.244939240922365e-01, 8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, 2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, 8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, 8.193433888191203e-01, 5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, 2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, 5.244939240922365e-01, 2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, 2.314790158712601e-01, 8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01, 8.193433888191203e-01, 5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, 8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, 2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, 5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, 8.193433888191203e-01, 2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, 5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, 5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, 5.244939240922365e-01, 8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, 2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, -8.193433888191203e-01, -2.314790158712601e-01, -5.244939240922365e-01, 8.193433888191203e-01, 5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, 2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, 2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, 2.314790158712601e-01, 8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, 5.244939240922365e-01, -2.314790158712601e-01, 8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01, -8.193433888191203e-01, -5.244939240922365e-01, -2.314790158712601e-01 }; static constexpr std::array<T,266> weights = { -1.313769127326952e-03, -1.313769127326952e-03, -1.313769127326952e-03, -1.313769127326952e-03, -1.313769127326952e-03, -1.313769127326952e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, -2.522728704859336e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 4.186853881700583e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 5.315167977810885e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.047142377086219e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 4.112482394406990e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 3.595584899758782e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.256131351428158e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.229582700647240e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.080914225780505e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03, 4.071467593830964e-03 }; }; }; }
56.472826
84
0.655535
evaleev
3bb01ab833d6e10dd860d94800fe384865ee0ada
5,905
cpp
C++
OrionUO/Managers/ColorManager.cpp
SirGlorg/OrionUO
42209bd144392fddff9e910562ccec1bf5704049
[ "MIT" ]
1
2019-04-27T22:20:34.000Z
2019-04-27T22:20:34.000Z
OrionUO/Managers/ColorManager.cpp
SirGlorg/OrionUO
42209bd144392fddff9e910562ccec1bf5704049
[ "MIT" ]
1
2018-12-28T13:45:08.000Z
2018-12-28T13:45:08.000Z
OrionUO/Managers/ColorManager.cpp
heppcatt/Siebenwind-Beta-Client
ba25683f37f9bb7496d12aa2b2117cba397370e2
[ "MIT" ]
null
null
null
// MIT License // Copyright (C) August 2016 Hotride CColorManager g_ColorManager; CColorManager::CColorManager() : m_HuesCount(0) { } CColorManager::~CColorManager() { } void CColorManager::Init() { DEBUG_TRACE_FUNCTION; intptr_t addr = (intptr_t)g_FileManager.m_HuesMul.Start; size_t size = g_FileManager.m_HuesMul.Size; if (addr > 0 && size > 0 && addr != -1 && size != -1) { size_t entryCount = size / sizeof(HUES_GROUP); m_HuesCount = (int)entryCount * 8; m_HuesRange.resize(entryCount); memcpy(&m_HuesRange[0], (void *)addr, entryCount * sizeof(HUES_GROUP)); } else { m_HuesCount = 0; } if (g_FileManager.m_RadarcolMul.Size != 0u) { m_Radarcol.resize(g_FileManager.m_RadarcolMul.Size / 2); memcpy( &m_Radarcol[0], (void *)g_FileManager.m_RadarcolMul.Start, g_FileManager.m_RadarcolMul.Size); } } void CColorManager::SetHuesBlock(int index, VERDATA_HUES_GROUP *group) { DEBUG_TRACE_FUNCTION; if (index < 0 || index >= m_HuesCount) { return; } m_HuesRange[index].Header = group->Header; for (int i = 0; i < 8; i++) { memcpy( &m_HuesRange[index].Entries[i].ColorTable[0], &group->Entries[i].ColorTable[0], sizeof(uint16_t[32])); } } void CColorManager::CreateHuesPalette() { DEBUG_TRACE_FUNCTION; m_HuesFloat.resize(m_HuesCount); int entryCount = m_HuesCount / 8; for (int i = 0; i < entryCount; i++) { for (int j = 0; j < 8; j++) { FLOAT_HUES &fh = m_HuesFloat[(i * 8) + j]; for (int h = 0; h < 32; h++) { int idx = (int)h * 3; uint16_t c = m_HuesRange[i].Entries[j].ColorTable[h]; fh.Palette[idx] = (((c >> 10) & 0x1F) / 31.0f); fh.Palette[idx + 1] = (((c >> 5) & 0x1F) / 31.0f); fh.Palette[idx + 2] = ((c & 0x1F) / 31.0f); } } } } void CColorManager::SendColorsToShader(uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0) { if ((color & SPECTRAL_COLOR_FLAG) != 0) { glUniform1fv(ShaderColorTable, 32 * 3, &m_HuesFloat[0].Palette[0]); } else { if (color >= m_HuesCount) { color %= m_HuesCount; if (color == 0u) { color = 1; } } glUniform1fv(ShaderColorTable, 32 * 3, &m_HuesFloat[color - 1].Palette[0]); } } } uint32_t CColorManager::Color16To32(uint16_t c) { const uint8_t table[32] = { 0x00, 0x08, 0x10, 0x18, 0x20, 0x29, 0x31, 0x39, 0x41, 0x4A, 0x52, 0x5A, 0x62, 0x6A, 0x73, 0x7B, 0x83, 0x8B, 0x94, 0x9C, 0xA4, 0xAC, 0xB4, 0xBD, 0xC5, 0xCD, 0xD5, 0xDE, 0xE6, 0xEE, 0xF6, 0xFF }; return (table[(c >> 10) & 0x1F] | (table[(c >> 5) & 0x1F] << 8) | (table[c & 0x1F] << 16)); /*return ( (((c >> 10) & 0x1F) * 0xFF / 0x1F) | ((((c >> 5) & 0x1F) * 0xFF / 0x1F) << 8) | (((c & 0x1F) * 0xFF / 0x1F) << 16) );*/ } uint16_t CColorManager::Color32To16(int c) { return (((c & 0xFF) * 32) / 256) | (((((c >> 16) & 0xff) * 32) / 256) << 10) | (((((c >> 8) & 0xff) * 32) / 256) << 5); } uint16_t CColorManager::ConvertToGray(uint16_t c) { return ((c & 0x1F) * 299 + ((c >> 5) & 0x1F) * 587 + ((c >> 10) & 0x1F) * 114) / 1000; } uint16_t CColorManager::GetColor16(uint16_t c, uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0 && color < m_HuesCount) { color -= 1; int g = color / 8; int e = color % 8; return m_HuesRange[g].Entries[e].ColorTable[(c >> 10) & 0x1F]; } return c; } uint16_t CColorManager::GetRadarColorData(int c) { DEBUG_TRACE_FUNCTION; if (c < (int)m_Radarcol.size()) { return m_Radarcol[c]; } return 0; } uint32_t CColorManager::GetPolygoneColor(uint16_t c, uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0 && color < m_HuesCount) { color -= 1; int g = color / 8; int e = color % 8; return Color16To32(m_HuesRange[g].Entries[e].ColorTable[c]); } return 0xFF010101; //Black } uint32_t CColorManager::GetUnicodeFontColor(uint16_t &c, uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0 && color < m_HuesCount) { color -= 1; int g = color / 8; int e = color % 8; return Color16To32(m_HuesRange[g].Entries[e].ColorTable[8]); } return Color16To32(c); } uint32_t CColorManager::GetColor(uint16_t &c, uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0 && color < m_HuesCount) { color -= 1; int g = color / 8; int e = color % 8; return Color16To32(m_HuesRange[g].Entries[e].ColorTable[(c >> 10) & 0x1F]); } return Color16To32(c); } uint32_t CColorManager::GetPartialHueColor(uint16_t &c, uint16_t color) { DEBUG_TRACE_FUNCTION; if (color != 0 && color < m_HuesCount) { color -= 1; int g = color / 8; int e = color % 8; uint32_t cl = Color16To32(c); if (ToColorR(cl) == ToColorG(cl) && ToColorB(cl) == ToColorG(cl)) { return Color16To32(m_HuesRange[g].Entries[e].ColorTable[(c >> 10) & 0x1F]); } return cl; } return Color16To32(c); } uint16_t CColorManager::FixColor(uint16_t color, uint16_t defaultColor) { uint16_t fixedColor = color & 0x3FFF; if (fixedColor != 0u) { if (fixedColor >= 0x0BB8) { fixedColor = 1; } fixedColor |= (color & 0xC000); } else { fixedColor = defaultColor; } return fixedColor; }
23.156863
97
0.535986
SirGlorg